diff --git a/__tests__/readConfig.test.ts b/__tests__/readConfig.test.ts index 5846637..088133d 100644 --- a/__tests__/readConfig.test.ts +++ b/__tests__/readConfig.test.ts @@ -1,13 +1,19 @@ import * as fs from 'fs'; import { readConfig, readJSONSync } from '../src/readConfig'; -jest.mock('fs', () => ({ - existsSync: jest.fn(), - readFileSync: jest.fn(), - promises: { - access: jest.fn() - } -})); +jest.mock('fs', () => { + const actualFs = jest.requireActual('fs'); + return { + ...actualFs, + existsSync: jest.fn(), + readFileSync: jest.fn(), + promises: { + ...actualFs.promises, + access: jest.fn() + } + }; +}); + jest.mock('@actions/core'); describe('readJSONSync', () => { diff --git a/dist/index.js b/dist/index.js index 943bc84..c6435e0 100644 --- a/dist/index.js +++ b/dist/index.js @@ -112,28 +112,3063 @@ function getReportFooter() { /***/ }), -/***/ 93562: +/***/ 73765: /***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => { "use strict"; -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "O": () => (/* binding */ duplicatedCheck) -/* harmony export */ }); -/* unused harmony export REPORT_ARTIFACT_NAME */ -/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(42186); -/* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(_actions_core__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(95438); -/* harmony import */ var _actions_github__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(_actions_github__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(57147); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__nccwpck_require__.n(fs__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var jscpd__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(84849); -/* harmony import */ var jscpd__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__nccwpck_require__.n(jscpd__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(73837); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__nccwpck_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(86979); -/* harmony import */ var _execute__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(3532); -/* harmony import */ var _git__WEBPACK_IMPORTED_MODULE_7__ = __nccwpck_require__(63350); -/* harmony import */ var _readConfig__WEBPACK_IMPORTED_MODULE_8__ = __nccwpck_require__(22094); + +// EXPORTS +__nccwpck_require__.d(__webpack_exports__, { + "O": () => (/* binding */ duplicatedCheck) +}); + +// UNUSED EXPORTS: REPORT_ARTIFACT_NAME + +// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js +var core = __nccwpck_require__(42186); +// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js +var github = __nccwpck_require__(95438); +// EXTERNAL MODULE: external "fs" +var external_fs_ = __nccwpck_require__(57147); +// EXTERNAL MODULE: ./node_modules/eventemitter3/index.js +var eventemitter3 = __nccwpck_require__(11848); +;// CONCATENATED MODULE: ./node_modules/eventemitter3/index.mjs + + + +/* harmony default export */ const node_modules_eventemitter3 = (eventemitter3); + +;// CONCATENATED MODULE: ./node_modules/@jscpd/core/dist/index.mjs +// src/validators/lines-length-clone.validator.ts +var LinesLengthCloneValidator = class { + validate(clone, options) { + const lines = clone.duplicationA.end.line - clone.duplicationA.start.line; + const status = lines >= Number(options?.minLines); + return { + status, + message: status ? ["ok"] : [`Lines of code less than limit (${lines} < ${options.minLines})`] + }; + } +}; + +// src/validators/validator.ts +function runCloneValidators(clone, options, validators) { + return validators.reduce((acc, validator) => { + const res = validator.validate(clone, options); + return { + ...acc, + status: res.status && acc.status, + message: res.message ? [...acc.message, ...res.message] : acc.message + }; + }, { status: true, message: [], clone }); +} + +// src/rabin-karp.ts +var RabinKarp = class _RabinKarp { + constructor(options, eventEmitter, cloneValidators) { + this.options = options; + this.eventEmitter = eventEmitter; + this.cloneValidators = cloneValidators; + } + async run(tokenMap, store) { + return new Promise((resolve) => { + let mapFrameInStore; + let clone = null; + const clones = []; + const loop = () => { + const iteration = tokenMap.next(); + store.get(iteration.value.id).then( + (mapFrameFromStore) => { + mapFrameInStore = mapFrameFromStore; + if (!clone) { + clone = _RabinKarp.createClone(tokenMap.getFormat(), iteration.value, mapFrameInStore); + } + }, + () => { + if (clone && this.validate(clone)) { + clones.push(clone); + } + clone = null; + if (iteration.value.id) { + return store.set(iteration.value.id, iteration.value); + } + } + ).finally(() => { + if (!iteration.done) { + if (clone) { + clone = _RabinKarp.enlargeClone(clone, iteration.value, mapFrameInStore); + } + loop(); + } else { + resolve(clones); + } + }); + }; + loop(); + }); + } + validate(clone) { + const validation = runCloneValidators(clone, this.options, this.cloneValidators); + if (validation.status) { + this.eventEmitter.emit("CLONE_FOUND", { clone }); + } else { + this.eventEmitter.emit("CLONE_SKIPPED", { clone, validation }); + } + return validation.status; + } + static createClone(format, mapFrameA, mapFrameB) { + return { + format, + foundDate: (/* @__PURE__ */ new Date()).getTime(), + duplicationA: { + sourceId: mapFrameA.sourceId, + start: mapFrameA?.start?.loc?.start, + end: mapFrameA?.end?.loc?.end, + range: [mapFrameA.start.range[0], mapFrameA.end.range[1]] + }, + duplicationB: { + sourceId: mapFrameB.sourceId, + start: mapFrameB?.start?.loc?.start, + end: mapFrameB?.end?.loc?.end, + range: [mapFrameB.start.range[0], mapFrameB.end.range[1]] + } + }; + } + static enlargeClone(clone, mapFrameA, mapFrameB) { + clone.duplicationA.range[1] = mapFrameA.end.range[1]; + clone.duplicationA.end = mapFrameA?.end?.loc?.end; + clone.duplicationB.range[1] = mapFrameB.end.range[1]; + clone.duplicationB.end = mapFrameB?.end?.loc?.end; + return clone; + } +}; + +// src/mode.ts +function strict(token) { + return token.type !== "ignore"; +} +function mild(token) { + return strict(token) && token.type !== "empty" && token.type !== "new_line"; +} +function weak(token) { + return mild(token) && token.format !== "comment" && token.type !== "comment" && token.type !== "block-comment"; +} +var MODES = { + mild, + strict, + weak +}; +function getModeByName(name) { + if (name in MODES) { + return MODES[name]; + } + throw new Error(`Mode ${name} does not supported yet.`); +} +function getModeHandler(mode) { + return typeof mode === "string" ? getModeByName(mode) : mode; +} + +// src/detector.ts + +var Detector = class extends node_modules_eventemitter3 { + constructor(tokenizer, store, cloneValidators = [], options) { + super(); + this.tokenizer = tokenizer; + this.store = store; + this.cloneValidators = cloneValidators; + this.options = options; + this.initCloneValidators(); + this.algorithm = new RabinKarp(this.options, this, this.cloneValidators); + this.options.minTokens = this.options.minTokens || 50; + this.options.maxLines = this.options.maxLines || 500; + this.options.minLines = this.options.minLines || 5; + this.options.mode = this.options.mode || mild; + } + algorithm; + async detect(id, text, format) { + const tokenMaps = this.tokenizer.generateMaps(id, text, format, this.options); + this.store.namespace(format); + const detect = async (tokenMap, clones) => { + if (tokenMap) { + this.emit("START_DETECTION", { source: tokenMap }); + return this.algorithm.run(tokenMap, this.store).then((clns) => { + clones.push(...clns); + const nextTokenMap = tokenMaps.pop(); + if (nextTokenMap) { + return detect(nextTokenMap, clones); + } else { + return clones; + } + }); + } + }; + const currentTokensMap = tokenMaps.pop(); + return currentTokensMap ? detect(currentTokensMap, []) : []; + } + initCloneValidators() { + if (this.options.minLines || this.options.maxLines) { + this.cloneValidators.push(new LinesLengthCloneValidator()); + } + } +}; + +// src/options.ts +function getDefaultOptions() { + return { + executionId: (/* @__PURE__ */ new Date()).toISOString(), + path: [process.cwd()], + mode: getModeHandler("mild"), + minLines: 5, + maxLines: 1e3, + maxSize: "100kb", + minTokens: 50, + output: "./report", + reporters: ["console"], + ignore: [], + threshold: void 0, + formatsExts: {}, + debug: false, + silent: false, + blame: false, + cache: true, + absolute: false, + noSymlinks: false, + skipLocal: false, + ignoreCase: false, + gitignore: false, + reportersOptions: {}, + exitCode: 0 + }; +} +function getOption(name, options) { + const defaultOptions = getDefaultOptions(); + return options ? options[name] || defaultOptions[name] : defaultOptions[name]; +} + +// src/statistic.ts +var Statistic = class _Statistic { + static getDefaultStatistic() { + return { + lines: 0, + tokens: 0, + sources: 0, + clones: 0, + duplicatedLines: 0, + duplicatedTokens: 0, + percentage: 0, + percentageTokens: 0, + newDuplicatedLines: 0, + newClones: 0 + }; + } + statistic = { + detectionDate: (/* @__PURE__ */ new Date()).toISOString(), + formats: {}, + total: _Statistic.getDefaultStatistic() + }; + subscribe() { + return { + CLONE_FOUND: this.cloneFound.bind(this), + START_DETECTION: this.matchSource.bind(this) + }; + } + getStatistic() { + return this.statistic; + } + cloneFound(payload) { + const { clone } = payload; + const id = clone.duplicationA.sourceId; + const id2 = clone.duplicationB.sourceId; + const linesCount = clone.duplicationA.end.line - clone.duplicationA.start.line; + const duplicatedTokens = clone.duplicationA.end.position - clone.duplicationA.start.position; + this.statistic.total.clones++; + this.statistic.total.duplicatedLines += linesCount; + this.statistic.total.duplicatedTokens += duplicatedTokens; + this.statistic.formats[clone.format].total.clones++; + this.statistic.formats[clone.format].total.duplicatedLines += linesCount; + this.statistic.formats[clone.format].total.duplicatedTokens += duplicatedTokens; + this.statistic.formats[clone.format].sources[id].clones++; + this.statistic.formats[clone.format].sources[id].duplicatedLines += linesCount; + this.statistic.formats[clone.format].sources[id].duplicatedTokens += duplicatedTokens; + this.statistic.formats[clone.format].sources[id2].clones++; + this.statistic.formats[clone.format].sources[id2].duplicatedLines += linesCount; + this.statistic.formats[clone.format].sources[id2].duplicatedTokens += duplicatedTokens; + this.updatePercentage(clone.format); + } + matchSource(payload) { + const { source } = payload; + const format = source.getFormat(); + if (!(format in this.statistic.formats)) { + this.statistic.formats[format] = { + sources: {}, + total: _Statistic.getDefaultStatistic() + }; + } + this.statistic.total.sources++; + this.statistic.total.lines += source.getLinesCount(); + this.statistic.total.tokens += source.getTokensCount(); + this.statistic.formats[format].total.sources++; + this.statistic.formats[format].total.lines += source.getLinesCount(); + this.statistic.formats[format].total.tokens += source.getTokensCount(); + this.statistic.formats[format].sources[source.getId()] = this.statistic.formats[format].sources[source.getId()] || _Statistic.getDefaultStatistic(); + this.statistic.formats[format].sources[source.getId()].sources = 1; + this.statistic.formats[format].sources[source.getId()].lines += source.getLinesCount(); + this.statistic.formats[format].sources[source.getId()].tokens += source.getTokensCount(); + this.updatePercentage(format); + } + updatePercentage(format) { + this.statistic.total.percentage = _Statistic.calculatePercentage( + this.statistic.total.lines, + this.statistic.total.duplicatedLines + ); + this.statistic.total.percentageTokens = _Statistic.calculatePercentage( + this.statistic.total.tokens, + this.statistic.total.duplicatedTokens + ); + this.statistic.formats[format].total.percentage = _Statistic.calculatePercentage( + this.statistic.formats[format].total.lines, + this.statistic.formats[format].total.duplicatedLines + ); + this.statistic.formats[format].total.percentageTokens = _Statistic.calculatePercentage( + this.statistic.formats[format].total.tokens, + this.statistic.formats[format].total.duplicatedTokens + ); + Object.entries(this.statistic.formats[format].sources).forEach(([id, stat]) => { + this.statistic.formats[format].sources[id].percentage = _Statistic.calculatePercentage( + stat.lines, + stat.duplicatedLines + ); + this.statistic.formats[format].sources[id].percentageTokens = _Statistic.calculatePercentage( + stat.tokens, + stat.duplicatedTokens + ); + }); + } + static calculatePercentage(total, cloned) { + return total ? Math.round(1e4 * cloned / total) / 100 : 0; + } +}; + +// src/store/memory.ts +var MemoryStore = class { + _namespace = ""; + values = {}; + namespace(namespace) { + this._namespace = namespace; + this.values[namespace] = this.values[namespace] || {}; + } + get(key) { + return new Promise((resolve, reject) => { + if (key in this.values[this._namespace]) { + resolve(this.values[this._namespace][key]); + } else { + reject(new Error("not found")); + } + }); + } + set(key, value) { + this.values[this._namespace][key] = value; + return Promise.resolve(value); + } + close() { + this.values = {}; + } +}; + +//# sourceMappingURL=index.mjs.map +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?colors/safe +var safe = __nccwpck_require__(75381); +// EXTERNAL MODULE: ./node_modules/reprism/lib/index.js +var lib = __nccwpck_require__(18042); +// EXTERNAL MODULE: external "path" +var external_path_ = __nccwpck_require__(71017); +// EXTERNAL MODULE: ./node_modules/spark-md5/spark-md5.js +var spark_md5 = __nccwpck_require__(70220); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/abap +var abap = __nccwpck_require__(30062); +var abap_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(abap, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/actionscript +var actionscript = __nccwpck_require__(28965); +var actionscript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(actionscript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/ada +var ada = __nccwpck_require__(59576); +var ada_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(ada, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/apacheconf +var apacheconf = __nccwpck_require__(94764); +var apacheconf_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(apacheconf, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/apl +var apl = __nccwpck_require__(37789); +var apl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(apl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/applescript +var applescript = __nccwpck_require__(70432); +var applescript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(applescript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/arff +var arff = __nccwpck_require__(24411); +var arff_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(arff, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/asciidoc +var asciidoc = __nccwpck_require__(89194); +var asciidoc_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(asciidoc, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/asm6502 +var asm6502 = __nccwpck_require__(29512); +var asm6502_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(asm6502, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/aspnet +var aspnet = __nccwpck_require__(10187); +var aspnet_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(aspnet, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/autohotkey +var autohotkey = __nccwpck_require__(33617); +var autohotkey_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(autohotkey, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/autoit +var autoit = __nccwpck_require__(53533); +var autoit_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(autoit, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/bash +var bash = __nccwpck_require__(63443); +var bash_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(bash, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/basic +var basic = __nccwpck_require__(38426); +var basic_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(basic, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/batch +var batch = __nccwpck_require__(76079); +var batch_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(batch, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/brainfuck +var brainfuck = __nccwpck_require__(23610); +var brainfuck_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(brainfuck, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/bro +var bro = __nccwpck_require__(84799); +var bro_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(bro, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/c +var c = __nccwpck_require__(17236); +var c_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(c, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/clike +var clike = __nccwpck_require__(11884); +var clike_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(clike, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/clojure +var clojure = __nccwpck_require__(58413); +var clojure_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(clojure, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/coffeescript +var coffeescript = __nccwpck_require__(66304); +var coffeescript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(coffeescript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/cpp +var cpp = __nccwpck_require__(7212); +var cpp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(cpp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/csharp +var csharp = __nccwpck_require__(9400); +var csharp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(csharp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/csp +var csp = __nccwpck_require__(22120); +var csp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(csp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/css-extras +var css_extras = __nccwpck_require__(63292); +var css_extras_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(css_extras, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/css +var css = __nccwpck_require__(34610); +var css_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(css, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/d +var d = __nccwpck_require__(69753); +var d_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(d, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/dart +var dart = __nccwpck_require__(36099); +var dart_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(dart, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/diff +var diff = __nccwpck_require__(41086); +var diff_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(diff, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/django +var django = __nccwpck_require__(84313); +var django_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(django, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/docker +var docker = __nccwpck_require__(82528); +var docker_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(docker, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/eiffel +var eiffel = __nccwpck_require__(86391); +var eiffel_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(eiffel, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/elixir +var elixir = __nccwpck_require__(40273); +var elixir_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(elixir, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/erlang +var erlang = __nccwpck_require__(57012); +var erlang_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(erlang, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/flow +var flow = __nccwpck_require__(11390); +var flow_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(flow, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/fortran +var fortran = __nccwpck_require__(30202); +var fortran_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(fortran, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/fsharp +var fsharp = __nccwpck_require__(34788); +var fsharp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(fsharp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/gedcom +var gedcom = __nccwpck_require__(50679); +var gedcom_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(gedcom, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/gherkin +var gherkin = __nccwpck_require__(10052); +var gherkin_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(gherkin, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/git +var git = __nccwpck_require__(79066); +var git_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(git, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/glsl +var glsl = __nccwpck_require__(86333); +var glsl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(glsl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/go +var go = __nccwpck_require__(18125); +var go_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(go, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/graphql +var graphql = __nccwpck_require__(29790); +var graphql_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(graphql, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/groovy +var groovy = __nccwpck_require__(80607); +var groovy_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(groovy, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/haml +var haml = __nccwpck_require__(76058); +var haml_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(haml, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/handlebars +var handlebars = __nccwpck_require__(24667); +var handlebars_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(handlebars, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/haskell +var haskell = __nccwpck_require__(83604); +var haskell_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(haskell, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/haxe +var haxe = __nccwpck_require__(66545); +var haxe_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(haxe, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/hpkp +var hpkp = __nccwpck_require__(27707); +var hpkp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(hpkp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/hsts +var hsts = __nccwpck_require__(43010); +var hsts_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(hsts, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/http +var http = __nccwpck_require__(99920); +var http_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(http, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/ichigojam +var ichigojam = __nccwpck_require__(4487); +var ichigojam_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(ichigojam, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/icon +var icon = __nccwpck_require__(23558); +var icon_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(icon, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/inform7 +var inform7 = __nccwpck_require__(79357); +var inform7_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(inform7, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/ini +var ini = __nccwpck_require__(70653); +var ini_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(ini, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/io +var io = __nccwpck_require__(66177); +var io_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(io, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/j +var j = __nccwpck_require__(95580); +var j_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(j, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/java +var java = __nccwpck_require__(56957); +var java_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(java, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/javascript +var javascript = __nccwpck_require__(46510); +var javascript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(javascript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/jolie +var jolie = __nccwpck_require__(52956); +var jolie_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(jolie, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/json +var json = __nccwpck_require__(71104); +var json_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(json, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/jsx +var jsx = __nccwpck_require__(86052); +var jsx_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(jsx, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/julia +var julia = __nccwpck_require__(32074); +var julia_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(julia, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/keyman +var keyman = __nccwpck_require__(35960); +var keyman_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(keyman, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/kotlin +var kotlin = __nccwpck_require__(43355); +var kotlin_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(kotlin, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/latex +var latex = __nccwpck_require__(71094); +var latex_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(latex, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/less +var less = __nccwpck_require__(28782); +var less_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(less, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/liquid +var liquid = __nccwpck_require__(24763); +var liquid_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(liquid, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/lisp +var lisp = __nccwpck_require__(906); +var lisp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(lisp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/livescript +var livescript = __nccwpck_require__(39317); +var livescript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(livescript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/lolcode +var lolcode = __nccwpck_require__(37565); +var lolcode_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(lolcode, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/lua +var lua = __nccwpck_require__(32369); +var lua_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(lua, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/makefile +var makefile = __nccwpck_require__(99559); +var makefile_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(makefile, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/markdown +var markdown = __nccwpck_require__(50671); +var markdown_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(markdown, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/markup-templating +var markup_templating = __nccwpck_require__(25481); +var markup_templating_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(markup_templating, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/markup +var markup = __nccwpck_require__(29767); +var markup_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(markup, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/matlab +var matlab = __nccwpck_require__(51375); +var matlab_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(matlab, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/mel +var mel = __nccwpck_require__(46870); +var mel_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(mel, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/mizar +var mizar = __nccwpck_require__(32950); +var mizar_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(mizar, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/monkey +var monkey = __nccwpck_require__(65487); +var monkey_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(monkey, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/n4js +var n4js = __nccwpck_require__(3993); +var n4js_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(n4js, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/nasm +var nasm = __nccwpck_require__(42947); +var nasm_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(nasm, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/nginx +var nginx = __nccwpck_require__(40947); +var nginx_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(nginx, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/nim +var nim = __nccwpck_require__(60276); +var nim_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(nim, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/nix +var nix = __nccwpck_require__(54421); +var nix_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(nix, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/nsis +var nsis = __nccwpck_require__(49752); +var nsis_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(nsis, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/objectivec +var objectivec = __nccwpck_require__(90301); +var objectivec_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(objectivec, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/ocaml +var ocaml = __nccwpck_require__(51689); +var ocaml_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(ocaml, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/opencl +var opencl = __nccwpck_require__(70078); +var opencl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(opencl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/oz +var oz = __nccwpck_require__(34039); +var oz_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(oz, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/parigp +var parigp = __nccwpck_require__(50490); +var parigp_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(parigp, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/parser +var parser = __nccwpck_require__(91454); +var parser_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(parser, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/pascal +var pascal = __nccwpck_require__(72122); +var pascal_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(pascal, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/perl +var perl = __nccwpck_require__(44169); +var perl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(perl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/php-extras +var php_extras = __nccwpck_require__(89565); +var php_extras_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(php_extras, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/php +var php = __nccwpck_require__(48121); +var php_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(php, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/powershell +var powershell = __nccwpck_require__(55283); +var powershell_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(powershell, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/processing +var processing = __nccwpck_require__(20846); +var processing_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(processing, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/prolog +var prolog = __nccwpck_require__(66647); +var prolog_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(prolog, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/properties +var properties = __nccwpck_require__(58618); +var properties_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(properties, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/protobuf +var protobuf = __nccwpck_require__(35887); +var protobuf_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(protobuf, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/pug +var pug = __nccwpck_require__(65378); +var pug_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(pug, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/puppet +var puppet = __nccwpck_require__(31293); +var puppet_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(puppet, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/pure +var pure = __nccwpck_require__(84519); +var pure_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(pure, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/python +var python = __nccwpck_require__(89022); +var python_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(python, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/q +var q = __nccwpck_require__(12783); +var q_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(q, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/qore +var qore = __nccwpck_require__(18167); +var qore_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(qore, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/r +var r = __nccwpck_require__(47761); +var r_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(r, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/reason +var reason = __nccwpck_require__(32777); +var reason_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(reason, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/renpy +var renpy = __nccwpck_require__(89096); +var renpy_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(renpy, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/rest +var rest = __nccwpck_require__(78772); +var rest_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(rest, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/rip +var rip = __nccwpck_require__(17910); +var rip_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(rip, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/roboconf +var roboconf = __nccwpck_require__(72825); +var roboconf_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(roboconf, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/ruby +var ruby = __nccwpck_require__(49147); +var ruby_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(ruby, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/rust +var rust = __nccwpck_require__(58634); +var rust_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(rust, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/sas +var sas = __nccwpck_require__(11854); +var sas_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(sas, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/sass +var sass = __nccwpck_require__(68825); +var sass_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(sass, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/scala +var scala = __nccwpck_require__(42604); +var scala_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(scala, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/scheme +var scheme = __nccwpck_require__(74656); +var scheme_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(scheme, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/scss +var scss = __nccwpck_require__(53823); +var scss_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(scss, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/smalltalk +var smalltalk = __nccwpck_require__(99657); +var smalltalk_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(smalltalk, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/smarty +var smarty = __nccwpck_require__(6218); +var smarty_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(smarty, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/soy +var soy = __nccwpck_require__(66154); +var soy_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(soy, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/stylus +var stylus = __nccwpck_require__(89796); +var stylus_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(stylus, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/swift +var swift = __nccwpck_require__(33773); +var swift_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(swift, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/tcl +var tcl = __nccwpck_require__(94492); +var tcl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(tcl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/textile +var textile = __nccwpck_require__(63291); +var textile_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(textile, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/tsx +var tsx = __nccwpck_require__(80047); +var tsx_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(tsx, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/twig +var twig = __nccwpck_require__(9962); +var twig_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(twig, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/typescript +var typescript = __nccwpck_require__(98381); +var typescript_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(typescript, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/vbnet +var vbnet = __nccwpck_require__(80219); +var vbnet_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(vbnet, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/velocity +var velocity = __nccwpck_require__(23716); +var velocity_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(velocity, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/verilog +var verilog = __nccwpck_require__(55790); +var verilog_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(verilog, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/vhdl +var vhdl = __nccwpck_require__(60368); +var vhdl_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(vhdl, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/vim +var vim = __nccwpck_require__(65969); +var vim_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(vim, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/visual-basic +var visual_basic = __nccwpck_require__(99880); +var visual_basic_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(visual_basic, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/wasm +var wasm = __nccwpck_require__(99898); +var wasm_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(wasm, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/wiki +var wiki = __nccwpck_require__(73237); +var wiki_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(wiki, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/xeora +var xeora = __nccwpck_require__(58553); +var xeora_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(xeora, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/xojo +var xojo = __nccwpck_require__(33994); +var xojo_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(xojo, 2); +// EXTERNAL MODULE: ./node_modules/@vercel/ncc/dist/ncc/@@notfound.js?reprism/languages/yaml +var yaml = __nccwpck_require__(54129); +var yaml_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(yaml, 2); +;// CONCATENATED MODULE: ./node_modules/@jscpd/tokenizer/dist/index.mjs +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// src/tokenize.ts + + +// src/formats.ts + +var FORMATS = { + abap: { + exts: [] + }, + actionscript: { + exts: ["as"] + }, + ada: { + exts: ["ada"] + }, + apacheconf: { + exts: [] + }, + apl: { + exts: ["apl"] + }, + applescript: { + exts: [] + }, + arduino: { + exts: [] + }, + arff: { + exts: [] + }, + asciidoc: { + exts: [] + }, + asm6502: { + exts: [] + }, + aspnet: { + exts: ["asp", "aspx"] + }, + autohotkey: { + exts: [] + }, + autoit: { + exts: [] + }, + bash: { + exts: ["sh", "ksh", "bash"] + }, + basic: { + exts: ["bas"] + }, + batch: { + exts: [] + }, + bison: { + exts: [] + }, + brainfuck: { + exts: ["b", "bf"] + }, + bro: { + exts: [] + }, + c: { + exts: ["c", "z80"] + }, + "c-header": { + exts: ["h"], + parent: "c" + }, + clike: { + exts: [] + }, + clojure: { + exts: ["cljs", "clj", "cljc", "cljx", "edn"] + }, + coffeescript: { + exts: ["coffee"] + }, + comments: { + exts: [] + }, + cpp: { + exts: ["cpp", "c++", "cc", "cxx"] + }, + "cpp-header": { + exts: ["hpp", "h++", "hh", "hxx"], + parent: "cpp" + }, + crystal: { + exts: ["cr"] + }, + csharp: { + exts: ["cs"] + }, + csp: { + exts: [] + }, + "css-extras": { + exts: [] + }, + css: { + exts: ["css", "gss"] + }, + d: { + exts: ["d"] + }, + dart: { + exts: ["dart"] + }, + diff: { + exts: ["diff", "patch"] + }, + django: { + exts: [] + }, + docker: { + exts: [] + }, + eiffel: { + exts: ["e"] + }, + elixir: { + exts: [] + }, + elm: { + exts: ["elm"] + }, + erb: { + exts: [] + }, + erlang: { + exts: ["erl", "erlang"] + }, + flow: { + exts: [] + }, + fortran: { + exts: ["f", "for", "f77", "f90"] + }, + fsharp: { + exts: ["fs"] + }, + gedcom: { + exts: [] + }, + gherkin: { + exts: ["feature"] + }, + git: { + exts: [] + }, + glsl: { + exts: [] + }, + go: { + exts: ["go"] + }, + graphql: { + exts: ["graphql"] + }, + groovy: { + exts: ["groovy", "gradle"] + }, + haml: { + exts: ["haml"] + }, + handlebars: { + exts: ["hb", "hbs", "handlebars"] + }, + haskell: { + exts: ["hs", "lhs "] + }, + haxe: { + exts: ["hx", "hxml"] + }, + hpkp: { + exts: [] + }, + hsts: { + exts: [] + }, + http: { + exts: [] + }, + ichigojam: { + exts: [] + }, + icon: { + exts: [] + }, + inform7: { + exts: [] + }, + ini: { + exts: ["ini"] + }, + io: { + exts: [] + }, + j: { + exts: [] + }, + java: { + exts: ["java"] + }, + javascript: { + exts: ["js", "es", "es6", "mjs", "cjs"] + }, + jolie: { + exts: [] + }, + json: { + exts: ["json", "map", "jsonld"] + }, + jsx: { + exts: ["jsx"] + }, + julia: { + exts: ["jl"] + }, + keymap: { + exts: [] + }, + kotlin: { + exts: ["kt", "kts"] + }, + latex: { + exts: ["tex"] + }, + less: { + exts: ["less"] + }, + liquid: { + exts: [] + }, + lisp: { + exts: ["cl", "lisp", "el"] + }, + livescript: { + exts: ["ls"] + }, + lolcode: { + exts: [] + }, + lua: { + exts: ["lua"] + }, + makefile: { + exts: [] + }, + markdown: { + exts: ["md", "markdown", "mkd", "txt"] + }, + markup: { + exts: ["html", "htm", "xml", "xsl", "xslt", "svg", "vue", "ejs", "jsp"] + }, + matlab: { + exts: [] + }, + mel: { + exts: [] + }, + mizar: { + exts: [] + }, + monkey: { + exts: [] + }, + n4js: { + exts: [] + }, + nasm: { + exts: [] + }, + nginx: { + exts: [] + }, + nim: { + exts: [] + }, + nix: { + exts: [] + }, + nsis: { + exts: ["nsh", "nsi"] + }, + objectivec: { + exts: ["m", "mm"] + }, + ocaml: { + exts: ["ocaml", "ml", "mli", "mll", "mly"] + }, + opencl: { + exts: [] + }, + oz: { + exts: ["oz"] + }, + parigp: { + exts: [] + }, + pascal: { + exts: ["pas", "p"] + }, + perl: { + exts: ["pl", "pm"] + }, + php: { + exts: ["php", "phtml"] + }, + plsql: { + exts: ["plsql"] + }, + powershell: { + exts: ["ps1", "psd1", "psm1"] + }, + processing: { + exts: [] + }, + prolog: { + exts: ["pro"] + }, + properties: { + exts: ["properties"] + }, + protobuf: { + exts: ["proto"] + }, + pug: { + exts: ["pug", "jade"] + }, + puppet: { + exts: ["pp", "puppet"] + }, + pure: { + exts: [] + }, + python: { + exts: ["py", "pyx", "pxd", "pxi"] + }, + q: { + exts: ["q"] + }, + qore: { + exts: [] + }, + r: { + exts: ["r", "R"] + }, + reason: { + exts: [] + }, + renpy: { + exts: [] + }, + rest: { + exts: [] + }, + rip: { + exts: [] + }, + roboconf: { + exts: [] + }, + ruby: { + exts: ["rb"] + }, + rust: { + exts: ["rs"] + }, + sas: { + exts: ["sas"] + }, + sass: { + exts: ["sass"] + }, + scala: { + exts: ["scala"] + }, + scheme: { + exts: ["scm", "ss"] + }, + scss: { + exts: ["scss"] + }, + smalltalk: { + exts: ["st"] + }, + smarty: { + exts: ["smarty", "tpl"] + }, + soy: { + exts: ["soy"] + }, + sql: { + exts: ["sql", "cql"] + }, + stylus: { + exts: ["styl", "stylus"] + }, + swift: { + exts: ["swift"] + }, + tap: { + exts: ["tap"] + }, + tcl: { + exts: ["tcl"] + }, + textile: { + exts: ["textile"] + }, + tsx: { + exts: ["tsx"] + }, + tt2: { + exts: ["tt2"] + }, + twig: { + exts: ["twig"] + }, + typescript: { + exts: ["ts", "mts", "cts"] + }, + vbnet: { + exts: ["vb"] + }, + velocity: { + exts: ["vtl"] + }, + verilog: { + exts: ["v"] + }, + vhdl: { + exts: ["vhd", "vhdl"] + }, + vim: { + exts: [] + }, + "visual-basic": { + exts: ["vb"] + }, + wasm: { + exts: [] + }, + url: { + exts: [] + }, + wiki: { + exts: [] + }, + xeora: { + exts: [] + }, + xojo: { + exts: [] + }, + xquery: { + exts: ["xy", "xquery"] + }, + yaml: { + exts: ["yaml", "yml"] + } +}; +function getSupportedFormats() { + return Object.keys(FORMATS).filter((name) => name !== "important" && name !== "url"); +} +function getFormatByFile(path, formatsExts) { + const ext = (0,external_path_.extname)(path).slice(1); + if (formatsExts && Object.keys(formatsExts).length) { + return Object.keys(formatsExts).find((format) => formatsExts[format]?.includes(ext)); + } + return Object.keys(FORMATS).find((language) => FORMATS[language]?.exts.includes(ext)); +} + +// src/hash.ts + +function hash(value) { + return spark_md5.hash(value); +} + +// src/token-map.ts +var TOKEN_HASH_LENGTH = 20; +function createTokenHash(token, hashFunction = void 0) { + return hashFunction ? hashFunction(token.type + token.value).substr(0, TOKEN_HASH_LENGTH) : hash(token.type + token.value).substr(0, TOKEN_HASH_LENGTH); +} +function groupByFormat(tokens) { + const result = {}; + tokens.forEach((token) => { + result[token.format] = result[token.format] ? [...result[token.format], token] : [token]; + }); + return result; +} +var TokensMap = class { + constructor(id, data, tokens, format, options) { + this.id = id; + this.data = data; + this.tokens = tokens; + this.format = format; + this.options = options; + this.hashMap = this.tokens.map((token) => { + if (options.ignoreCase) { + token.value = token.value.toLocaleLowerCase(); + } + return createTokenHash(token, this.options.hashFunction); + }).join(""); + } + position = 0; + hashMap; + getTokensCount() { + return this.tokens[this.tokens.length - 1].loc.end.position - this.tokens[0].loc.start.position; + } + getId() { + return this.id; + } + getLinesCount() { + return this.tokens[this.tokens.length - 1].loc.end.line - this.tokens[0].loc.start.line; + } + getFormat() { + return this.format; + } + [Symbol.iterator]() { + return this; + } + next() { + const hashFunction = this.options.hashFunction ? this.options.hashFunction : hash; + const mapFrame = hashFunction( + this.hashMap.substring( + this.position * TOKEN_HASH_LENGTH, + this.position * TOKEN_HASH_LENGTH + this.options.minTokens * TOKEN_HASH_LENGTH + ) + ).substring(0, TOKEN_HASH_LENGTH); + if (this.position < this.tokens.length - this.options.minTokens) { + this.position++; + return { + done: false, + value: { + id: mapFrame, + sourceId: this.getId(), + start: this.tokens[this.position - 1], + end: this.tokens[this.position + this.options.minTokens - 1] + } + }; + } else { + return { + done: true, + value: false + }; + } + } +}; +function generateMapsForFormats(id, data, tokens, options) { + return Object.values(groupByFormat(tokens)).map((formatTokens) => new TokensMap(id, data, formatTokens, formatTokens[0].format, options)); +} +function createTokensMaps(id, data, tokens, options) { + return generateMapsForFormats(id, data, tokens, options); +} + +// src/grammar-loader.ts + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// src/languages/tap.ts +var tap_exports = {}; +__export(tap_exports, { + default: () => tap_default +}); +var grammar = { + language: "tap", + init(Prism) { + Prism.languages.tap = { + fail: /not ok[^#{\n\r]*/, + pass: /ok[^#{\n\r]*/, + pragma: /pragma [+-][a-z]+/, + bailout: /bail out!.*/i, + version: /TAP version \d+/i, + plan: /\d+\.\.\d+(?: +#.*)?/, + subtest: { + pattern: /# Subtest(?:: .*)?/, + greedy: true + }, + punctuation: /[{}]/, + directive: /#.*/, + yamlish: { + pattern: /(^[ \t]*)---[\s\S]*?[\r\n][ \t]*\.\.\.$/m, + lookbehind: true, + inside: Prism.languages.yaml, + alias: "language-yaml" + } + }; + } +}; +var tap_default = grammar; + +// src/languages/sql.ts +var sql_exports = {}; +__export(sql_exports, { + default: () => sql_default +}); +var grammar2 = { + language: "sql", + init(Prism) { + Prism.languages.sql = { + "comment": { + pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/, + lookbehind: true + }, + "variable": [ + { + pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/, + greedy: true + }, + /@[\w.$]+/ + ], + "string": { + pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/, + greedy: true, + lookbehind: true + }, + "function": /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, + // Should we highlight user defined functions too? + "keyword": /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i, + "boolean": /\b(?:TRUE|FALSE|NULL)\b/i, + "number": /\b0x[\da-f]+\b|\b\d+\.?\d*|\B\.\d+\b/i, + "operator": /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i, + "punctuation": /[;[\]()`,.]/ + }; + } +}; +var sql_default = grammar2; + +// src/languages/plsql.ts +var plsql_exports = {}; +__export(plsql_exports, { + default: () => plsql_default +}); +var grammar3 = { + language: "plsql", + init(Prism) { + Prism.languages.plsql = Prism.languages.extend("sql", { + comment: [/\/\*[\s\S]*?\*\//, /--.*/] + }); + if (Prism.util.type(Prism.languages.plsql.keyword) !== "Array") { + Prism.languages.plsql.keyword = [Prism.languages.plsql.keyword]; + } + Prism.languages.plsql.keyword.unshift(/\b(?:ACCESS|AGENT|AGGREGATE|ARRAY|ARROW|AT|ATTRIBUTE|AUDIT|AUTHID|BFILE_BASE|BLOB_BASE|BLOCK|BODY|BOTH|BOUND|BYTE|CALLING|CHAR_BASE|CHARSET(?:FORM|ID)|CLOB_BASE|COLAUTH|COLLECT|CLUSTERS?|COMPILED|COMPRESS|CONSTANT|CONSTRUCTOR|CONTEXT|CRASH|CUSTOMDATUM|DANGLING|DATE_BASE|DEFINE|DETERMINISTIC|DURATION|ELEMENT|EMPTY|EXCEPTIONS?|EXCLUSIVE|EXTERNAL|FINAL|FORALL|FORM|FOUND|GENERAL|HEAP|HIDDEN|IDENTIFIED|IMMEDIATE|INCLUDING|INCREMENT|INDICATOR|INDEXES|INDICES|INFINITE|INITIAL|ISOPEN|INSTANTIABLE|INTERFACE|INVALIDATE|JAVA|LARGE|LEADING|LENGTH|LIBRARY|LIKE[24C]|LIMITED|LONG|LOOP|MAP|MAXEXTENTS|MAXLEN|MEMBER|MINUS|MLSLABEL|MULTISET|NAME|NAN|NATIVE|NEW|NOAUDIT|NOCOMPRESS|NOCOPY|NOTFOUND|NOWAIT|NUMBER(?:_BASE)?|OBJECT|OCI(?:COLL|DATE|DATETIME|DURATION|INTERVAL|LOBLOCATOR|NUMBER|RAW|REF|REFCURSOR|ROWID|STRING|TYPE)|OFFLINE|ONLINE|ONLY|OPAQUE|OPERATOR|ORACLE|ORADATA|ORGANIZATION|ORL(?:ANY|VARY)|OTHERS|OVERLAPS|OVERRIDING|PACKAGE|PARALLEL_ENABLE|PARAMETERS?|PASCAL|PCTFREE|PIPE(?:LINED)?|PRAGMA|PRIOR|PRIVATE|RAISE|RANGE|RAW|RECORD|REF|REFERENCE|REM|REMAINDER|RESULT|RESOURCE|RETURNING|REVERSE|ROW(?:ID|NUM|TYPE)|SAMPLE|SB[124]|SEGMENT|SELF|SEPARATE|SEQUENCE|SHORT|SIZE(?:_T)?|SPARSE|SQL(?:CODE|DATA|NAME|STATE)|STANDARD|STATIC|STDDEV|STORED|STRING|STRUCT|STYLE|SUBMULTISET|SUBPARTITION|SUBSTITUTABLE|SUBTYPE|SUCCESSFUL|SYNONYM|SYSDATE|TABAUTH|TDO|THE|TIMEZONE_(?:ABBR|HOUR|MINUTE|REGION)|TRAILING|TRANSAC(?:TIONAL)?|TRUSTED|UB[124]|UID|UNDER|UNTRUSTED|VALIDATE|VALIST|VARCHAR2|VARIABLE|VARIANCE|VARRAY|VIEWS|VOID|WHENEVER|WRAPPED|ZONE)\b/i); + if (Prism.util.type(Prism.languages.plsql.operator) !== "Array") { + Prism.languages.plsql.operator = [Prism.languages.plsql.operator]; + } + Prism.languages.plsql.operator.unshift(/:=/); + } +}; +var plsql_default = grammar3; + +// src/grammar-loader.ts +var languages = { + abap: abap_namespaceObject, + actionscript: actionscript_namespaceObject, + ada: ada_namespaceObject, + apacheconf: apacheconf_namespaceObject, + apl: apl_namespaceObject, + applescript: applescript_namespaceObject, + arff: arff_namespaceObject, + asciidoc: asciidoc_namespaceObject, + asm6502: asm6502_namespaceObject, + aspnet: aspnet_namespaceObject, + autohotkey: autohotkey_namespaceObject, + autoit: autoit_namespaceObject, + bash: bash_namespaceObject, + basic: basic_namespaceObject, + batch: batch_namespaceObject, + brainfuck: brainfuck_namespaceObject, + bro: bro_namespaceObject, + c: c_namespaceObject, + clike: clike_namespaceObject, + clojure: clojure_namespaceObject, + coffeescript: coffeescript_namespaceObject, + cpp: cpp_namespaceObject, + csharp: csharp_namespaceObject, + csp: csp_namespaceObject, + cssExtras: css_extras_namespaceObject, + css: css_namespaceObject, + d: d_namespaceObject, + dart: dart_namespaceObject, + diff: diff_namespaceObject, + django: django_namespaceObject, + docker: docker_namespaceObject, + eiffel: eiffel_namespaceObject, + elixir: elixir_namespaceObject, + erlang: erlang_namespaceObject, + flow: flow_namespaceObject, + fortran: fortran_namespaceObject, + fsharp: fsharp_namespaceObject, + gedcom: gedcom_namespaceObject, + gherkin: gherkin_namespaceObject, + git: git_namespaceObject, + glsl: glsl_namespaceObject, + go: go_namespaceObject, + graphql: graphql_namespaceObject, + groovy: groovy_namespaceObject, + haml: haml_namespaceObject, + handlebars: handlebars_namespaceObject, + haskell: haskell_namespaceObject, + haxe: haxe_namespaceObject, + hpkp: hpkp_namespaceObject, + hsts: hsts_namespaceObject, + http: http_namespaceObject, + ichigojam: ichigojam_namespaceObject, + icon: icon_namespaceObject, + inform7: inform7_namespaceObject, + ini: ini_namespaceObject, + io: io_namespaceObject, + j: j_namespaceObject, + java: java_namespaceObject, + javascript: javascript_namespaceObject, + jolie: jolie_namespaceObject, + json: json_namespaceObject, + jsx: jsx_namespaceObject, + julia: julia_namespaceObject, + keyman: keyman_namespaceObject, + kotlin: kotlin_namespaceObject, + latex: latex_namespaceObject, + less: less_namespaceObject, + liquid: liquid_namespaceObject, + lisp: lisp_namespaceObject, + livescript: livescript_namespaceObject, + lolcode: lolcode_namespaceObject, + lua: lua_namespaceObject, + makefile: makefile_namespaceObject, + markdown: markdown_namespaceObject, + markupTemplating: markup_templating_namespaceObject, + markup: markup_namespaceObject, + matlab: matlab_namespaceObject, + mel: mel_namespaceObject, + mizar: mizar_namespaceObject, + monkey: monkey_namespaceObject, + n4js: n4js_namespaceObject, + nasm: nasm_namespaceObject, + nginx: nginx_namespaceObject, + nim: nim_namespaceObject, + nix: nix_namespaceObject, + nsis: nsis_namespaceObject, + objectivec: objectivec_namespaceObject, + ocaml: ocaml_namespaceObject, + opencl: opencl_namespaceObject, + oz: oz_namespaceObject, + parigp: parigp_namespaceObject, + parser: parser_namespaceObject, + pascal: pascal_namespaceObject, + perl: perl_namespaceObject, + php: php_namespaceObject, + phpExtras: php_extras_namespaceObject, + powershell: powershell_namespaceObject, + processing: processing_namespaceObject, + prolog: prolog_namespaceObject, + properties: properties_namespaceObject, + protobuf: protobuf_namespaceObject, + pug: pug_namespaceObject, + puppet: puppet_namespaceObject, + pure: pure_namespaceObject, + python: python_namespaceObject, + q: q_namespaceObject, + qore: qore_namespaceObject, + r: r_namespaceObject, + reason: reason_namespaceObject, + renpy: renpy_namespaceObject, + rest: rest_namespaceObject, + rip: rip_namespaceObject, + roboconf: roboconf_namespaceObject, + ruby: ruby_namespaceObject, + rust: rust_namespaceObject, + sas: sas_namespaceObject, + sass: sass_namespaceObject, + scala: scala_namespaceObject, + scheme: scheme_namespaceObject, + scss: scss_namespaceObject, + smalltalk: smalltalk_namespaceObject, + smarty: smarty_namespaceObject, + soy: soy_namespaceObject, + stylus: stylus_namespaceObject, + swift: swift_namespaceObject, + tcl: tcl_namespaceObject, + textile: textile_namespaceObject, + twig: twig_namespaceObject, + typescript: typescript_namespaceObject, + vbnet: vbnet_namespaceObject, + velocity: velocity_namespaceObject, + verilog: verilog_namespaceObject, + vhdl: vhdl_namespaceObject, + vim: vim_namespaceObject, + visualBasic: visual_basic_namespaceObject, + wasm: wasm_namespaceObject, + wiki: wiki_namespaceObject, + xeora: xeora_namespaceObject, + xojo: xojo_namespaceObject, + yaml: yaml_namespaceObject, + tsx: tsx_namespaceObject, + sql: sql_exports, + plsql: plsql_exports, + tap: tap_exports +}; +var loadLanguages2 = () => { + lib.loadLanguages(Object.values(languages).map((v) => v.default)); +}; + +// src/tokenize.ts +var ignore = { + ignore: [ + { + pattern: /(jscpd:ignore-start)[\s\S]*?(?=jscpd:ignore-end)/, + lookbehind: true, + greedy: true + }, + { + pattern: /jscpd:ignore-start/, + greedy: false + }, + { + pattern: /jscpd:ignore-end/, + greedy: false + } + ] +}; +var punctuation = { + // eslint-disable-next-line @typescript-eslint/camelcase + new_line: /\n/, + empty: /\s+/ +}; +var initializeFormats = () => { + loadLanguages2(); + Object.keys(lib.languages).forEach((lang) => { + if (lang !== "extend" && lang !== "insertBefore" && lang !== "DFS") { + lib.languages[lang] = { + ...ignore, + ...lib.languages[lang], + ...punctuation + }; + } + }); +}; +initializeFormats(); +function getLanguagePrismName(lang) { + if (lang in FORMATS && FORMATS[lang]?.parent) { + return FORMATS[lang]?.parent; + } + return lang; +} +function tokenize(code, language) { + let length = 0; + let line = 1; + let column = 1; + function sanitizeLangName(name) { + return name && name.replace ? name.replace("language-", "") : "unknown"; + } + function createTokenFromString(token, lang) { + return [ + { + format: lang, + type: "default", + value: token, + length: token.length + } + ]; + } + function calculateLocation(token, position) { + const result = token; + const lines = typeof result.value === "string" && result.value.split ? result.value.split("\n") : []; + const newLines = lines.length - 1; + const start = { + line, + column, + position + }; + column = newLines >= 0 ? Number(lines[lines.length - 1]?.length) + 1 : column; + const end = { + line: line + newLines, + column, + position + }; + result.loc = { start, end }; + result.range = [length, length + result.length]; + length += result.length; + line += newLines; + return result; + } + function createTokenFromFlatToken(token, lang) { + return [ + { + format: lang, + type: token.type, + value: token.content, + length: token.length + } + ]; + } + function createTokens(token, lang) { + if (token.content && typeof token.content === "string") { + return createTokenFromFlatToken(token, lang); + } + if (token.content && Array.isArray(token.content)) { + let res = []; + token.content.forEach( + (t) => res = res.concat(createTokens(t, token.alias ? sanitizeLangName(token.alias) : lang)) + ); + return res; + } + return createTokenFromString(token, lang); + } + let tokens = []; + const grammar4 = lib.languages[getLanguagePrismName(language)]; + if (!lib.languages[getLanguagePrismName(language)]) { + console.warn('Warn: jscpd has issue with support of "' + getLanguagePrismName(language) + '"'); + return []; + } + lib.tokenize(code, grammar4).forEach( + (t) => tokens = tokens.concat(createTokens(t, language)) + ); + return tokens.filter((t) => t.format in FORMATS).map( + (token, index) => calculateLocation(token, index) + ); +} +function setupIgnorePatterns(format, ignorePattern) { + const language = getLanguagePrismName(format); + const ignorePatterns = ignorePattern.map((pattern) => ({ + pattern: new RegExp(pattern), + greedy: false + })); + lib.languages[language] = { + ...ignorePatterns, + ...lib.languages[language] + }; +} +function createTokenMapBasedOnCode(id, data, format, options = {}) { + const { mode, ignoreCase, ignorePattern } = options; + const tokens = tokenize(data, format).filter((token) => mode(token, options)); + if (ignorePattern) + setupIgnorePatterns(format, options.ignorePattern || []); + if (ignoreCase) { + return createTokensMaps(id, data, tokens.map( + (token) => { + token.value = token.value.toLocaleLowerCase(); + return token; + } + ), options); + } + return createTokensMaps(id, data, tokens, options); +} + +// src/index.ts +var Tokenizer = class { + generateMaps(id, data, format, options) { + return createTokenMapBasedOnCode(id, data, format, options); + } +}; + +//# sourceMappingURL=index.mjs.map +// EXTERNAL MODULE: ./node_modules/fast-glob/out/index.js +var out = __nccwpck_require__(43664); +// EXTERNAL MODULE: ./node_modules/fs-extra/lib/index.js +var fs_extra_lib = __nccwpck_require__(5630); +// EXTERNAL MODULE: ./node_modules/bytes/index.js +var bytes = __nccwpck_require__(86966); +// EXTERNAL MODULE: ./node_modules/blamer/build/main/index.js +var main = __nccwpck_require__(56781); +;// CONCATENATED MODULE: external "process" +const external_process_namespaceObject = require("process"); +// EXTERNAL MODULE: ./node_modules/markdown-table/index.js +var markdown_table = __nccwpck_require__(41062); +;// CONCATENATED MODULE: ./node_modules/@jscpd/finder/dist/index.mjs +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// src/in-files-detector.ts + + + +// src/validators/skip-local.validator.ts + + +var SkipLocalValidator = class _SkipLocalValidator { + validate(clone, options) { + const status = !this.shouldSkipClone(clone, options); + return { + status, + clone, + message: [ + `Sources of duplication located in same local folder (${clone.duplicationA.sourceId}, ${clone.duplicationB.sourceId})` + ] + }; + } + shouldSkipClone(clone, options) { + const path = getOption("path", options); + return path.some( + (dir) => _SkipLocalValidator.isRelative(clone.duplicationA.sourceId, dir) && _SkipLocalValidator.isRelative(clone.duplicationB.sourceId, dir) + ); + } + static isRelative(file, path) { + const rel = (0,external_path_.relative)(path, file); + return rel !== "" && !rel.startsWith("..") && !(0,external_path_.isAbsolute)(rel); + } +}; + +// src/in-files-detector.ts +var InFilesDetector = class { + constructor(tokenizer, store, statistic, options) { + this.tokenizer = tokenizer; + this.store = store; + this.statistic = statistic; + this.options = options; + this.registerSubscriber(this.statistic); + } + reporters = []; + subscribes = []; + postHooks = []; + registerReporter(reporter) { + this.reporters.push(reporter); + } + registerSubscriber(subscriber) { + this.subscribes.push(subscriber); + } + registerHook(hook) { + this.postHooks.push(hook); + } + detect(fls) { + const files = fls.filter((f) => !!f); + if (files.length === 0) { + return Promise.resolve([]); + } + const options = this.options; + const hooks = [...this.postHooks]; + const store = this.store; + const validators = []; + if (options.skipLocal) { + validators.push(new SkipLocalValidator()); + } + const detector = new Detector(this.tokenizer, store, validators, options); + this.subscribes.forEach((listener) => { + Object.entries(listener.subscribe()).map(([event, handler]) => detector.on(event, handler)); + }); + const detect = (entry, clones = []) => { + const { path, content } = entry; + const format = getFormatByFile(path, options.formatsExts); + return format !== void 0 ? detector.detect(path, content, format).then((clns) => { + if (clns) { + clones.push(...clns); + } + const file = files.pop(); + if (file) { + return detect(file, clones); + } + return clones; + }) : Promise.resolve([]); + }; + const processHooks = (hook, detectedClones) => { + return hook.process(detectedClones).then((clones) => { + const nextHook = hooks.pop(); + if (nextHook) { + return processHooks(nextHook, clones); + } + return clones; + }); + }; + return detect(files.pop()).then((clones) => { + const hook = hooks.pop(); + if (hook) { + return processHooks(hook, clones); + } + return clones; + }).then((clones) => { + const statistic = this.statistic.getStatistic(); + this.reporters.forEach((reporter) => { + reporter.report(clones, statistic); + }); + return clones; + }); + } +}; + +// src/files.ts + + + + + + + +function isFile(path) { + try { + const stat = (0,external_fs_.lstatSync)(path); + return stat.isFile(); + } catch (e) { + return false; + } +} +function isSymlink(path) { + try { + const stat = (0,external_fs_.lstatSync)(path); + return stat.isSymbolicLink(); + } catch (e) { + return false; + } +} +function skipNotSupportedFormats(options) { + return (entry) => { + const { path } = entry; + const format = getFormatByFile(path, options.formatsExts); + const shouldNotSkip = !!(format && options.format && options.format.includes(format)); + if ((options.debug || options.verbose) && !shouldNotSkip) { + console.log(`File ${path} skipped! Format "${format}" does not included to supported formats.`); + } + return shouldNotSkip; + }; +} +function skipBigFiles(options) { + return (entry) => { + const { stats, path } = entry; + const shouldSkip = stats !== void 0 && bytes.parse(stats.size) > bytes.parse(getOption("maxSize", options)); + if (options.debug && shouldSkip) { + console.log(`File ${path} skipped! Size more then limit (${bytes(stats.size)} > ${getOption("maxSize", options)})`); + } + return !shouldSkip; + }; +} +function skipFilesIfLinesOfContentNotInLimits(options) { + return (entry) => { + const { path, content } = entry; + const lines = content.split("\n").length; + const minLines = getOption("minLines", options); + const maxLines = getOption("maxLines", options); + if (lines < minLines || lines > maxLines) { + if (options.debug || options.verbose) { + console.log((0,safe.grey)(`File ${path} skipped! Code lines=${lines} not in limits (${minLines}:${maxLines})`)); + } + return false; + } + return true; + }; +} +function addContentToEntry(entry) { + const { path } = entry; + const content = (0,fs_extra_lib.readFileSync)(path).toString(); + return { ...entry, content }; +} +function getFilesToDetect(options) { + const pattern = options.pattern || "**/*"; + let patterns = options.path; + if (options.noSymlinks) { + patterns = patterns !== void 0 ? patterns.filter((path) => !isSymlink(path)) : []; + } + patterns = patterns !== void 0 ? patterns.map((path) => { + const currentPath = (0,fs_extra_lib.realpathSync)(path); + if (isFile(currentPath)) { + return path; + } + return path.endsWith("/") ? `${path}${pattern}` : `${path}/${pattern}`; + }) : []; + return (0,out.sync)( + patterns, + { + ignore: options.ignore, + onlyFiles: true, + dot: true, + stats: true, + absolute: options.absolute, + followSymbolicLinks: !options.noSymlinks + } + ).filter(skipNotSupportedFormats(options)).filter(skipBigFiles(options)).map(addContentToEntry).filter(skipFilesIfLinesOfContentNotInLimits(options)); +} + +// src/hooks/blamer.ts + +var BlamerHook = class _BlamerHook { + process(clones) { + return Promise.all(clones.map((clone) => _BlamerHook.blameLines(clone))); + } + static async blameLines(clone) { + const blamer = new main(); + const blamedFileA = await blamer.blameByFile(clone.duplicationA.sourceId); + const blamedFileB = await blamer.blameByFile(clone.duplicationB.sourceId); + clone.duplicationA.blame = _BlamerHook.getBlamedLines(blamedFileA, clone.duplicationA.start.line, clone.duplicationA.end.line); + clone.duplicationB.blame = _BlamerHook.getBlamedLines(blamedFileB, clone.duplicationB.start.line, clone.duplicationB.end.line); + return clone; + } + static getBlamedLines(blamedFiles, start, end) { + const [file] = Object.keys(blamedFiles); + const result = {}; + Object.keys(blamedFiles[file]).filter((lineNumber) => { + return Number(lineNumber) >= start && Number(lineNumber) <= end; + }).map((lineNumber) => blamedFiles[file][lineNumber]).forEach((info) => { + result[info.line] = info; + }); + return result; + } +}; + +// src/hooks/fragment.ts + +var FragmentsHook = class _FragmentsHook { + process(clones) { + return Promise.all( + clones.map((clone) => _FragmentsHook.addFragments(clone)) + ); + } + static addFragments(clone) { + const codeA = (0,external_fs_.readFileSync)(clone.duplicationA.sourceId).toString(); + const codeB = (0,external_fs_.readFileSync)(clone.duplicationB.sourceId).toString(); + clone.duplicationA.fragment = codeA.substring(clone.duplicationA.range[0], clone.duplicationA.range[1]); + clone.duplicationB.fragment = codeB.substring(clone.duplicationB.range[0], clone.duplicationB.range[1]); + return clone; + } +}; + +// src/utils/clone-found.ts + + +// src/utils/reports.ts + + + +var compareDates = (firstDate, secondDate) => { + const first = new Date(firstDate); + const second = new Date(secondDate); + switch (true) { + case first < second: + return "=>"; + case first > second: + return "<="; + default: + return "=="; + } +}; +function escapeXml(unsafe) { + return unsafe.replace(/[<>&'"]/g, (c) => { + switch (c) { + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + case "'": + return "'"; + case '"': + return """; + default: + return ""; + } + }); +} +function getPath(path, options) { + return options.absolute ? path : (0,external_path_.relative)((0,external_process_namespaceObject.cwd)(), path); +} +function getPathConsoleString(path, options) { + return (0,safe.bold)((0,safe.green)(getPath(path, options))); +} +function getSourceLocation(start, end) { + return `${start.line}:${start.column} - ${end.line}:${end.column}`; +} +function generateLine(clone, position, line) { + const lineNumberA = (clone.duplicationA.start.line + position).toString(); + const lineNumberB = (clone.duplicationB.start.line + position).toString(); + if (clone.duplicationA.blame && clone.duplicationB.blame) { + return [ + lineNumberA, + // @ts-ignore + clone.duplicationA.blame[lineNumberA] ? clone.duplicationA.blame[lineNumberA].author : "", + clone.duplicationA.blame[lineNumberA] && clone.duplicationB.blame[lineNumberB] ? compareDates(clone.duplicationA.blame[lineNumberA].date, clone.duplicationB.blame[lineNumberB].date) : "", + lineNumberB, + // @ts-ignore + clone.duplicationB.blame[lineNumberB] ? clone.duplicationB.blame[lineNumberB].author : "", + (0,safe.grey)(line) + ]; + } else { + return [lineNumberA, lineNumberB, (0,safe.grey)(line)]; + } +} +function convertStatisticToArray(format, statistic) { + return [ + format, + `${statistic.sources}`, + `${statistic.lines}`, + `${statistic.tokens}`, + `${statistic.clones}`, + `${statistic.duplicatedLines} (${statistic.percentage}%)`, + `${statistic.duplicatedTokens} (${statistic.percentageTokens}%)` + ]; +} + +// src/utils/clone-found.ts +function cloneFound(clone, options) { + const { duplicationA, duplicationB, format, isNew } = clone; + console.log("Clone found (" + format + "):" + (isNew ? (0,safe.red)("*") : "")); + console.log( + ` - ${getPathConsoleString(duplicationA.sourceId, options)} [${getSourceLocation( + duplicationA.start, + duplicationA.end + )}] (${duplicationA.end.line - duplicationA.start.line} lines${duplicationA.end.position ? ", " + (duplicationA.end.position - duplicationA.start.position) + " tokens" : ""})` + ); + console.log( + ` ${getPathConsoleString(duplicationB.sourceId, options)} [${getSourceLocation( + duplicationB.start, + duplicationB.end + )}]` + ); + console.log(""); +} + +// src/subscribers/progress.ts +var ProgressSubscriber = class { + constructor(options) { + this.options = options; + } + subscribe() { + return { + CLONE_FOUND: (payload) => cloneFound(payload.clone, this.options) + }; + } +}; + +// src/subscribers/verbose.ts + +var VerboseSubscriber = class { + constructor(options) { + this.options = options; + } + subscribe() { + return { + "CLONE_FOUND": (payload) => { + const { clone } = payload; + console.log((0,safe.yellow)("CLONE_FOUND")); + console.log((0,safe.grey)(JSON.stringify(clone, null, " "))); + }, + "CLONE_SKIPPED": (payload) => { + const { validation } = payload; + console.log((0,safe.yellow)("CLONE_SKIPPED")); + console.log( + (0,safe.grey)("Clone skipped: " + validation?.message?.join(" ")) + ); + }, + "START_DETECTION": (payload) => { + const { source } = payload; + console.log((0,safe.yellow)("START_DETECTION")); + console.log( + (0,safe.grey)("Start detection for source id=" + source?.getId() + " format=" + source?.getFormat()) + ); + } + }; + } +}; + +// src/reporters/console.ts + +var Table = __require("cli-table3"); +var ConsoleReporter = class { + options; + constructor(options) { + this.options = options; + } + report(clones, statistic = void 0) { + if (statistic && !this.options.silent) { + const table = new Table({ + head: ["Format", "Files analyzed", "Total lines", "Total tokens", "Clones found", "Duplicated lines", "Duplicated tokens"] + }); + Object.keys(statistic.formats).filter((format) => statistic.formats[format].sources).forEach((format) => { + table.push(convertStatisticToArray(format, statistic.formats[format].total)); + }); + table.push(convertStatisticToArray((0,safe.bold)("Total:"), statistic.total)); + console.log(table.toString()); + console.log((0,safe.grey)(`Found ${clones.length} clones.`)); + } + } +}; + +// src/reporters/console-full.ts + +var Table2 = __require("cli-table3"); +var TABLE_OPTIONS = { + chars: { + top: "", + "top-mid": "", + "top-left": "", + "top-right": "", + bottom: "", + "bottom-mid": "", + "bottom-left": "", + "bottom-right": "", + left: "", + "left-mid": "", + mid: "", + "mid-mid": "", + right: "", + "right-mid": "", + middle: "\u2502" + } +}; +var ConsoleFullReporter = class { + constructor(options) { + this.options = options; + } + report(clones) { + clones.forEach((clone) => { + this.cloneFullFound(clone); + }); + console.log((0,safe.grey)(`Found ${clones.length} clones.`)); + } + cloneFullFound(clone) { + const table = new Table2(TABLE_OPTIONS); + cloneFound(clone, this.options); + clone.duplicationA.fragment.split("\n").forEach((line, position) => { + table.push(generateLine(clone, position, line)); + }); + console.log(table.toString()); + console.log(""); + } +}; + +// src/reporters/json.ts + + + + +var JsonReporter = class { + constructor(options) { + this.options = options; + } + generateJson(clones, statistics) { + return { + statistics, + duplicates: clones.map((clone) => this.cloneFound(clone)) + }; + } + report(clones, statistic) { + const json = this.generateJson(clones, statistic); + (0,fs_extra_lib.ensureDirSync)(getOption("output", this.options)); + (0,fs_extra_lib.writeFileSync)(getOption("output", this.options) + "/jscpd-report.json", JSON.stringify(json, null, " ")); + console.log((0,safe.green)(`JSON report saved to ${(0,external_path_.join)(this.options.output, "jscpd-report.json")}`)); + } + cloneFound(clone) { + const startLineA = clone.duplicationA.start.line; + const endLineA = clone.duplicationA.end.line; + const startLineB = clone.duplicationB.start.line; + const endLineB = clone.duplicationB.end.line; + return { + format: clone.format, + lines: endLineA - startLineA + 1, + fragment: clone.duplicationA.fragment, + tokens: 0, + firstFile: { + name: getPath(clone.duplicationA.sourceId, this.options), + start: startLineA, + end: endLineA, + startLoc: clone.duplicationA.start, + endLoc: clone.duplicationA.end, + blame: clone.duplicationA.blame + }, + secondFile: { + name: getPath(clone.duplicationB.sourceId, this.options), + start: startLineB, + end: endLineB, + startLoc: clone.duplicationB.start, + endLoc: clone.duplicationB.end, + blame: clone.duplicationB.blame + } + }; + } +}; + +// src/reporters/csv.ts + + + + +var CSVReporter = class { + constructor(options) { + this.options = options; + } + // @ts-ignore + report(clones, statistic) { + const report = [ + ["Format", "Files analyzed", "Total lines", "Total tokens", "Clones found", "Duplicated lines", "Duplicated tokens"], + ...Object.keys(statistic.formats).map((format) => convertStatisticToArray(format, statistic.formats[format].total)), + convertStatisticToArray("Total:", statistic.total) + ].map((arr) => arr.join(",")).join("\n"); + (0,fs_extra_lib.ensureDirSync)(getOption("output", this.options)); + (0,fs_extra_lib.writeFileSync)(getOption("output", this.options) + "/jscpd-report.csv", report); + console.log((0,safe.green)(`CSV report saved to ${(0,external_path_.join)(this.options?.output, "jscpd-report.csv")}`)); + } +}; + +// src/reporters/markdown.ts + + + + + +var MarkdownReporter = class { + constructor(options) { + this.options = options; + } + report(clones, statistic) { + const report = ` +# Copy/paste detection report + +> Duplications detection: Found ${clones.length} exact clones with ${statistic.total.duplicatedLines}(${statistic.total.percentage}%) duplicated lines in ${statistic.total.sources} (${Object.keys(statistic.formats).length} formats) files. + +${markdown_table([ + ["Format", "Files analyzed", "Total lines", "Total tokens", "Clones found", "Duplicated lines", "Duplicated tokens"], + ...Object.keys(statistic.formats).map((format) => convertStatisticToArray(format, statistic.formats[format].total)), + convertStatisticToArray("Total:", statistic.total).map((item) => `**${item}**`) + ])} +`; + (0,fs_extra_lib.ensureDirSync)(getOption("output", this.options)); + (0,fs_extra_lib.writeFileSync)(getOption("output", this.options) + "/jscpd-report.md", report); + console.log((0,safe.green)(`Markdown report saved to ${(0,external_path_.join)(this.options.output, "jscpd-report.md")}`)); + } +}; + +// src/reporters/xml.ts + + + + + +var XmlReporter = class { + constructor(options) { + this.options = options; + } + report(clones) { + let xmlDoc = ''; + xmlDoc += ""; + clones.forEach((clone) => { + xmlDoc = `${xmlDoc} + + + /i, "CDATA_END")}]]> + + + /i, "CDATA_END")}]]> + + /i, "CDATA_END")}]]> + + `; + }); + xmlDoc += ""; + (0,fs_extra_lib.ensureDirSync)(getOption("output", this.options)); + (0,external_fs_.writeFileSync)(getOption("output", this.options) + "/jscpd-report.xml", xmlDoc); + console.log((0,safe.green)(`XML report saved to ${(0,external_path_.join)(this.options.output, "jscpd-report.xml")}`)); + } +}; + +// src/reporters/silent.ts + +var SilentReporter = class { + report(clones, statistic) { + if (statistic) { + console.log( + `Duplications detection: Found ${(0,safe.bold)(clones.length.toString())} exact clones with ${(0,safe.bold)(statistic.total.duplicatedLines.toString())}(${statistic.total.percentage}%) duplicated lines in ${(0,safe.bold)(statistic.total.sources.toString())} (${Object.keys(statistic.formats).length} formats) files.` + ); + } + } +}; + +// src/reporters/threshold.ts + +var ThresholdReporter = class { + constructor(options) { + this.options = options; + } + // @ts-ignore + report(clones, statistic) { + if (statistic && this.options.threshold !== void 0 && this.options.threshold < statistic.total.percentage) { + const message = `ERROR: jscpd found too many duplicates (${statistic.total.percentage}%) over threshold (${this.options.threshold}%)`; + console.error((0,safe.red)(message)); + throw new Error(message); + } + } +}; + +// src/reporters/xcode.ts +var XcodeReporter = class { + constructor(options) { + this.options = options; + } + report(clones) { + clones.forEach((clone) => { + this.cloneFound(clone); + }); + console.log(`Found ${clones.length} clones.`); + } + cloneFound(clone) { + const pathA = getPath(clone.duplicationA.sourceId, { ...this.options, absolute: true }); + const pathB = getPath(clone.duplicationB.sourceId, this.options); + const startLineA = clone.duplicationA.start.line; + const characterA = clone.duplicationA.start.column; + const endLineA = clone.duplicationA.end.line; + const startLineB = clone.duplicationB.start.line; + const endLineB = clone.duplicationB.end.line; + console.log(`${pathA}:${startLineA}:${characterA}: warning: Found ${endLineA - startLineA} lines (${startLineA}-${endLineA}) duplicated on file ${pathB} (${startLineB}-${endLineB})`); + } +}; + +// src/utils/options.ts +function parseFormatsExtensions(extensions = "") { + const result = {}; + if (!extensions) { + return void 0; + } + extensions.split(";").forEach((format) => { + const pair = format.split(":"); + result[pair[0]] = pair[1].split(","); + }); + return result; +} + +//# sourceMappingURL=index.mjs.map +// EXTERNAL MODULE: ./node_modules/jscpd/node_modules/commander/index.js +var commander = __nccwpck_require__(85178); +// EXTERNAL MODULE: external "crypto" +var external_crypto_ = __nccwpck_require__(6113); +// EXTERNAL MODULE: external "url" +var external_url_ = __nccwpck_require__(57310); +// EXTERNAL MODULE: ./node_modules/pug/lib/index.js +var pug_lib = __nccwpck_require__(40316); +;// CONCATENATED MODULE: ./node_modules/@jscpd/html-reporter/dist/index.mjs +// ../../node_modules/.pnpm/tsup@8.0.2_postcss@8.4.38_ts-node@10.9.2_@types+node@20.12.12_typescript@5.4.5__typescript@5.4.5/node_modules/tsup/assets/esm_shims.js + + +var getFilename = () => fileURLToPath(import.meta.url); +var getDirname = () => path.dirname(getFilename()); +var dist_dirname = /* @__PURE__ */ (/* unused pure expression or super */ null && (getDirname())); + +// src/index.ts + + + + + +var HtmlReporter = class { + constructor(options) { + this.options = options; + } + report(clones, statistic) { + const jsonReporter = new JsonReporter(this.options); + const json = jsonReporter.generateJson(clones, statistic); + const result = pug_lib.renderFile(__nccwpck_require__.ab + "main.pug", json); + if (this.options.output) { + const destination = (0,external_path_.join)(this.options.output, "html/"); + try { + (0,fs_extra_lib.copySync)(__nccwpck_require__.ab + "public", destination, { overwrite: true }); + const index = (0,external_path_.join)(destination, "index.html"); + (0,fs_extra_lib.writeFileSync)(index, result); + (0,fs_extra_lib.writeFileSync)( + (0,external_path_.join)(destination, "jscpd-report.json"), + JSON.stringify(json, null, " ") + ); + console.log((0,safe.green)(`HTML report saved to ${(0,external_path_.join)(this.options.output, "html/")}`)); + } catch (e) { + console.log((0,safe.red)(e)); + } + } + } +}; + +//# sourceMappingURL=index.mjs.map +// EXTERNAL MODULE: ./node_modules/node-sarif-builder/dist/index.js +var dist = __nccwpck_require__(369); +;// CONCATENATED MODULE: ./node_modules/jscpd-sarif-reporter/dist/index.mjs +// ../../node_modules/.pnpm/tsup@8.0.2_postcss@8.4.38_ts-node@10.9.2_@types+node@20.12.12_typescript@5.4.5__typescript@5.4.5/node_modules/tsup/assets/esm_shims.js + + +var dist_getFilename = () => fileURLToPath(import.meta.url); +var dist_getDirname = () => path.dirname(dist_getFilename()); +var jscpd_sarif_reporter_dist_dirname = /* @__PURE__ */ (/* unused pure expression or super */ null && (dist_getDirname())); + +// src/index.ts + + + + +function dist_getSourceLocation(start, end) { + return `${start.line}:${start.column} - ${end.line}:${end.column}`; +} +var SarifReporter = class { + constructor(options) { + this.options = options; + } + report(clones, statistic) { + const url = "https://github.com/kucherenko/jscpd/"; + if (this.options.output) { + const pkg = (0,fs_extra_lib.readJsonSync)(__nccwpck_require__.ab + "package1.json"); + const sarifBuilder = new dist/* SarifBuilder */.ZH(); + const sarifRunBuilder = new dist/* SarifRunBuilder */.Je().initSimple({ + toolDriverName: "jscpd", + toolDriverVersion: pkg.version, + url + }); + sarifRunBuilder.addRule( + new dist/* SarifRuleBuilder */.iy().initSimple({ + ruleId: "duplication", + shortDescriptionText: "Found code duplication", + helpUri: url + }) + ); + sarifRunBuilder.addRule( + new dist/* SarifRuleBuilder */.iy().initSimple({ + ruleId: "duplications-threshold", + shortDescriptionText: "Level of duplication is too high", + helpUri: url + }) + ); + for (const clone of clones) { + const sarifResultBuilder = new dist/* SarifResultBuilder */.nn(); + sarifRunBuilder.addResult( + sarifResultBuilder.initSimple( + { + // Transcode to a SARIF level: can be "warning" or "error" or "note" + level: "warning", + messageText: `Clone detected in ${clone.format}, - ${clone.duplicationA.sourceId}[${dist_getSourceLocation(clone.duplicationA.start, clone.duplicationA.end)}] and ${clone.duplicationB.sourceId}[${dist_getSourceLocation(clone.duplicationB.start, clone.duplicationB.end)}]`, + ruleId: "duplication", + fileUri: clone.duplicationA.sourceId, + startLine: clone.duplicationA.start.line, + startColumn: clone.duplicationA.start.column, + endLine: clone.duplicationA.end.line, + endColumn: clone.duplicationA.end.column + } + ) + ); + } + if (statistic.total?.percentage >= (this.options.threshold || 100)) { + const sarifResultBuilderThreshold = new dist/* SarifResultBuilder */.nn(); + sarifRunBuilder.addResult( + sarifResultBuilderThreshold.initSimple({ + level: "error", + messageText: `The duplication level (${statistic.total.percentage}%) is bigger than threshold (${this.options.threshold}%)`, + ruleId: "duplications-threshold" + }) + ); + } + const path2 = (0,external_path_.join)(this.options.output, "jscpd-sarif.json"); + sarifBuilder.addRun(sarifRunBuilder); + const sarifJsonString = sarifBuilder.buildSarifJsonString({ indent: false }); + (0,fs_extra_lib.ensureDirSync)(this.options.output); + (0,fs_extra_lib.writeFileSync)(path2, sarifJsonString); + console.log((0,safe.green)(`SARIF report saved to ${path2}`)); + } + } +}; + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/jscpd/dist/jscpd.mjs +var jscpd_require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// src/index.ts + + + + +// src/init/cli.ts + + +function initCli(packageJson, argv) { + const cli = new commander.Command(packageJson.name); + cli.version(packageJson.version).usage("[options] ").description(packageJson.description).option( + "-l, --min-lines [number]", + "min size of duplication in code lines (Default is " + getOption("minLines") + ")" + ).option( + "-k, --min-tokens [number]", + "min size of duplication in code tokens (Default is " + getOption("minTokens") + ")" + ).option("-x, --max-lines [number]", "max size of source in lines (Default is " + getOption("maxLines") + ")").option( + "-z, --max-size [string]", + "max size of source in bytes, examples: 1kb, 1mb, 120kb (Default is " + getOption("maxSize") + ")" + ).option( + "-t, --threshold [number]", + "threshold for duplication, in case duplications >= threshold jscpd will exit with error" + ).option("-c, --config [string]", "path to config file (Default is .jscpd.json in )").option("-i, --ignore [string]", "glob pattern for files what should be excluded from duplication detection").option("--ignore-pattern [string]", "Ignore code blocks matching the regexp patterns").option( + "-r, --reporters [string]", + "reporters or list of reporters separated with comma to use (Default is time,console)" + ).option("-o, --output [string]", "reporters to use (Default is ./report/)").option( + "-m, --mode [string]", + 'mode of quality of search, can be "strict", "mild" and "weak" (Default is "' + getOption("mode") + '")' + ).option("-f, --format [string]", "format or formats separated by comma (Example php,javascript,python)").option("-p, --pattern [string]", "glob pattern to file search (Example **/*.txt)").option("-b, --blame", "blame authors of duplications (get information about authors from git)").option("-s, --silent", "do not write detection progress and result to a console").option("--store [string]", "use for define custom store (e.g. --store leveldb used for big codebase)").option("-a, --absolute", "use absolute path in reports").option("-n, --noSymlinks", "dont use symlinks for detection in files").option("--ignoreCase", "ignore case of symbols in code (experimental)").option("-g, --gitignore", "ignore all files from .gitignore file").option("--formats-exts [string]", "list of formats with file extensions (javascript:es,es6;dart:dt)").option("-d, --debug", "show debug information, not run detection process(options list and selected files)").option("-v, --verbose", "show full information during detection process").option("--list", "show list of total supported formats").option("--skipLocal", "skip duplicates in local folders, just detect cross folders duplications").option("--exitCode [number]", "exit code to use when code duplications are detected"); + cli.parse(argv); + return cli; +} + +// src/init/options.ts + + + +// src/init/ignore.ts + +var gitignoreToGlob = jscpd_require("gitignore-to-glob"); +function initIgnore(options) { + const ignore = options.ignore || []; + if (options.gitignore && (0,external_fs_.existsSync)(process.cwd() + "/.gitignore")) { + let gitignorePatterns = gitignoreToGlob(process.cwd() + "/.gitignore") || []; + gitignorePatterns = gitignorePatterns.map( + (pattern) => pattern.substr(pattern.length - 1) === "/" ? `${pattern}**/*` : pattern + ); + ignore.push(...gitignorePatterns); + ignore.map((pattern) => pattern.replace("!", "")); + } + return ignore; +} + +// src/options.ts + + + + + +var convertCliToOptions = (cli) => { + const result = { + minTokens: cli.minTokens ? parseInt(cli.minTokens) : void 0, + minLines: cli.minLines ? parseInt(cli.minLines) : void 0, + maxLines: cli.maxLines ? parseInt(cli.maxLines) : void 0, + maxSize: cli.maxSize, + debug: cli.debug, + store: cli.store, + pattern: cli.pattern, + executionId: cli.executionId, + silent: cli.silent, + blame: cli.blame, + verbose: cli.verbose, + cache: cli.cache, + output: cli.output, + format: cli.format, + formatsExts: parseFormatsExtensions(cli.formatsExts), + list: cli.list, + mode: cli.mode, + absolute: cli.absolute, + noSymlinks: cli.noSymlinks, + skipLocal: cli.skipLocal, + ignoreCase: cli.ignoreCase, + gitignore: cli.gitignore, + exitCode: cli.exitCode + }; + if (cli.threshold !== void 0) { + result.threshold = Number(cli.threshold); + } + if (cli.reporters) { + result.reporters = cli.reporters.split(","); + } + if (cli.format) { + result.format = cli.format.split(","); + } + if (cli.ignore) { + result.ignore = cli.ignore.split(","); + } + if (cli.ignorePattern) { + result.ignorePattern = cli.ignorePattern.split(","); + } + result.path = cli.path ? [cli.path].concat(cli.args) : cli.args; + if (result.path.length === 0) { + delete result.path; + } + Object.keys(result).forEach((key) => { + if (typeof result[key] === "undefined") { + delete result[key]; + } + }); + return result; +}; +var readConfigJson = (config) => { + const configFile = config ? (0,external_path_.resolve)(config) : (0,external_path_.resolve)(".jscpd.json"); + const configExists = (0,external_fs_.existsSync)(configFile); + if (configExists) { + const result = { config: configFile, ...(0,fs_extra_lib.readJSONSync)(configFile) }; + if (result.path) { + result.path = result.path.map((path) => (0,external_path_.resolve)((0,external_path_.dirname)(configFile), path)); + } + return result; + } + return {}; +}; +var readPackageJsonConfig = () => { + const config = (0,external_path_.resolve)(process.cwd() + "/package.json"); + if ((0,external_fs_.existsSync)(config)) { + const json = (0,fs_extra_lib.readJSONSync)(config); + if (json.jscpd && json.jscpd.path) { + json.jscpd.path = json.jscpd.path.map((path) => (0,external_path_.resolve)((0,external_path_.dirname)(config), path)); + } + return json.jscpd ? { config, ...json.jscpd } : {}; + } + return {}; +}; +function prepareOptions(cli) { + const storedConfig = readConfigJson(cli.config); + const packageJsonConfig = readPackageJsonConfig(); + const argsConfig = convertCliToOptions(cli); + const result = { + ...getDefaultOptions(), + ...packageJsonConfig, + ...storedConfig, + ...argsConfig + }; + result.reporters = result.reporters || []; + result.listeners = result.listeners || []; + if (result.silent) { + result.reporters = result.reporters.filter( + (reporter) => !reporter.includes("console") + ).concat("silent"); + } + if (result.threshold !== void 0) { + result.reporters = [...result.reporters, "threshold"]; + } + return result; +} + +// src/init/options.ts +function initOptionsFromCli(cli) { + const options = prepareOptions(cli); + options.format = options.format || getSupportedFormats(); + options.mode = getModeHandler(options.mode); + options.ignore = initIgnore(options); + return options; +} + +// src/print/files.ts + +function printFiles(files) { + files.forEach((stats) => { + console.log((0,safe.grey)(stats.path)); + }); + console.log((0,safe.bold)(`Found ${files.length} files to detect.`)); +} + +// src/print/options.ts + +function printOptions(options) { + console.log((0,safe.bold)((0,safe.white)("Options:"))); + console.dir(options); +} + +// src/print/supported-format.ts + + +function printSupportedFormat() { + console.log((0,safe.bold)((0,safe.white)("Supported formats: "))); + console.log(getSupportedFormats().join(", ")); + process.exit(0); +} + +// src/index.ts + + +// src/init/store.ts + + +function getStore(storeName) { + if (storeName) { + const packageName = "@jscpd/" + storeName + "-store"; + try { + const store = jscpd_require(packageName).default; + return new store(); + } catch (e) { + console.error((0,safe.red)("store name " + storeName + " not installed.")); + } + } + return new MemoryStore(); +} + +// src/index.ts + + +// src/init/reporters.ts + + + + +var reporters = { + xml: XmlReporter, + json: JsonReporter, + csv: CSVReporter, + markdown: MarkdownReporter, + consoleFull: ConsoleFullReporter, + html: HtmlReporter, + console: ConsoleReporter, + silent: SilentReporter, + threshold: ThresholdReporter, + xcode: XcodeReporter, + sarif: SarifReporter +}; +function registerReporters(options, detector) { + options.reporters.forEach((reporter) => { + if (reporter in reporters) { + detector.registerReporter(new reporters[reporter](options)); + } else { + try { + const reporterClass = jscpd_require(`@jscpd/${reporter}-reporter`).default; + detector.registerReporter(new reporterClass(options)); + } catch (e) { + try { + const reporterClass = jscpd_require(`jscpd-${reporter}-reporter`).default; + detector.registerReporter(new reporterClass(options)); + } catch (e2) { + console.log((0,safe.yellow)(`warning: ${reporter} not installed (install packages named @jscpd/${reporter}-reporter or jscpd-${reporter}-reporter)`)); + console.log((0,safe.grey)(e2.message)); + } + } + } + }); +} + +// src/init/subscribers.ts + +function registerSubscribers(options, detector) { + if (options.verbose) { + detector.registerSubscriber(new VerboseSubscriber(options)); + } + if (!options.silent) { + detector.registerSubscriber(new ProgressSubscriber(options)); + } +} + +// src/init/hooks.ts + +function registerHooks(options, detector) { + detector.registerHook(new FragmentsHook()); + if (options.blame) { + detector.registerHook(new BlamerHook()); + } +} + +// src/index.ts + +var TIMER_LABEL = "Detection time:"; +var detectClones = (opts, store = void 0) => { + const options = { ...getDefaultOptions(), ...opts }; + options.format = options.format || getSupportedFormats(); + const files = getFilesToDetect(options); + const hashFunction = (value) => { + return (0,external_crypto_.createHash)("md5").update(value).digest("hex"); + }; + options.hashFunction = options.hashFunction || hashFunction; + const currentStore = store || getStore(options.store); + const statistic = new Statistic(); + const tokenizer = new Tokenizer(); + const detector = new InFilesDetector(tokenizer, currentStore, statistic, options); + registerReporters(options, detector); + registerSubscribers(options, detector); + registerHooks(options, detector); + if (!options.silent) { + console.time((0,safe.italic)((0,safe.grey)(TIMER_LABEL))); + } + return detector.detect(files).then((clones) => { + if (!options.silent) { + console.timeEnd((0,safe.italic)((0,safe.grey)(TIMER_LABEL))); + } + return clones; + }); +}; +async function jscpd(argv, exitCallback) { + const packageJson = (0,fs_extra_lib.readJSONSync)(__nccwpck_require__.ab + "package.json"); + const cli = initCli(packageJson, argv); + const options = initOptionsFromCli(cli); + if (options.list) { + printSupportedFormat(); + } + if (options.debug) { + printOptions(options); + } + if (!options.path || options.path.length === 0) { + options.path = [process.cwd()]; + } + if (options.debug) { + const files = getFilesToDetect(options); + printFiles(files); + return Promise.resolve([]); + } else { + const store = getStore(options.store); + return detectClones(options, store).then((clones) => { + if (clones.length > 0) { + exitCallback?.(options.exitCode || 0); + } + return clones; + }).finally(() => { + store.close(); + }); + } +} + +// bin/jscpd.ts +(async () => { + try { + await jscpd(process.argv, process.exit); + } catch (e) { + console.log(e); + process.exit(1); + } +})(); + +//# sourceMappingURL=jscpd.mjs.map +// EXTERNAL MODULE: external "util" +var external_util_ = __nccwpck_require__(73837); +// EXTERNAL MODULE: ./lib/common.js +var common = __nccwpck_require__(86979); +// EXTERNAL MODULE: ./lib/execute.js +var execute = __nccwpck_require__(3532); +// EXTERNAL MODULE: ./lib/git.js + 1 modules +var lib_git = __nccwpck_require__(63350); +// EXTERNAL MODULE: ./lib/readConfig.js + 1 modules +var readConfig = __nccwpck_require__(22094); +;// CONCATENATED MODULE: ./lib/duplicated.js @@ -151,48 +3186,48 @@ async function duplicatedCheck(workspace, jscpdConfigPath, jscpdCheckAsError, po const cwd = process.cwd(); const path = checkWorkspace(workspace); const options = getOptions(jscpdConfigPath, path, cwd); - const clones = await (0,jscpd__WEBPACK_IMPORTED_MODULE_3__.detectClones)(options); + const clones = await detectClones(options); if (clones.length > 0) { const reportFiles = getReportFiles(cwd); const markdownReport = reportFiles.find(file => file.endsWith('.md')); const jsonReport = reportFiles.find(file => file.endsWith('.json')); const message = await postReport(githubClient, markdownReport, clones, workspace, postNewComment); - fs__WEBPACK_IMPORTED_MODULE_2__.writeFileSync(markdownReport, message); - await _git__WEBPACK_IMPORTED_MODULE_7__/* .UploadReportToArtifacts */ .BC([markdownReport, jsonReport], REPORT_ARTIFACT_NAME); + external_fs_.writeFileSync(markdownReport, message); + await lib_git/* UploadReportToArtifacts */.BC([markdownReport, jsonReport], REPORT_ARTIFACT_NAME); const isOverThreshold = checkThreshold(jsonReport, options.threshold || 0); - jscpdCheckAsError && isOverThreshold ? _actions_core__WEBPACK_IMPORTED_MODULE_0__.setFailed('❌ DUPLICATED CODE FOUND') : _actions_core__WEBPACK_IMPORTED_MODULE_0__.warning('DUPLICATED CODE FOUND', ANNOTATION_OPTIONS); + jscpdCheckAsError && isOverThreshold ? core.setFailed('❌ DUPLICATED CODE FOUND') : core.warning('DUPLICATED CODE FOUND', ANNOTATION_OPTIONS); showAnnotation(clones, cwd, jscpdCheckAsError && isOverThreshold); - _actions_core__WEBPACK_IMPORTED_MODULE_0__.setOutput('hasDuplicates', `${isOverThreshold}`); + core.setOutput('hasDuplicates', `${isOverThreshold}`); } else { - _actions_core__WEBPACK_IMPORTED_MODULE_0__.setOutput('hasDuplicates', 'false'); - _actions_core__WEBPACK_IMPORTED_MODULE_0__.notice('✅ NO DUPLICATED CODE FOUND', ANNOTATION_OPTIONS); + core.setOutput('hasDuplicates', 'false'); + core.notice('✅ NO DUPLICATED CODE FOUND', ANNOTATION_OPTIONS); } - await (0,_execute__WEBPACK_IMPORTED_MODULE_6__/* .execute */ .h)(`rm -rf ${cwd}/${REPORT_ARTIFACT_NAME}`); + await (0,execute/* execute */.h)(`rm -rf ${cwd}/${REPORT_ARTIFACT_NAME}`); } function getOptions(jscpdConfigPath, workspace, cwd) { - const configOptions = (0,_readConfig__WEBPACK_IMPORTED_MODULE_8__/* .readConfig */ .z)({}, jscpdConfigPath, workspace, '.jscpd.json'); + const configOptions = (0,readConfig/* readConfig */.z)({}, jscpdConfigPath, workspace, '.jscpd.json'); const defaultOptions = { path: [`${workspace}`], reporters: ['markdown', 'json', 'consoleFull'], output: `${cwd}/${REPORT_ARTIFACT_NAME}` }; const options = { ...configOptions, ...defaultOptions }; - _actions_core__WEBPACK_IMPORTED_MODULE_0__.startGroup('🔎 loaded options'); - _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`${(0,util__WEBPACK_IMPORTED_MODULE_4__.inspect)(options)}`); - _actions_core__WEBPACK_IMPORTED_MODULE_0__.endGroup(); + core.startGroup('🔎 loaded options'); + core.info(`${(0,external_util_.inspect)(options)}`); + core.endGroup(); return options; } function getReportFiles(cwd) { - const files = fs__WEBPACK_IMPORTED_MODULE_2__.readdirSync(`${cwd}/${REPORT_ARTIFACT_NAME}`); + const files = external_fs_.readdirSync(`${cwd}/${REPORT_ARTIFACT_NAME}`); const filePaths = files.map(file => `${cwd}/${REPORT_ARTIFACT_NAME}/${file}`); - _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`reportFiles: ${filePaths.join(',')}`); + core.info(`reportFiles: ${filePaths.join(',')}`); return filePaths; } function checkWorkspace(workspace) { - _actions_core__WEBPACK_IMPORTED_MODULE_0__.info(`workspace: ${workspace}`); + core.info(`workspace: ${workspace}`); //check if workspace path is a file - const isFile = fs__WEBPACK_IMPORTED_MODULE_2__.existsSync(workspace) && fs__WEBPACK_IMPORTED_MODULE_2__.lstatSync(workspace).isFile(); + const isFile = external_fs_.existsSync(workspace) && external_fs_.lstatSync(workspace).isFile(); if (isFile) { // if it is a file, get the directory return workspace.substring(0, workspace.lastIndexOf('/')); @@ -200,7 +3235,7 @@ function checkWorkspace(workspace) { return workspace; } function showAnnotation(clones, cwd, isError) { - const show = isError ? _actions_core__WEBPACK_IMPORTED_MODULE_0__.error : _actions_core__WEBPACK_IMPORTED_MODULE_0__.warning; + const show = isError ? core.error : core.warning; for (const clone of clones) { show(`${clone.duplicationA.sourceId.replace(cwd, '')} (${clone.duplicationA.start.line}-${clone.duplicationA.end.line}) and ${clone.duplicationB.sourceId.replace(cwd, '')} (${clone.duplicationB.start.line}-${clone.duplicationB.end.line})`, { @@ -215,7 +3250,7 @@ function getReportHeader(workspace) { return `## ❌ DUPLICATED CODE FOUND - ${workspace}`; } async function postReport(githubClient, markdownReport, clones, workspace, postNewComment) { - let report = fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync(markdownReport, 'utf8'); + let report = external_fs_.readFileSync(markdownReport, 'utf8'); // remove existing header report = report.replace('# Copy/paste detection report', ''); const cwd = process.cwd(); @@ -229,28 +3264,28 @@ async function postReport(githubClient, markdownReport, clones, workspace, postN } markdown += '\n'; const header = getReportHeader(workspace); - const message = `${header} \n\n${report}\n\n ${markdown}\n\n ${(0,_common__WEBPACK_IMPORTED_MODULE_5__/* .getReportFooter */ .TS)()}`; - await _git__WEBPACK_IMPORTED_MODULE_7__/* .setSummary */ .Li(message); - if (_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.eventName === 'pull_request') { - const existingCommentId = await _git__WEBPACK_IMPORTED_MODULE_7__/* .getExistingCommentId */ .Iy(githubClient, header); + const message = `${header} \n\n${report}\n\n ${markdown}\n\n ${(0,common/* getReportFooter */.TS)()}`; + await lib_git/* setSummary */.Li(message); + if (github.context.eventName === 'pull_request') { + const existingCommentId = await lib_git/* getExistingCommentId */.Iy(githubClient, header); if (!postNewComment && existingCommentId) { - await _git__WEBPACK_IMPORTED_MODULE_7__/* .updateComment */ .uA(githubClient, existingCommentId, message); + await lib_git/* updateComment */.uA(githubClient, existingCommentId, message); } else { - await _git__WEBPACK_IMPORTED_MODULE_7__/* .comment */ .UI(githubClient, message); + await lib_git/* comment */.UI(githubClient, message); } } return message; } function toGithubLink(path, cwd, range) { const main = path.replace(`${cwd}/`, ''); - return `[${main}#L${range[0]}-L${range[1]}](https://github.com/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.owner}/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.repo.repo}/blob/${_actions_github__WEBPACK_IMPORTED_MODULE_1__.context.sha}/${main}#L${range[0]}-L${range[1]})`; + return `[${main}#L${range[0]}-L${range[1]}](https://github.com/${github.context.repo.owner}/${github.context.repo.repo}/blob/${github.context.sha}/${main}#L${range[0]}-L${range[1]})`; } function checkThreshold(jsonReport, threshold) { // read json report - const report = JSON.parse(fs__WEBPACK_IMPORTED_MODULE_2__.readFileSync(jsonReport, 'utf8')); + const report = JSON.parse(external_fs_.readFileSync(jsonReport, 'utf8')); if (report.statistics.total.percentage > threshold) { - _actions_core__WEBPACK_IMPORTED_MODULE_0__.error(`DUPLICATED CODE FOUND ${report.statistics.total.percentage}% IS OVER THRESHOLD ${threshold}%`, ANNOTATION_OPTIONS); + core.error(`DUPLICATED CODE FOUND ${report.statistics.total.percentage}% IS OVER THRESHOLD ${threshold}%`, ANNOTATION_OPTIONS); return true; } return false; @@ -823,7 +3858,7 @@ __nccwpck_require__.r(__webpack_exports__); /* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(73837); /* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__nccwpck_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(86979); -/* harmony import */ var _duplicated__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(93562); +/* harmony import */ var _duplicated__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(73765); /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(19118); /* harmony import */ var _problem_matcher__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(6702); @@ -6960,7 +9995,7 @@ var __rest = (this && this.__rest) || function (s, e) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DefaultArtifactClient = void 0; -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); const config_1 = __nccwpck_require__(74610); const upload_artifact_1 = __nccwpck_require__(42578); const download_artifact_1 = __nccwpck_require__(73555); @@ -7100,7 +10135,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteArtifactInternal = exports.deleteArtifactPublic = void 0; -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); const github_1 = __nccwpck_require__(21260); const user_agent_1 = __nccwpck_require__(85164); const retry_options_1 = __nccwpck_require__(64597); @@ -7218,7 +10253,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.downloadArtifactInternal = exports.downloadArtifactPublic = exports.streamExtractExternal = void 0; const promises_1 = __importDefault(__nccwpck_require__(73292)); const github = __importStar(__nccwpck_require__(21260)); -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const httpClient = __importStar(__nccwpck_require__(58464)); const unzip_stream_1 = __importDefault(__nccwpck_require__(69340)); const user_agent_1 = __nccwpck_require__(85164); @@ -7427,7 +10462,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getArtifactInternal = exports.getArtifactPublic = void 0; const github_1 = __nccwpck_require__(21260); const plugin_retry_1 = __nccwpck_require__(86298); -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const utils_1 = __nccwpck_require__(58154); const retry_options_1 = __nccwpck_require__(64597); const plugin_request_log_1 = __nccwpck_require__(68883); @@ -7531,7 +10566,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.listArtifactsInternal = exports.listArtifactsPublic = void 0; -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); const github_1 = __nccwpck_require__(21260); const user_agent_1 = __nccwpck_require__(85164); const retry_options_1 = __nccwpck_require__(64597); @@ -7691,7 +10726,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRetryOptions = void 0; -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); // Defaults for fetching artifacts const defaultMaxRetryNumber = 5; const defaultExemptStatusCodes = [400, 401, 403, 404, 422]; // https://github.com/octokit/plugin-retry.js/blob/9a2443746c350b3beedec35cf26e197ea318a261/src/index.ts#L14 @@ -7736,7 +10771,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.internalArtifactTwirpClient = void 0; const http_client_1 = __nccwpck_require__(58464); const auth_1 = __nccwpck_require__(5788); -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); const generated_1 = __nccwpck_require__(49960); const config_1 = __nccwpck_require__(74610); const user_agent_1 = __nccwpck_require__(85164); @@ -7888,7 +10923,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUploadChunkTimeout = exports.getConcurrency = exports.getGitHubWorkspaceDir = exports.isGhes = exports.getResultsServiceUrl = exports.getRuntimeToken = exports.getUploadChunkSize = void 0; const os_1 = __importDefault(__nccwpck_require__(22037)); -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); // Used for controlling the highWaterMark value of the zip that is being streamed // The same value is used as the chunk size that is use during upload to blob storage function getUploadChunkSize() { @@ -8109,7 +11144,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBackendIdsFromToken = void 0; -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const config_1 = __nccwpck_require__(74610); const jwt_decode_1 = __importDefault(__nccwpck_require__(84329)); const InvalidJwtError = new Error('Failed to get backend IDs: The provided JWT token is invalid and/or missing claims'); @@ -8205,7 +11240,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uploadZipToBlobStorage = void 0; const storage_blob_1 = __nccwpck_require__(84100); const config_1 = __nccwpck_require__(74610); -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const crypto = __importStar(__nccwpck_require__(6113)); const stream = __importStar(__nccwpck_require__(12781)); const errors_1 = __nccwpck_require__(38182); @@ -8288,7 +11323,7 @@ exports.uploadZipToBlobStorage = uploadZipToBlobStorage; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateFilePath = exports.validateArtifactName = void 0; -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); /** * Invalid characters that cannot be in the artifact name or an uploaded file. Will be rejected * from the server if attempted to be sent over. These characters are not allowed due to limitations with certain @@ -8386,7 +11421,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExpiration = void 0; const generated_1 = __nccwpck_require__(49960); -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); function getExpiration(retentionDays) { if (!retentionDays) { return undefined; @@ -8455,7 +11490,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uploadArtifact = void 0; -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const retention_1 = __nccwpck_require__(3231); const path_and_artifact_name_validation_1 = __nccwpck_require__(63219); const artifact_twirp_client_1 = __nccwpck_require__(12312); @@ -8558,7 +11593,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUploadZipSpecification = exports.validateRootDirectory = void 0; const fs = __importStar(__nccwpck_require__(57147)); -const core_1 = __nccwpck_require__(15457); +const core_1 = __nccwpck_require__(42186); const path_1 = __nccwpck_require__(71017); const path_and_artifact_name_validation_1 = __nccwpck_require__(63219); /** @@ -8692,7 +11727,7 @@ exports.createZipUploadStream = exports.ZipUploadStream = exports.DEFAULT_COMPRE const stream = __importStar(__nccwpck_require__(12781)); const promises_1 = __nccwpck_require__(73292); const archiver = __importStar(__nccwpck_require__(43084)); -const core = __importStar(__nccwpck_require__(15457)); +const core = __importStar(__nccwpck_require__(42186)); const config_1 = __nccwpck_require__(74610); exports.DEFAULT_COMPRESSION_LEVEL = 6; // Custom stream transformer so we can set the highWaterMark property @@ -8775,18 +11810,75 @@ const zipEndCallback = () => { /***/ }), -/***/ 56270: +/***/ 47387: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(22037); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 21260: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -8799,90 +11891,147 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(86700); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(47387)); +const utils_1 = __nccwpck_require__(58154); +exports.context = new Context.Context(); /** - * Commands - * - * Command Format: - * ::name key=value,key=value::message + * Returns a hydrated octokit ready to use for GitHub Actions * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); } -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 12114: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(8343)); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; } -function escapeData(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); } -function escapeProperty(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); +exports.getProxyAgent = getProxyAgent; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; } -//# sourceMappingURL=command.js.map +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 58154: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(47387)); +const Utils = __importStar(__nccwpck_require__(12114)); +// octokit + plugins +const core_1 = __nccwpck_require__(76762); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); +const plugin_paginate_rest_1 = __nccwpck_require__(64193); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 15457: +/***/ 8343: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); @@ -8916,980 +12065,720 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(56270); -const file_command_1 = __nccwpck_require__(85436); -const utils_1 = __nccwpck_require__(86700); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(4759); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode || (exports.ExitCode = ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +const pm = __importStar(__nccwpck_require__(72212)); +const tunnel = __importStar(__nccwpck_require__(74294)); +const undici_1 = __nccwpck_require__(41773); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** - * Registers a secret which will get masked from logs - * @param secret value of the secret + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ -function setSecret(secret) { - (0, command_1.issueCommand)('add-mask', {}, secret); +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - (0, file_command_1.issueFileCommand)('PATH', inputPath); - } - else { - (0, command_1.issueCommand)('add-path', {}, inputPath); +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - (0, command_1.issue)('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - (0, command_1.issueCommand)('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - (0, command_1.issue)('group', name); } -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - (0, command_1.issue)('endgroup'); +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(47613); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(47613); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(3849); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -/** - * Platform utilities exports - */ -exports.platform = __importStar(__nccwpck_require__(17940)); -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 85436: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const crypto = __importStar(__nccwpck_require__(6113)); -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(86700); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - const convertedValue = (0, utils_1.toCommandValue)(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 4759: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(69714); -const auth_1 = __nccwpck_require__(27444); -const core_1 = __nccwpck_require__(15457); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); } - static getCall(id_token_url) { - var _a; + sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; + return this.request(verb, requestUrl, stream, additionalHeaders); }); } - static getIDToken(audience) { + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map - -/***/ }), - -/***/ 3849: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 17940: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -const os_1 = __importDefault(__nccwpck_require__(22037)); -const exec = __importStar(__nccwpck_require__(71514)); -const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { - silent: true - }); - const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { - silent: true - }); - return { - name: name.trim(), - version: version.trim() - }; -}); -const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b, _c, _d; - const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { - silent: true - }); - const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; - return { - name, - version - }; -}); -const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { - silent: true - }); - const [name, version] = stdout.trim().split('\n'); - return { - name, - version - }; -}); -exports.platform = os_1.default.platform(); -exports.arch = os_1.default.arch(); -exports.isWindows = exports.platform === 'win32'; -exports.isMacOS = exports.platform === 'darwin'; -exports.isLinux = exports.platform === 'linux'; -function getDetails() { - return __awaiter(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, (yield (exports.isWindows - ? getWindowsInfo() - : exports.isMacOS - ? getMacOsInfo() - : getLinuxInfo()))), { platform: exports.platform, - arch: exports.arch, - isWindows: exports.isWindows, - isMacOS: exports.isMacOS, - isLinux: exports.isLinux }); - }); -} -exports.getDetails = getDetails; -//# sourceMappingURL=platform.js.map - -/***/ }), - -/***/ 47613: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch */ - filePath() { + request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + if (this._disposed) { + throw new Error('Client has already been disposed.'); } - this._filePath = pathFromEnv; - return this._filePath; + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); } /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element + * Needs to be called if keepAlive is set to true in request options. */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; + dispose() { + if (this._agent) { + this._agent.destroy(); } - return `<${tag}${htmlAttrs}>${content}`; + this._disposed = true; } /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance + * Raw request. + * @param info + * @param data */ - write(options) { + requestRaw(info, data) { return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); }); } /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } } /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); } } -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 86700: +/***/ 72212: /***/ ((__unused_webpack_module, exports) => { "use strict"; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - else if (typeof input === 'string' || input instanceof String) { - return input; + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } + } + else { + return undefined; } - return JSON.stringify(input); } -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; } -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map +exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} +//# sourceMappingURL=proxy.js.map /***/ }), -/***/ 27444: +/***/ 5788: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -9977,7 +12866,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 69714: +/***/ 58464: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -10019,7 +12908,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(13685)); const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(78649)); +const pm = __importStar(__nccwpck_require__(7377)); const tunnel = __importStar(__nccwpck_require__(74294)); const undici_1 = __nccwpck_require__(41773); var HttpCodes; @@ -10485,7 +13374,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -10517,16 +13406,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -10548,7 +13433,7 @@ class HttpClient { } const usingSsl = parsedUrl.protocol === 'https:'; proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `${proxyUrl.username}:${proxyUrl.password}` + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { @@ -10640,7 +13525,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 78649: +/***/ 7377: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -10662,11 +13547,11 @@ function getProxyUrl(reqUrl) { })(); if (proxyVar) { try { - return new URL(proxyVar); + return new DecodedURL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new URL(`http://${proxyVar}`); + return new DecodedURL(`http://${proxyVar}`); } } else { @@ -10725,79 +13610,138 @@ function isLoopbackAddress(host) { hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } +class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } +} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 47387: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87351: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + this.command = command; + this.properties = properties; + this.message = message; } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; } } -exports.Context = Context; -//# sourceMappingURL=context.js.map +function escapeData(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map /***/ }), -/***/ 21260: +/***/ 42186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -10810,38 +13754,346 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(47387)); -const utils_1 = __nccwpck_require__(58154); -exports.context = new Context.Context(); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(87351); +const file_command_1 = __nccwpck_require__(717); +const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const oidc_utils_1 = __nccwpck_require__(98041); /** - * Returns a hydrated octokit ready to use for GitHub Actions + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (exports.ExitCode = ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = (0, utils_1.toCommandValue)(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); + } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + (0, command_1.issueCommand)('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + (0, file_command_1.issueFileCommand)('PATH', inputPath); + } + else { + (0, command_1.issueCommand)('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + if (options && options.trimWhitespace === false) { + return val; + } + return val.trim(); } -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + process.stdout.write(os.EOL); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + (0, command_1.issueCommand)('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + (0, command_1.issue)('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + (0, command_1.issue)('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(81327); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(81327); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(2981); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(85243)); +//# sourceMappingURL=core.js.map /***/ }), -/***/ 12114: +/***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +// For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -10854,44 +14106,146 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(8343)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const crypto = __importStar(__nccwpck_require__(6113)); +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(5278); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { + encoding: 'utf8' + }); } -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 98041: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); +const core_1 = __nccwpck_require__(42186); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); + } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + (0, core_1.debug)(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + (0, core_1.setSecret)(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } } -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 58154: +/***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -10904,53 +14258,56 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(47387)); -const Utils = __importStar(__nccwpck_require__(12114)); -// octokit + plugins -const core_1 = __nccwpck_require__(76762); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); -const plugin_paginate_rest_1 = __nccwpck_require__(64193); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(71017)); /** - * Convience function to correctly format Octokit Options to pass into the constructor. + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set + * @param pth. Path to transform. + * @return string Posix path. */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); } -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map /***/ }), -/***/ 8343: +/***/ 85243: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); @@ -10983,725 +14340,431 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(72212)); -const tunnel = __importStar(__nccwpck_require__(74294)); -const undici_1 = __nccwpck_require__(41773); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(22037)); +const exec = __importStar(__nccwpck_require__(71514)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); } -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 81327: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(57147); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; } - readBodyBuffer() { + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on('data', (chunk) => { - chunks.push(chunk); - }); - this.message.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + if (this._filePath) { + return this._filePath; } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + this._filePath = pathFromEnv; + return this._filePath; }); } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; } - head(requestUrl, additionalHeaders) { + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); }); } - sendStream(verb, requestUrl, stream, additionalHeaders) { + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); + return this.emptyBuffer().write({ overwrite: true }); }); } /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + stringify() { + return this._buffer; } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); + emptyBuffer() { + this._buffer = ''; + return this; } /** - * Needs to be called if keepAlive is set to true in request options. + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; } /** - * Raw request. - * @param info - * @param data + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); + addEOL() { + return this.addRaw(os_1.EOL); } /** - * Raw request with callback. - * @param info - * @param data - * @param onResult + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); } /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - // if agent is already assigned use that agent. - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `${proxyUrl.username}:${proxyUrl.password}` - }))); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map /***/ }), -/***/ 72212: +/***/ 5278: /***/ ((__unused_webpack_module, exports) => { "use strict"; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - try { - return new URL(proxyVar); - } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new URL(`http://${proxyVar}`); - } +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; } - else { - return undefined; + else if (typeof input === 'string' || input instanceof String) { + return input; } + return JSON.stringify(input); } -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; - } +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; } - return false; -} -exports.checkBypass = checkBypass; -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return (hostLower === 'localhost' || - hostLower.startsWith('127.') || - hostLower.startsWith('[::1]') || - hostLower.startsWith('[0:0:0:0:0:0:0:1]')); + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; } -//# sourceMappingURL=proxy.js.map +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 5788: -/***/ (function(__unused_webpack_module, exports) { +/***/ 71514: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -11712,92 +14775,90 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(71576); +const tr = __importStar(__nccwpck_require__(88159)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 58464: +/***/ 88159: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -11810,7 +14871,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -11824,835 +14885,671 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(7377)); -const tunnel = __importStar(__nccwpck_require__(74294)); -const undici_1 = __nccwpck_require__(41773); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const events = __importStar(__nccwpck_require__(82361)); +const child = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const io = __importStar(__nccwpck_require__(47351)); +const ioUtil = __importStar(__nccwpck_require__(81962)); +const timers_1 = __nccwpck_require__(39512); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; } - readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on('data', (chunk) => { - chunks.push(chunk); - }); - this.message.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; } } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); + return s; } - else { - req.end(); + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; } } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + return this.toolPath; } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; } } - return info; + return this.args; } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); + _endsWith(str, end) { + return str.endsWith(end); } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); } - if (!useProxy) { - agent = this._agent; + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; } - // if agent is already assigned use that agent. - if (agent) { - return agent; + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote } else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + quoteHit = false; } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; } - // if tunneling agent isn't assigned create a new agent - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + if (!arg) { + // Need double quotation for empty argument + return '""'; } - // if agent is already assigned use that agent. - if (proxyAgent) { - return proxyAgent; + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; } - const usingSsl = parsedUrl.protocol === 'https:'; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` - }))); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; } - return proxyAgent; + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; } - _processResponse(res, options) { + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; + } + /** + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number + */ + exec() { return __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); } - else { - obj = JSON.parse(contents); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); } - response.result = obj; - } - response.headers = res.message.headers; + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); } - catch (err) { - // Invalid resource (contents not json); leaving result obj null + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); } else { - msg = `Failed request: (${statusCode})`; + resolve(exitCode); } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); } })); }); } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 7377: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; + } + arg += c; + escaped = false; } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } + else { + append(c); + } + continue; } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; + if (c === '\\' && escaped) { + append(c); + continue; } - })(); - if (proxyVar) { - try { - return new DecodedURL(proxyVar); + if (c === '\\' && inQuotes) { + escaped = true; + continue; } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new DecodedURL(`http://${proxyVar}`); + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; } + append(c); } - else { - return undefined; + if (arg.length > 0) { + args.push(arg.trim()); } + return args; } -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); + } + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; + } } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); } } - return false; -} -exports.checkBypass = checkBypass; -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return (hostLower === 'localhost' || - hostLower.startsWith('127.') || - hostLower.startsWith('[::1]') || - hostLower.startsWith('[0:0:0:0:0:0:0:1]')); -} -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); + _debug(message) { + this.emit('debug', message); } - get username() { - return this._decodedUsername; + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); } - get password() { - return this._decodedPassword; + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); } } -//# sourceMappingURL=proxy.js.map +//# sourceMappingURL=toolrunner.js.map /***/ }), -/***/ 87351: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 74087: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(5278); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; +exports.Context = void 0; +const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(22037); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } } - this.command = command; - this.properties = properties; - this.message = message; + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = + (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); } } -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map +exports.Context = Context; +//# sourceMappingURL=context.js.map /***/ }), -/***/ 42186: +/***/ 95438: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -12665,338 +15562,42 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(87351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(98041); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); - } - command_1.issueCommand('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); - } - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); - } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); -} -exports.saveState = saveState; +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(74087)); +const utils_1 = __nccwpck_require__(73030); +exports.context = new Context.Context(); /** - * Gets the value of an state set by this action's main execution. + * Returns a hydrated octokit ready to use for GitHub Actions * - * @param name name of the state to get - * @returns string + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); } -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(81327); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(81327); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(2981); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -//# sourceMappingURL=core.js.map +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map /***/ }), -/***/ 717: +/***/ 47914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -// For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -13009,55 +15610,10 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const uuid_1 = __nccwpck_require__(75840); -const utils_1 = __nccwpck_require__(5278); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 98041: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -13068,83 +15624,57 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(96255); -const auth_1 = __nccwpck_require__(35526); -const core_1 = __nccwpck_require__(42186); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); +exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(96255)); +const undici_1 = __nccwpck_require__(41773); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - core_1.debug(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; } -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +exports.getProxyAgentDispatcher = getProxyAgentDispatcher; +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +exports.getProxyFetch = getProxyFetch; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 2981: +/***/ 73030: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -13157,1900 +15687,572 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(74087)); +const Utils = __importStar(__nccwpck_require__(47914)); +// octokit + plugins +const core_1 = __nccwpck_require__(18525); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(94045); +const plugin_paginate_rest_1 = __nccwpck_require__(48945); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl), + fetch: Utils.getProxyFetch(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); /** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. + * Convience function to correctly format Octokit Options to pass into the constructor. * - * @param pth The path to platformize. - * @return string The platform-specific path. + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; } -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 81327: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 40673: +/***/ ((module) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; } -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 5278: -/***/ ((__unused_webpack_module, exports) => { +/***/ 18525: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(45030); +var import_before_after_hook = __nccwpck_require__(83682); +var import_request = __nccwpck_require__(89353); +var import_graphql = __nccwpck_require__(86422); +var import_auth_token = __nccwpck_require__(40673); + +// pkg/dist-src/version.js +var VERSION = "5.0.1"; + +// pkg/dist-src/index.js +var Octokit = class { + static { + this.VERSION = VERSION; + } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } }; -} -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + } + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new import_before_after_hook.Collection(); + const requestDefaults = { + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = [ + options.userAgent, + `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + ].filter(Boolean).join(" "); + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: () => { + }, + info: () => { + }, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, + options.log + ); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = (0, import_auth_token.createTokenAuth)(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; + } + const classConstructor = this.constructor; + classConstructor.plugins.forEach((plugin) => { + Object.assign(this, plugin(this, options)); + }); + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 71514: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 38713: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(71576); -const tr = __importStar(__nccwpck_require__(88159)); -/** - * Exec a command. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code - */ -function exec(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - // Path to tool to execute should be first arg - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); -} -exports.exec = exec; -/** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr - */ -function getExecOutput(commandLine, args, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); -} -exports.getExecOutput = getExecOutput; -//# sourceMappingURL=exec.js.map +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ }), +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); -/***/ 88159: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(45030); -"use strict"; +// pkg/dist-src/version.js +var VERSION = "9.0.1"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const events = __importStar(__nccwpck_require__(82361)); -const child = __importStar(__nccwpck_require__(32081)); -const path = __importStar(__nccwpck_require__(71017)); -const io = __importStar(__nccwpck_require__(47351)); -const ioUtil = __importStar(__nccwpck_require__(81962)); -const timers_1 = __nccwpck_require__(39512); -/* eslint-disable @typescript-eslint/unbound-method */ -const IS_WINDOWS = process.platform === 'win32'; -/* - * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. - */ -class ToolRunner extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool - if (IS_WINDOWS) { - // Windows + cmd file - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows + verbatim - else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows (regular) - else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } - else { - // OSX/Linux - this can likely be improved with some form of quoting. - // creating processes on Unix is fundamentally different than Windows. - // on Unix, execvp() takes an arg array. - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); - return ''; - } + +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +// pkg/dist-src/util/merge-deep.js +var import_is_plain_object = __nccwpck_require__(63287); +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if ((0, import_is_plain_object.isPlainObject)(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } - } - return this.toolPath; + }); + return result; +} + +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += ' '; - argline += options.windowsVerbatimArguments - ? a - : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; + } + return obj; +} + +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); } - _endsWith(str, end) { - return str.endsWith(end); + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} + +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); + if (!matches) { + return []; + } + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} + +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} + +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } - _windowsQuoteCmdArg(arg) { - // for .exe, apply the normal quoting rules that libuv applies - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - // otherwise apply quoting rules specific to the cmd.exe command line parser. - // the libuv rules are generic and are not designed specifically for cmd.exe - // command line parser. - // - // for a detailed description of the cmd.exe command line parser, refer to - // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 - // need quotes for empty arg - if (!arg) { - return '""'; - } - // determine whether the arg needs to be quoted - const cmdSpecialChars = [ - ' ', - '\t', - '&', - '(', - ')', - '[', - ']', - '{', - '}', - '^', - '=', - ';', - '!', - "'", - '+', - ',', - '`', - '~', - '|', - '<', - '>', - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some(x => x === char)) { - needsQuotes = true; - break; + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); } + }); } - // short-circuit if quotes not needed - if (!needsQuotes) { - return arg; - } - // the following quoting rules are very similar to the rules that by libuv applies. - // - // 1) wrap the string in quotes - // - // 2) double-up quotes - i.e. " => "" - // - // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately - // doesn't work well with a cmd.exe command line. - // - // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. - // for example, the command line: - // foo.exe "myarg:""my val""" - // is parsed by a .NET console app into an arg array: - // [ "myarg:\"my val\"" ] - // which is the same end result when applying libuv quoting rules. although the actual - // command line from libuv quoting rules would look like: - // foo.exe "myarg:\"my val\"" - // - // 3) double-up slashes that precede a quote, - // e.g. hello \world => "hello \world" - // hello\"world => "hello\\""world" - // hello\\"world => "hello\\\\""world" - // hello world\ => "hello world\\" - // - // technically this is not required for a cmd.exe command line, or the batch argument parser. - // the reasons for including this as a .cmd quoting rule are: - // - // a) this is optimized for the scenario where the argument is passed from the .cmd file to an - // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. - // - // b) it's what we've been doing previously (by deferring to node default behavior) and we - // haven't heard any complaints about that aspect. - // - // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be - // escaped when used on the command line directly - even though within a .cmd file % can be escaped - // by using %%. - // - // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts - // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. - // - // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would - // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the - // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args - // to an external program. - // - // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. - // % can be escaped within a .cmd file. - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; // double the slash - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; // double the quote - } - else { - quoteHit = false; + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); } + }); } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _uvQuoteCmdArg(arg) { - // Tool runner wraps child_process.spawn() and needs to apply the same quoting as - // Node in certain cases where the undocumented spawn option windowsVerbatimArguments - // is used. - // - // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, - // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), - // pasting copyright notice from Node within this function: - // - // Copyright Joyent, Inc. and other Node contributors. All rights reserved. - // - // Permission is hereby granted, free of charge, to any person obtaining a copy - // of this software and associated documentation files (the "Software"), to - // deal in the Software without restriction, including without limitation the - // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - // sell copies of the Software, and to permit persons to whom the Software is - // furnished to do so, subject to the following conditions: - // - // The above copyright notice and this permission notice shall be included in - // all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - // IN THE SOFTWARE. - if (!arg) { - // Need double quotation for empty argument - return '""'; - } - if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { - // No quotation needed - return arg; - } - if (!arg.includes('"') && !arg.includes('\\')) { - // No embedded double quotes or backslashes, so I can just wrap - // quote marks around the whole thing. - return `"${arg}"`; - } - // Expected input/output: - // input : hello"world - // output: "hello\"world" - // input : hello""world - // output: "hello\"\"world" - // input : hello\world - // output: hello\world - // input : hello\\world - // output: hello\\world - // input : hello\"world - // output: "hello\\\"world" - // input : hello\\"world - // output: "hello\\\\\"world" - // input : hello world\ - // output: "hello world\\" - note the comment in libuv actually reads "hello world\" - // but it appears the comment is wrong, it should be "hello world\\" - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '\\'; - } - else { - quoteHit = false; - } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); + } } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 10000 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result['windowsVerbatimArguments'] = - options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter(this, void 0, void 0, function* () { - // root the tool path if it is unrooted and contains relative pathing - if (!ioUtil.isRooted(this.toolPath) && - (this.toolPath.includes('/') || - (IS_WINDOWS && this.toolPath.includes('\\')))) { - // prefer options.cwd if it is specified, however options.cwd may also need to be rooted - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - // if the tool is only a file name, then resolve it from the PATH - // otherwise verify it exists (add extension on Windows if necessary) - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug('arguments:'); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on('debug', (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; - if (cp.stdout) { - cp.stdout.on('data', (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ''; - if (cp.stderr) { - cp.stderr.on('data', (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && - optionsNonNull.errStream && - optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr - ? optionsNonNull.errStream - : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on('error', (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on('exit', (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on('close', (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on('done', (error, exitCode) => { - if (stdbuffer.length > 0) { - this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - reject(error); - } - else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error('child process missing stdin'); - } - cp.stdin.end(this.options.input); - } - })); + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); }); - } -} -exports.ToolRunner = ToolRunner; -/** - * Convert an arg string to an array of args. Handles escaping - * - * @param argString string of arguments - * @returns string[] array of arguments - */ -function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ''; - function append(c) { - // we only escape double quotes. - if (escaped && c !== '"') { - arg += '\\'; + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } - else { - append(c); - } - continue; - } - if (c === '\\' && escaped) { - append(c); - continue; - } - if (c === '\\' && inQuotes) { - escaped = true; - continue; - } - if (c === ' ' && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ''; - } - continue; - } - append(c); - } - if (arg.length > 0) { - args.push(arg.trim()); - } - return args; -} -exports.argStringToArray = argStringToArray; -class ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; // tracks whether the process has exited and stdio is closed - this.processError = ''; - this.processExitCode = 0; - this.processExited = false; // tracks whether the process has exited - this.processStderr = false; // tracks whether stderr was written to - this.delay = 10000; // 10 seconds - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error('toolPath must not be empty'); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); - } - } - _debug(message) { - this.emit('debug', message); - } - _setResult() { - // determine whether there is an error - let error; - if (this.processExited) { - if (this.processError) { - error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } - else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } - else if (this.processStderr && this.options.failOnStdErr) { - error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - // clear the timeout - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit('done', error, this.processExitCode); - } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / - 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); - } -} -//# sourceMappingURL=toolrunner.js.map - -/***/ }), - -/***/ 74087: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = - (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 95438: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const utils_1 = __nccwpck_require__(73030); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 47914: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(96255)); -const undici_1 = __nccwpck_require__(41773); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); -} -exports.getProxyAgentDispatcher = getProxyAgentDispatcher; -function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; -} -exports.getProxyFetch = getProxyFetch; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 73030: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const Utils = __importStar(__nccwpck_require__(47914)); -// octokit + plugins -const core_1 = __nccwpck_require__(18525); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(94045); -const plugin_paginate_rest_1 = __nccwpck_require__(48945); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl), - fetch: Utils.getProxyFetch(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; -} -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 40673: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - createTokenAuth: () => createTokenAuth -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/auth.js -var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -var REGEX_IS_INSTALLATION = /^ghs_/; -var REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} - -// pkg/dist-src/with-authorization-prefix.js -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} - -// pkg/dist-src/hook.js -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -// pkg/dist-src/index.js -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 18525: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(dist_src_exports); -var import_universal_user_agent = __nccwpck_require__(45030); -var import_before_after_hook = __nccwpck_require__(83682); -var import_request = __nccwpck_require__(89353); -var import_graphql = __nccwpck_require__(86422); -var import_auth_token = __nccwpck_require__(40673); - -// pkg/dist-src/version.js -var VERSION = "5.0.1"; - -// pkg/dist-src/index.js -var Octokit = class { - static { - this.VERSION = VERSION; - } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static { - this.plugins = []; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static { - this.plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - } - }; - return NewOctokit; - } - constructor(options = {}) { - const hook = new import_before_after_hook.Collection(); - const requestDefaults = { - baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = [ - options.userAgent, - `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - ].filter(Boolean).join(" "); - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = import_request.request.defaults(requestDefaults); - this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); - this.log = Object.assign( - { - debug: () => { - }, - info: () => { - }, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, - options.log - ); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = (0, import_auth_token.createTokenAuth)(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook.wrap("request", auth.hook); - this.auth = auth; - } - const classConstructor = this.constructor; - classConstructor.plugins.forEach((plugin) => { - Object.assign(this, plugin(this, options)); - }); - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 38713: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - endpoint: () => endpoint -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/defaults.js -var import_universal_user_agent = __nccwpck_require__(45030); - -// pkg/dist-src/version.js -var VERSION = "9.0.1"; - -// pkg/dist-src/defaults.js -var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; - -// pkg/dist-src/util/lowercase-keys.js -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -// pkg/dist-src/util/merge-deep.js -var import_is_plain_object = __nccwpck_require__(63287); -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if ((0, import_is_plain_object.isPlainObject)(options[key])) { - if (!(key in defaults)) - Object.assign(result, { [key]: options[key] }); - else - result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} - -// pkg/dist-src/util/remove-undefined-properties.js -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} - -// pkg/dist-src/merge.js -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} - -// pkg/dist-src/util/add-query-parameters.js -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -// pkg/dist-src/util/extract-url-variable-names.js -var urlVariableRegex = /\{[^}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - if (!matches) { - return []; - } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} - -// pkg/dist-src/util/omit.js -function omit(object, keysToOmit) { - return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} - -// pkg/dist-src/util/url-template.js -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } + } else { + return encodeReserved(literal); + } } ); } @@ -44257,781 +45459,6 @@ exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 14175: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* - -The MIT License (MIT) - -Original Library - - Copyright (c) Marak Squires - -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - -var colors = {}; -module['exports'] = colors; - -colors.themes = {}; - -var util = __nccwpck_require__(73837); -var ansiStyles = colors.styles = __nccwpck_require__(95691); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); - -colors.supportsColor = (__nccwpck_require__(21959).supportsColor); - -if (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; -} - -colors.enable = function() { - colors.enabled = true; -}; - -colors.disable = function() { - colors.enabled = false; -}; - -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); -}; - -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; - } - - var styleMap = ansiStyles[style]; - - // Stylize should work for non-ANSI styles, too - if (!styleMap && style in colors) { - // Style maps like trap operate as functions on strings; - // they don't have properties like open or close. - return colors[style](str); - } - - return styleMap.open + str + styleMap.close; -}; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return str.replace(matchOperatorsRe, '\\$&'); -}; - -function build(_styles) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - builder._styles = _styles; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - builder.__proto__ = proto; - return builder; -} - -var styles = (function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = - new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - }, - }; - }); - return ret; -})(); - -var proto = defineProps(function colors() {}, styles); - -function applyStyle() { - var args = Array.prototype.slice.call(arguments); - - var str = args.map(function(arg) { - // Use weak equality check so we can colorize null/undefined in safe mode - if (arg != null && arg.constructor === String) { - return arg; - } else { - return util.inspect(arg); - } - }).join(' '); - - if (!colors.enabled || !str) { - return str; - } - - var newLinesPresent = str.indexOf('\n') != -1; - - var nestedStyles = this._styles; - - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - if (newLinesPresent) { - str = str.replace(newLineRegex, function(match) { - return code.close + match + code.open; - }); - } - } - - return str; -} - -colors.setTheme = function(theme) { - if (typeof theme === 'string') { - console.log('colors.setTheme now only accepts an object, not a string. ' + - 'If you are trying to set a theme from a file, it is now your (the ' + - 'caller\'s) responsibility to require the file. The old syntax ' + - 'looked like colors.setTheme(__dirname + ' + - '\'/../themes/generic-logging.js\'); The new syntax looks like '+ - 'colors.setTheme(require(__dirname + ' + - '\'/../themes/generic-logging.js\'));'); - return; - } - for (var style in theme) { - (function(style) { - colors[style] = function(str) { - if (typeof theme[style] === 'object') { - var out = str; - for (var i in theme[style]) { - out = colors[theme[style][i]](out); - } - return out; - } - return colors[theme[style]](str); - }; - })(style); - } -}; - -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, - }; - }); - return ret; -} - -var sequencer = function sequencer(map, str) { - var exploded = str.split(''); - exploded = exploded.map(map); - return exploded.join(''); -}; - -// custom formatter methods -colors.trap = __nccwpck_require__(29493); -colors.zalgo = __nccwpck_require__(80090); - -// maps -colors.maps = {}; -colors.maps.america = __nccwpck_require__(29337)(colors); -colors.maps.zebra = __nccwpck_require__(3792)(colors); -colors.maps.rainbow = __nccwpck_require__(19565)(colors); -colors.maps.random = __nccwpck_require__(78212)(colors); - -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); -} - -defineProps(colors, init()); - - -/***/ }), - -/***/ 29493: -/***/ ((module) => { - -module['exports'] = function runTheTrap(text, options) { - var result = ''; - text = text || 'Run the trap, drop the bass'; - text = text.split(''); - var trap = { - a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], - b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], - c: ['\u00a9', '\u023b', '\u03fe'], - d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], - e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', - '\u0a6c'], - f: ['\u04fa'], - g: ['\u0262'], - h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], - i: ['\u0f0f'], - j: ['\u0134'], - k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], - l: ['\u0139'], - m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], - n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], - o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', - '\u06dd', '\u0e4f'], - p: ['\u01f7', '\u048e'], - q: ['\u09cd'], - r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], - s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], - t: ['\u0141', '\u0166', '\u0373'], - u: ['\u01b1', '\u054d'], - v: ['\u05d8'], - w: ['\u0428', '\u0460', '\u047c', '\u0d70'], - x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], - y: ['\u00a5', '\u04b0', '\u04cb'], - z: ['\u01b5', '\u0240'], - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [' ']; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== 'undefined') { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; -}; - - -/***/ }), - -/***/ 80090: -/***/ ((module) => { - -// please no -module['exports'] = function zalgo(text, options) { - text = text || ' he is here '; - var soul = { - 'up': [ - '̍', '̎', '̄', '̅', - '̿', '̑', '̆', '̐', - '͒', '͗', '͑', '̇', - '̈', '̊', '͂', '̓', - '̈', '͊', '͋', '͌', - '̃', '̂', '̌', '͐', - '̀', '́', '̋', '̏', - '̒', '̓', '̔', '̽', - '̉', 'ͣ', 'ͤ', 'ͥ', - 'ͦ', 'ͧ', 'ͨ', 'ͩ', - 'ͪ', 'ͫ', 'ͬ', 'ͭ', - 'ͮ', 'ͯ', '̾', '͛', - '͆', '̚', - ], - 'down': [ - '̖', '̗', '̘', '̙', - '̜', '̝', '̞', '̟', - '̠', '̤', '̥', '̦', - '̩', '̪', '̫', '̬', - '̭', '̮', '̯', '̰', - '̱', '̲', '̳', '̹', - '̺', '̻', '̼', 'ͅ', - '͇', '͈', '͉', '͍', - '͎', '͓', '͔', '͕', - '͖', '͙', '͚', '̣', - ], - 'mid': [ - '̕', '̛', '̀', '́', - '͘', '̡', '̢', '̧', - '̨', '̴', '̵', '̶', - '͜', '͝', '͞', - '͟', '͠', '͢', '̸', - '̷', '͡', ' ҉', - ], - }; - var all = [].concat(soul.up, soul.down, soul.mid); - - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } - - function isChar(character) { - var bool = false; - all.filter(function(i) { - bool = (i === character); - }); - return bool; - } - - - function heComes(text, options) { - var result = ''; - var counts; - var l; - options = options || {}; - options['up'] = - typeof options['up'] !== 'undefined' ? options['up'] : true; - options['mid'] = - typeof options['mid'] !== 'undefined' ? options['mid'] : true; - options['down'] = - typeof options['down'] !== 'undefined' ? options['down'] : true; - options['size'] = - typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; - text = text.split(''); - for (l in text) { - if (isChar(l)) { - continue; - } - result = result + text[l]; - counts = {'up': 0, 'down': 0, 'mid': 0}; - switch (options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } - - var arr = ['up', 'mid', 'down']; - for (var d in arr) { - var index = arr[d]; - for (var i = 0; i <= counts[index]; i++) { - if (options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - } - // don't summon him - return heComes(text, options); -}; - - - -/***/ }), - -/***/ 29337: -/***/ ((module) => { - -module['exports'] = function(colors) { - return function(letter, i, exploded) { - if (letter === ' ') return letter; - switch (i%3) { - case 0: return colors.red(letter); - case 1: return colors.white(letter); - case 2: return colors.blue(letter); - } - }; -}; - - -/***/ }), - -/***/ 19565: -/***/ ((module) => { - -module['exports'] = function(colors) { - // RoY G BiV - var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; - return function(letter, i, exploded) { - if (letter === ' ') { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; -}; - - - -/***/ }), - -/***/ 78212: -/***/ ((module) => { - -module['exports'] = function(colors) { - var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', - 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', - 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; - return function(letter, i, exploded) { - return letter === ' ' ? letter : - colors[ - available[Math.round(Math.random() * (available.length - 2))] - ](letter); - }; -}; - - -/***/ }), - -/***/ 3792: -/***/ ((module) => { - -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; - - -/***/ }), - -/***/ 95691: -/***/ ((module) => { - -/* -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - -var styles = {}; -module['exports'] = styles; - -var codes = { - reset: [0, 0], - - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], - - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], - - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgGray: [100, 49], - bgGrey: [100, 49], - - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], - - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49], - -}; - -Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = '\u001b[' + val[0] + 'm'; - style.close = '\u001b[' + val[1] + 'm'; -}); - - -/***/ }), - -/***/ 63680: -/***/ ((module) => { - -"use strict"; -/* -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - - - -module.exports = function(flag, argv) { - argv = argv || process.argv; - - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); - - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; - - -/***/ }), - -/***/ 21959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - - - -var os = __nccwpck_require__(22037); -var hasFlag = __nccwpck_require__(63680); - -var env = process.env; - -var forceColor = void 0; -if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') - || hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 - || parseInt(env.FORCE_COLOR, 10) !== 0; -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - var min = forceColor ? 1 : 0; - - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first - // Windows release that supports 256 colors. Windows 10 build 14931 is the - // first release that supports 16m/TrueColor. - var osRelease = os.release().split('.'); - if (Number(process.versions.node.split('.')[0]) >= 8 - && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); - } - - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - if (env.TERM === 'dumb') { - return min; - } - - return min; -} - -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), -}; - - -/***/ }), - -/***/ 59256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// -// Remark: Requiring this file will use the "safe" colors API, -// which will not touch String.prototype. -// -// var colors = require('colors/safe'); -// colors.red("foo") -// -// -var colors = __nccwpck_require__(14175); -module['exports'] = colors; - - /***/ }), /***/ 2856: @@ -46454,2461 +46881,6 @@ function parseParams (str) { module.exports = parseParams -/***/ }), - -/***/ 55128: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const rabin_karp_1 = __nccwpck_require__(8105); -const validators_1 = __nccwpck_require__(82218); -const mode_1 = __nccwpck_require__(27899); -// TODO replace to own event emitter -const EventEmitter = __nccwpck_require__(11848); -class Detector extends EventEmitter { - constructor(tokenizer, store, cloneValidators = [], options) { - super(); - this.tokenizer = tokenizer; - this.store = store; - this.cloneValidators = cloneValidators; - this.options = options; - this.initCloneValidators(); - this.algorithm = new rabin_karp_1.RabinKarp(this.options, this, this.cloneValidators); - this.options.minTokens = this.options.minTokens || 50; - this.options.maxLines = this.options.maxLines || 500; - this.options.minLines = this.options.minLines || 5; - this.options.mode = this.options.mode || mode_1.mild; - } - detect(id, text, format) { - return __awaiter(this, void 0, void 0, function* () { - const tokenMaps = this.tokenizer.generateMaps(id, text, format, this.options); - // TODO change stores implementation - this.store.namespace(format); - const detect = (tokenMap, clones) => __awaiter(this, void 0, void 0, function* () { - if (tokenMap) { - this.emit('START_DETECTION', { source: tokenMap }); - return this.algorithm - .run(tokenMap, this.store) - .then((clns) => { - clones.push(...clns); - const nextTokenMap = tokenMaps.pop(); - if (nextTokenMap) { - return detect(nextTokenMap, clones); - } - else { - return clones; - } - }); - } - }); - return detect(tokenMaps.pop(), []); - }); - } - initCloneValidators() { - if (this.options.minLines || this.options.maxLines) { - this.cloneValidators.push(new validators_1.LinesLengthCloneValidator()); - } - } -} -exports.Detector = Detector; -//# sourceMappingURL=detector.js.map - -/***/ }), - -/***/ 84511: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(55128)); -__export(__nccwpck_require__(27899)); -__export(__nccwpck_require__(81070)); -__export(__nccwpck_require__(67799)); -__export(__nccwpck_require__(54628)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 27899: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function strict(token) { - return token.type !== 'ignore'; -} -exports.strict = strict; -function mild(token) { - return strict(token) && token.type !== 'empty' && token.type !== 'new_line'; -} -exports.mild = mild; -function weak(token) { - return mild(token) - && token.format !== 'comment' - && token.type !== 'comment' - && token.type !== 'block-comment'; -} -exports.weak = weak; -const MODES = { - mild, - strict, - weak, -}; -function getModeByName(name) { - if (name in MODES) { - return MODES[name]; - } - throw new Error(`Mode ${name} does not supported yet.`); -} -exports.getModeByName = getModeByName; -function getModeHandler(mode) { - return typeof mode === 'string' ? getModeByName(mode) : mode; -} -exports.getModeHandler = getModeHandler; -//# sourceMappingURL=mode.js.map - -/***/ }), - -/***/ 81070: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const mode_1 = __nccwpck_require__(27899); -function getDefaultOptions() { - return { - executionId: new Date().toISOString(), - path: [process.cwd()], - mode: mode_1.getModeHandler('mild'), - minLines: 5, - maxLines: 1000, - maxSize: '100kb', - minTokens: 50, - output: './report', - reporters: ['console'], - ignore: [], - threshold: undefined, - formatsExts: {}, - debug: false, - silent: false, - blame: false, - cache: true, - absolute: false, - noSymlinks: false, - skipLocal: false, - ignoreCase: false, - gitignore: false, - reportersOptions: {}, - exitCode: 0, - }; -} -exports.getDefaultOptions = getDefaultOptions; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getOption(name, options) { - const defaultOptions = getDefaultOptions(); - return options ? options[name] || defaultOptions[name] : defaultOptions[name]; -} -exports.getOption = getOption; -//# sourceMappingURL=options.js.map - -/***/ }), - -/***/ 8105: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const validators_1 = __nccwpck_require__(82218); -class RabinKarp { - constructor(options, eventEmitter, cloneValidators) { - this.options = options; - this.eventEmitter = eventEmitter; - this.cloneValidators = cloneValidators; - } - run(tokenMap, store) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve => { - let mapFrameInStore; - let clone = null; - const clones = []; - // eslint-disable-next-line @typescript-eslint/explicit-function-return-type - const loop = () => { - const iteration = tokenMap.next(); - store - .get(iteration.value.id) - .then((mapFrameFromStore) => { - mapFrameInStore = mapFrameFromStore; - if (!clone) { - clone = RabinKarp.createClone(tokenMap.getFormat(), iteration.value, mapFrameInStore); - } - }, () => { - if (clone && this.validate(clone)) { - clones.push(clone); - } - clone = null; - if (iteration.value.id) { - return store.set(iteration.value.id, iteration.value); - } - }) - .finally(() => { - if (!iteration.done) { - if (clone) { - clone = RabinKarp.enlargeClone(clone, iteration.value, mapFrameInStore); - } - loop(); - } - else { - resolve(clones); - } - }); - }; - loop(); - })); - }); - } - validate(clone) { - const validation = validators_1.runCloneValidators(clone, this.options, this.cloneValidators); - if (validation.status) { - this.eventEmitter.emit('CLONE_FOUND', { clone }); - } - else { - this.eventEmitter.emit('CLONE_SKIPPED', { clone, validation }); - } - return validation.status; - } - static createClone(format, mapFrameA, mapFrameB) { - return { - format, - foundDate: new Date().getTime(), - duplicationA: { - sourceId: mapFrameA.sourceId, - start: mapFrameA.start.loc.start, - end: mapFrameA.end.loc.end, - range: [mapFrameA.start.range[0], mapFrameA.end.range[1]], - }, - duplicationB: { - sourceId: mapFrameB.sourceId, - start: mapFrameB.start.loc.start, - end: mapFrameB.end.loc.end, - range: [mapFrameB.start.range[0], mapFrameB.end.range[1]], - }, - }; - } - static enlargeClone(clone, mapFrameA, mapFrameB) { - clone.duplicationA.range[1] = mapFrameA.end.range[1]; - clone.duplicationA.end = mapFrameA.end.loc.end; - clone.duplicationB.range[1] = mapFrameB.end.range[1]; - clone.duplicationB.end = mapFrameB.end.loc.end; - return clone; - } -} -exports.RabinKarp = RabinKarp; -//# sourceMappingURL=rabin-karp.js.map - -/***/ }), - -/***/ 67799: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class Statistic { - constructor() { - this.statistic = { - detectionDate: new Date().toISOString(), - formats: {}, - total: Statistic.getDefaultStatistic(), - }; - } - static getDefaultStatistic() { - return { - lines: 0, - tokens: 0, - sources: 0, - clones: 0, - duplicatedLines: 0, - duplicatedTokens: 0, - percentage: 0, - percentageTokens: 0, - newDuplicatedLines: 0, - newClones: 0, - }; - } - subscribe() { - return { - CLONE_FOUND: this.cloneFound.bind(this), - START_DETECTION: this.matchSource.bind(this), - }; - } - getStatistic() { - return this.statistic; - } - cloneFound(payload) { - const { clone } = payload; - const id = clone.duplicationA.sourceId; - const id2 = clone.duplicationB.sourceId; - const linesCount = clone.duplicationA.end.line - clone.duplicationA.start.line; - const duplicatedTokens = clone.duplicationA.end.position - clone.duplicationA.start.position; - this.statistic.total.clones++; - this.statistic.total.duplicatedLines += linesCount; - this.statistic.total.duplicatedTokens += duplicatedTokens; - this.statistic.formats[clone.format].total.clones++; - this.statistic.formats[clone.format].total.duplicatedLines += linesCount; - this.statistic.formats[clone.format].total.duplicatedTokens += duplicatedTokens; - this.statistic.formats[clone.format].sources[id].clones++; - this.statistic.formats[clone.format].sources[id].duplicatedLines += linesCount; - this.statistic.formats[clone.format].sources[id].duplicatedTokens += duplicatedTokens; - this.statistic.formats[clone.format].sources[id2].clones++; - this.statistic.formats[clone.format].sources[id2].duplicatedLines += linesCount; - this.statistic.formats[clone.format].sources[id2].duplicatedTokens += duplicatedTokens; - this.updatePercentage(clone.format); - } - matchSource(payload) { - const { source } = payload; - const format = source.getFormat(); - if (!(format in this.statistic.formats)) { - this.statistic.formats[format] = { - sources: {}, - total: Statistic.getDefaultStatistic(), - }; - } - this.statistic.total.sources++; - this.statistic.total.lines += source.getLinesCount(); - this.statistic.total.tokens += source.getTokensCount(); - this.statistic.formats[format].total.sources++; - this.statistic.formats[format].total.lines += source.getLinesCount(); - this.statistic.formats[format].total.tokens += source.getTokensCount(); - this.statistic.formats[format].sources[source.getId()] = - this.statistic.formats[format].sources[source.getId()] || Statistic.getDefaultStatistic(); - this.statistic.formats[format].sources[source.getId()].sources = 1; - this.statistic.formats[format].sources[source.getId()].lines += source.getLinesCount(); - this.statistic.formats[format].sources[source.getId()].tokens += source.getTokensCount(); - this.updatePercentage(format); - } - updatePercentage(format) { - this.statistic.total.percentage = Statistic.calculatePercentage(this.statistic.total.lines, this.statistic.total.duplicatedLines); - this.statistic.total.percentageTokens = Statistic.calculatePercentage(this.statistic.total.tokens, this.statistic.total.duplicatedTokens); - this.statistic.formats[format].total.percentage = Statistic.calculatePercentage(this.statistic.formats[format].total.lines, this.statistic.formats[format].total.duplicatedLines); - this.statistic.formats[format].total.percentageTokens = Statistic.calculatePercentage(this.statistic.formats[format].total.tokens, this.statistic.formats[format].total.duplicatedTokens); - Object.entries(this.statistic.formats[format].sources).forEach(([id, stat]) => { - this.statistic.formats[format].sources[id].percentage = Statistic.calculatePercentage(stat.lines, stat.duplicatedLines); - this.statistic.formats[format].sources[id].percentageTokens = Statistic.calculatePercentage(stat.tokens, stat.duplicatedTokens); - }); - } - static calculatePercentage(total, cloned) { - return total ? Math.round((10000 * cloned) / total) / 100 : 0.0; - } -} -exports.Statistic = Statistic; -//# sourceMappingURL=statistic.js.map - -/***/ }), - -/***/ 54628: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class MemoryStore { - constructor() { - this.values = {}; - } - namespace(namespace) { - this._namespace = namespace; - this.values[namespace] = this.values[namespace] || {}; - } - get(key) { - return new Promise((resolve, reject) => { - if (key in this.values[this._namespace]) { - resolve(this.values[this._namespace][key]); - } - else { - reject(new Error('not found')); - } - }); - } - set(key, value) { - this.values[this._namespace][key] = value; - return Promise.resolve(value); - } - close() { - this.values = {}; - } -} -exports.MemoryStore = MemoryStore; -//# sourceMappingURL=memory.js.map - -/***/ }), - -/***/ 82218: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(52214)); -__export(__nccwpck_require__(43865)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 52214: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -class LinesLengthCloneValidator { - validate(clone, options) { - const lines = clone.duplicationA.end.line - clone.duplicationA.start.line; - const status = lines >= options.minLines; - return { - status, - message: status ? ['ok'] : [`Lines of code less than limit (${lines} < ${options.minLines})`], - }; - } -} -exports.LinesLengthCloneValidator = LinesLengthCloneValidator; -//# sourceMappingURL=lines-length-clone.validator.js.map - -/***/ }), - -/***/ 43865: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function runCloneValidators(clone, options, validators) { - return validators.reduce((acc, validator) => { - const res = validator.validate(clone, options); - return Object.assign(Object.assign({}, acc), { status: res.status && acc.status, message: res.message ? [...acc.message, ...res.message] : acc.message }); - }, { status: true, message: [], clone }); -} -exports.runCloneValidators = runCloneValidators; -//# sourceMappingURL=validator.js.map - -/***/ }), - -/***/ 51908: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core_1 = __nccwpck_require__(84511); -const fast_glob_1 = __nccwpck_require__(43664); -const tokenizer_1 = __nccwpck_require__(92080); -const fs_extra_1 = __nccwpck_require__(5630); -const safe_1 = __nccwpck_require__(41997); -const fs_1 = __nccwpck_require__(57147); -const bytes = __nccwpck_require__(86966); -function isFile(path) { - try { - const stat = fs_1.lstatSync(path); - return stat.isFile(); - } - catch (e) { - // lstatSync throws an error if path doesn't exist - return false; - } -} -function isSymlink(path) { - try { - const stat = fs_1.lstatSync(path); - return stat.isSymbolicLink(); - } - catch (e) { - // lstatSync throws an error if path doesn't exist - return false; - } -} -function skipNotSupportedFormats(options) { - return (entry) => { - const { path } = entry; - const format = tokenizer_1.getFormatByFile(path, options.formatsExts); - const shouldNotSkip = format && options.format && options.format.includes(format); - if ((options.debug || options.verbose) && !shouldNotSkip) { - console.log(`File ${path} skipped! Format "${format}" does not included to supported formats.`); - } - return shouldNotSkip; - }; -} -function skipBigFiles(options) { - return (entry) => { - const { stats, path } = entry; - const shouldSkip = bytes.parse(stats.size) > bytes.parse(core_1.getOption('maxSize', options)); - if (options.debug && shouldSkip) { - console.log(`File ${path} skipped! Size more then limit (${bytes(stats.size)} > ${core_1.getOption('maxSize', options)})`); - } - return !shouldSkip; - }; -} -function skipFilesIfLinesOfContentNotInLimits(options) { - return (entry) => { - const { path, content } = entry; - const lines = content.split('\n').length; - const minLines = core_1.getOption('minLines', options); - const maxLines = core_1.getOption('maxLines', options); - if (lines < minLines || lines > maxLines) { - if ((options.debug || options.verbose)) { - console.log(safe_1.grey(`File ${path} skipped! Code lines=${lines} not in limits (${minLines}:${maxLines})`)); - } - return false; - } - return true; - }; -} -function addContentToEntry(entry) { - const { path } = entry; - const content = fs_extra_1.readFileSync(path).toString(); - return Object.assign(Object.assign({}, entry), { content }); -} -function getFilesToDetect(options) { - const pattern = options.pattern || '**/*'; - let patterns = options.path; - if (options.noSymlinks) { - patterns = patterns.filter((path) => !isSymlink(path)); - } - patterns = patterns.map((path) => { - const currentPath = fs_extra_1.realpathSync(path); - if (isFile(currentPath)) { - return path; - } - return path.endsWith('/') ? `${path}${pattern}` : `${path}/${pattern}`; - }); - return fast_glob_1.sync(patterns, { - ignore: options.ignore, - onlyFiles: true, - dot: true, - stats: true, - absolute: options.absolute, - followSymbolicLinks: !options.noSymlinks, - }) - .filter(skipNotSupportedFormats(options)) - .filter(skipBigFiles(options)) - .map(addContentToEntry) - .filter(skipFilesIfLinesOfContentNotInLimits(options)); -} -exports.getFilesToDetect = getFilesToDetect; -//# sourceMappingURL=files.js.map - -/***/ }), - -/***/ 74574: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const blamer_1 = __nccwpck_require__(56781); -class BlamerHook { - process(clones) { - return Promise.all(clones.map((clone) => BlamerHook.blameLines(clone))); - } - static blameLines(clone) { - return __awaiter(this, void 0, void 0, function* () { - const blamer = new blamer_1.default(); - const blamedFileA = yield blamer.blameByFile(clone.duplicationA.sourceId); - const blamedFileB = yield blamer.blameByFile(clone.duplicationB.sourceId); - clone.duplicationA.blame = BlamerHook.getBlamedLines(blamedFileA, clone.duplicationA.start.line, clone.duplicationA.end.line); - clone.duplicationB.blame = BlamerHook.getBlamedLines(blamedFileB, clone.duplicationB.start.line, clone.duplicationB.end.line); - return clone; - }); - } - static getBlamedLines(blamedFiles, start, end) { - // TODO rewrite the method - const [file] = Object.keys(blamedFiles); - const result = {}; - Object.keys(blamedFiles[file]) - .filter((lineNumber) => { - return Number(lineNumber) >= start && Number(lineNumber) <= end; - }) - .map((lineNumber) => blamedFiles[file][lineNumber]) - .forEach((info) => { - result[info.line] = info; - }); - return result; - } -} -exports.BlamerHook = BlamerHook; -//# sourceMappingURL=blamer.js.map - -/***/ }), - -/***/ 44810: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __nccwpck_require__(57147); -class FragmentsHook { - process(clones) { - return Promise.all(clones.map((clone) => FragmentsHook.addFragments(clone))); - } - static addFragments(clone) { - const codeA = fs_1.readFileSync(clone.duplicationA.sourceId).toString(); - const codeB = fs_1.readFileSync(clone.duplicationB.sourceId).toString(); - clone.duplicationA.fragment = codeA.substring(clone.duplicationA.range[0], clone.duplicationA.range[1]); - clone.duplicationB.fragment = codeB.substring(clone.duplicationB.range[0], clone.duplicationB.range[1]); - return clone; - } -} -exports.FragmentsHook = FragmentsHook; -//# sourceMappingURL=fragment.js.map - -/***/ }), - -/***/ 88131: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(74574)); -__export(__nccwpck_require__(44810)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 88241: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core_1 = __nccwpck_require__(84511); -const tokenizer_1 = __nccwpck_require__(92080); -const validators_1 = __nccwpck_require__(20733); -class InFilesDetector { - constructor(tokenizer, store, statistic, options) { - this.tokenizer = tokenizer; - this.store = store; - this.statistic = statistic; - this.options = options; - this.reporters = []; - this.subscribes = []; - this.postHooks = []; - this.registerSubscriber(this.statistic); - } - registerReporter(reporter) { - this.reporters.push(reporter); - } - registerSubscriber(subscriber) { - this.subscribes.push(subscriber); - } - registerHook(hook) { - this.postHooks.push(hook); - } - detect(fls) { - const files = fls.filter((f) => !!f); - if (files.length === 0) { - return Promise.resolve([]); - } - const options = this.options; - const hooks = [...this.postHooks]; - const store = this.store; - const validators = []; - if (options.skipLocal) { - validators.push(new validators_1.SkipLocalValidator()); - } - const detector = new core_1.Detector(this.tokenizer, store, validators, options); - this.subscribes.forEach((listener) => { - Object - .entries(listener.subscribe()) - .map(([event, handler]) => detector.on(event, handler)); - }); - const detect = (entry, clones = []) => { - const { path, content } = entry; - const format = tokenizer_1.getFormatByFile(path, options.formatsExts); - return detector - .detect(path, content, format) - .then((clns) => { - if (clns) { - clones.push(...clns); - } - const file = files.pop(); - if (file) { - return detect(file, clones); - } - return clones; - }); - }; - const processHooks = (hook, detectedClones) => { - return hook - .process(detectedClones) - .then((clones) => { - const nextHook = hooks.pop(); - if (nextHook) { - return processHooks(nextHook, clones); - } - return clones; - }); - }; - return detect(files.pop()) - .then((clones) => { - const hook = hooks.pop(); - if (hook) { - return processHooks(hook, clones); - } - return clones; - }) - .then((clones) => { - const statistic = this.statistic.getStatistic(); - this.reporters.forEach((reporter) => { - reporter.report(clones, statistic); - }); - return clones; - }); - } -} -exports.InFilesDetector = InFilesDetector; -//# sourceMappingURL=in-files-detector.js.map - -/***/ }), - -/***/ 39148: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(88241)); -__export(__nccwpck_require__(51908)); -__export(__nccwpck_require__(88131)); -__export(__nccwpck_require__(48812)); -__export(__nccwpck_require__(16872)); -__export(__nccwpck_require__(20733)); -__export(__nccwpck_require__(43465)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 57959: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const reports_1 = __nccwpck_require__(42083); -const clone_found_1 = __nccwpck_require__(17304); -const safe_1 = __nccwpck_require__(41997); -const Table = __nccwpck_require__(2101); -const TABLE_OPTIONS = { - chars: { - top: '', - 'top-mid': '', - 'top-left': '', - 'top-right': '', - bottom: '', - 'bottom-mid': '', - 'bottom-left': '', - 'bottom-right': '', - left: '', - 'left-mid': '', - mid: '', - 'mid-mid': '', - right: '', - 'right-mid': '', - middle: '│', - }, -}; -class ConsoleFullReporter { - constructor(options) { - this.options = options; - } - report(clones) { - clones.forEach((clone) => { - this.cloneFullFound(clone); - }); - console.log(safe_1.grey(`Found ${clones.length} clones.`)); - } - cloneFullFound(clone) { - const table = new Table(TABLE_OPTIONS); - clone_found_1.cloneFound(clone, this.options); - clone.duplicationA.fragment.split('\n').forEach((line, position) => { - (table).push(reports_1.generateLine(clone, position, line)); - }); - console.log(table.toString()); - console.log(''); - } -} -exports.ConsoleFullReporter = ConsoleFullReporter; -//# sourceMappingURL=console-full.js.map - -/***/ }), - -/***/ 94513: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const safe_1 = __nccwpck_require__(41997); -const reports_1 = __nccwpck_require__(42083); -const Table = __nccwpck_require__(2101); -class ConsoleReporter { - constructor(options) { - this.options = options; - } - report(clones, statistic = undefined) { - if (statistic && !this.options.silent) { - const table = new Table({ - head: ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'], - }); - Object.keys(statistic.formats) - .filter((format) => statistic.formats[format].sources) - .forEach((format) => { - table.push(reports_1.convertStatisticToArray(format, statistic.formats[format].total)); - }); - table.push(reports_1.convertStatisticToArray(safe_1.bold('Total:'), statistic.total)); - console.log(table.toString()); - console.log(safe_1.grey(`Found ${clones.length} clones.`)); - } - } -} -exports.ConsoleReporter = ConsoleReporter; -//# sourceMappingURL=console.js.map - -/***/ }), - -/***/ 54038: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core_1 = __nccwpck_require__(84511); -const fs_extra_1 = __nccwpck_require__(5630); -const safe_1 = __nccwpck_require__(41997); -const path_1 = __nccwpck_require__(71017); -const reports_1 = __nccwpck_require__(42083); -class CSVReporter { - constructor(options) { - this.options = options; - } - report(clones, statistic) { - const report = [ - ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'], - ...Object.keys(statistic.formats).map((format) => reports_1.convertStatisticToArray(format, statistic.formats[format].total)), - reports_1.convertStatisticToArray('Total:', statistic.total) - ].map((arr) => arr.join(',')).join('\n'); - fs_extra_1.ensureDirSync(core_1.getOption('output', this.options)); - fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.csv', report); - console.log(safe_1.green(`CSV report saved to ${path_1.join(this.options.output, 'jscpd-report.csv')}`)); - } -} -exports.CSVReporter = CSVReporter; -//# sourceMappingURL=csv.js.map - -/***/ }), - -/***/ 16872: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(94513)); -__export(__nccwpck_require__(57959)); -__export(__nccwpck_require__(78634)); -__export(__nccwpck_require__(54038)); -__export(__nccwpck_require__(91708)); -__export(__nccwpck_require__(9319)); -__export(__nccwpck_require__(87850)); -__export(__nccwpck_require__(42639)); -__export(__nccwpck_require__(39774)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 78634: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_extra_1 = __nccwpck_require__(5630); -const core_1 = __nccwpck_require__(84511); -const reports_1 = __nccwpck_require__(42083); -const safe_1 = __nccwpck_require__(41997); -const path_1 = __nccwpck_require__(71017); -class JsonReporter { - constructor(options) { - this.options = options; - } - generateJson(clones, statistics) { - return { - statistics, - duplicates: clones.map(clone => this.cloneFound(clone)) - }; - } - report(clones, statistic) { - const json = this.generateJson(clones, statistic); - fs_extra_1.ensureDirSync(core_1.getOption('output', this.options)); - fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.json', JSON.stringify(json, null, ' ')); - console.log(safe_1.green(`JSON report saved to ${path_1.join(this.options.output, 'jscpd-report.json')}`)); - } - cloneFound(clone) { - const startLineA = clone.duplicationA.start.line; - const endLineA = clone.duplicationA.end.line; - const startLineB = clone.duplicationB.start.line; - const endLineB = clone.duplicationB.end.line; - return { - format: clone.format, - lines: endLineA - startLineA + 1, - fragment: clone.duplicationA.fragment, - tokens: 0, - firstFile: { - name: reports_1.getPath(clone.duplicationA.sourceId, this.options), - start: startLineA, - end: endLineA, - startLoc: clone.duplicationA.start, - endLoc: clone.duplicationA.end, - blame: clone.duplicationA.blame, - }, - secondFile: { - name: reports_1.getPath(clone.duplicationB.sourceId, this.options), - start: startLineB, - end: endLineB, - startLoc: clone.duplicationB.start, - endLoc: clone.duplicationB.end, - blame: clone.duplicationB.blame, - }, - }; - } -} -exports.JsonReporter = JsonReporter; -//# sourceMappingURL=json.js.map - -/***/ }), - -/***/ 91708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core_1 = __nccwpck_require__(84511); -const fs_extra_1 = __nccwpck_require__(5630); -const safe_1 = __nccwpck_require__(41997); -const path_1 = __nccwpck_require__(71017); -const reports_1 = __nccwpck_require__(42083); -const table = __nccwpck_require__(41062); -class MarkdownReporter { - constructor(options) { - this.options = options; - } - report(clones, statistic) { - const report = ` -# Copy/paste detection report - -> Duplications detection: Found ${clones.length} exact clones with ${statistic.total.duplicatedLines}(${statistic.total.percentage}%) duplicated lines in ${statistic.total.sources} (${Object.keys(statistic.formats).length} formats) files. - -${table([ - ['Format', 'Files analyzed', 'Total lines', 'Total tokens', 'Clones found', 'Duplicated lines', 'Duplicated tokens'], - ...Object.keys(statistic.formats).map((format) => reports_1.convertStatisticToArray(format, statistic.formats[format].total)), - reports_1.convertStatisticToArray('Total:', statistic.total).map(item => `**${item}**`) - ])} -`; - fs_extra_1.ensureDirSync(core_1.getOption('output', this.options)); - fs_extra_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.md', report); - console.log(safe_1.green(`Markdown report saved to ${path_1.join(this.options.output, 'jscpd-report.md')}`)); - } -} -exports.MarkdownReporter = MarkdownReporter; -//# sourceMappingURL=markdown.js.map - -/***/ }), - -/***/ 87850: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const safe_1 = __nccwpck_require__(41997); -class SilentReporter { - report(clones, statistic) { - if (statistic) { - console.log(`Duplications detection: Found ${safe_1.bold(clones.length.toString())} ` + - `exact clones with ${safe_1.bold(statistic.total.duplicatedLines.toString())}(${statistic.total.percentage}%) ` + - `duplicated lines in ${safe_1.bold(statistic.total.sources.toString())} ` + - `(${Object.keys(statistic.formats).length} formats) files.`); - } - } -} -exports.SilentReporter = SilentReporter; -//# sourceMappingURL=silent.js.map - -/***/ }), - -/***/ 42639: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const safe_1 = __nccwpck_require__(41997); -class ThresholdReporter { - constructor(options) { - this.options = options; - } - report(clones, statistic) { - if (statistic && this.options.threshold !== undefined && this.options.threshold < statistic.total.percentage) { - const message = `ERROR: jscpd found too many duplicates (${statistic.total.percentage}%) over threshold (${this.options.threshold}%)`; - console.error(safe_1.red(message)); - throw new Error(message); - } - } -} -exports.ThresholdReporter = ThresholdReporter; -//# sourceMappingURL=threshold.js.map - -/***/ }), - -/***/ 39774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const reports_1 = __nccwpck_require__(42083); -class XcodeReporter { - constructor(options) { - this.options = options; - } - report(clones) { - clones.forEach((clone) => { - this.cloneFound(clone); - }); - console.log(`Found ${clones.length} clones.`); - } - cloneFound(clone) { - const pathA = reports_1.getPath(clone.duplicationA.sourceId, Object.assign(Object.assign({}, this.options), { absolute: true })); - const pathB = reports_1.getPath(clone.duplicationB.sourceId, this.options); - const startLineA = clone.duplicationA.start.line; - const characterA = clone.duplicationA.start.column; - const endLineA = clone.duplicationA.end.line; - const startLineB = clone.duplicationB.start.line; - const endLineB = clone.duplicationB.end.line; - console.log(`${pathA}:${startLineA}:${characterA}: warning: Found ${endLineA - startLineA} lines (${startLineA}-${endLineA}) duplicated on file ${pathB} (${startLineB}-${endLineB})`); - } -} -exports.XcodeReporter = XcodeReporter; -//# sourceMappingURL=xcode.js.map - -/***/ }), - -/***/ 9319: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __nccwpck_require__(57147); -const fs_extra_1 = __nccwpck_require__(5630); -const core_1 = __nccwpck_require__(84511); -const reports_1 = __nccwpck_require__(42083); -const safe_1 = __nccwpck_require__(41997); -const path_1 = __nccwpck_require__(71017); -class XmlReporter { - constructor(options) { - this.options = options; - } - report(clones) { - let xmlDoc = ''; - xmlDoc += ''; - clones.forEach((clone) => { - xmlDoc = `${xmlDoc} - - - /i, 'CDATA_END')}]]> - - - /i, 'CDATA_END')}]]> - - /i, 'CDATA_END')}]]> - - `; - }); - xmlDoc += ''; - fs_extra_1.ensureDirSync(core_1.getOption('output', this.options)); - fs_1.writeFileSync(core_1.getOption('output', this.options) + '/jscpd-report.xml', xmlDoc); - console.log(safe_1.green(`XML report saved to ${path_1.join(this.options.output, 'jscpd-report.xml')}`)); - } -} -exports.XmlReporter = XmlReporter; -//# sourceMappingURL=xml.js.map - -/***/ }), - -/***/ 48812: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(14941)); -__export(__nccwpck_require__(10865)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 14941: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const clone_found_1 = __nccwpck_require__(17304); -class ProgressSubscriber { - constructor(options) { - this.options = options; - } - subscribe() { - return { - CLONE_FOUND: (payload) => clone_found_1.cloneFound(payload.clone, this.options), - }; - } -} -exports.ProgressSubscriber = ProgressSubscriber; -//# sourceMappingURL=progress.js.map - -/***/ }), - -/***/ 10865: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const safe_1 = __nccwpck_require__(41997); -class VerboseSubscriber { - constructor(options) { - this.options = options; - } - subscribe() { - return { - 'CLONE_FOUND': (payload) => { - const { clone } = payload; - console.log(safe_1.yellow('CLONE_FOUND')); - console.log(safe_1.grey(JSON.stringify(clone, null, '\t'))); - }, - 'CLONE_SKIPPED': (payload) => { - const { validation } = payload; - console.log(safe_1.yellow('CLONE_SKIPPED')); - console.log(safe_1.grey('Clone skipped: ' + validation.message.join(' '))); - }, - 'START_DETECTION': (payload) => { - const { source } = payload; - console.log(safe_1.yellow('START_DETECTION')); - console.log(safe_1.grey('Start detection for source id=' + source.getId() + ' format=' + source.getFormat())); - }, - }; - } -} -exports.VerboseSubscriber = VerboseSubscriber; -//# sourceMappingURL=verbose.js.map - -/***/ }), - -/***/ 17304: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const safe_1 = __nccwpck_require__(41997); -const reports_1 = __nccwpck_require__(42083); -function cloneFound(clone, options) { - const { duplicationA, duplicationB, format, isNew } = clone; - console.log('Clone found (' + format + '):' + (isNew ? safe_1.red('*') : '')); - console.log(` - ${reports_1.getPathConsoleString(duplicationA.sourceId, options)} [${reports_1.getSourceLocation(duplicationA.start, duplicationA.end)}] (${duplicationA.end.line - duplicationA.start.line} lines${duplicationA.end.position ? ', ' + (duplicationA.end.position - duplicationA.start.position) + ' tokens' : ''})`); - console.log(` ${reports_1.getPathConsoleString(duplicationB.sourceId, options)} [${reports_1.getSourceLocation(duplicationB.start, duplicationB.end)}]`); - console.log(''); -} -exports.cloneFound = cloneFound; -//# sourceMappingURL=clone-found.js.map - -/***/ }), - -/***/ 43465: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function parseFormatsExtensions(extensions = '') { - const result = {}; - if (!extensions) { - return undefined; - } - extensions.split(';').forEach((format) => { - const pair = format.split(':'); - result[pair[0]] = pair[1].split(','); - }); - return result; -} -exports.parseFormatsExtensions = parseFormatsExtensions; -//# sourceMappingURL=options.js.map - -/***/ }), - -/***/ 42083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const path_1 = __nccwpck_require__(71017); -const process_1 = __nccwpck_require__(77282); -const safe_1 = __nccwpck_require__(41997); -exports.compareDates = (firstDate, secondDate) => { - const first = new Date(firstDate); - const second = new Date(secondDate); - switch (true) { - case first < second: - return '=>'; - case first > second: - return '<='; - default: - return '=='; - } -}; -function escapeXml(unsafe) { - return unsafe.replace(/[<>&'"]/g, function (c) { - switch (c) { - case '<': return '<'; - case '>': return '>'; - case '&': return '&'; - case '\'': return '''; - case '"': return '"'; - } - }); -} -exports.escapeXml = escapeXml; -function getPath(path, options) { - return options.absolute ? path : path_1.relative(process_1.cwd(), path); -} -exports.getPath = getPath; -function getPathConsoleString(path, options) { - return safe_1.bold(safe_1.green(getPath(path, options))); -} -exports.getPathConsoleString = getPathConsoleString; -function getSourceLocation(start, end) { - return `${start.line}:${start.column} - ${end.line}:${end.column}`; -} -exports.getSourceLocation = getSourceLocation; -function generateLine(clone, position, line) { - const lineNumberA = (clone.duplicationA.start.line + position).toString(); - const lineNumberB = (clone.duplicationB.start.line + position).toString(); - if (clone.duplicationA.blame && clone.duplicationB.blame) { - return [ - lineNumberA, - clone.duplicationA.blame[lineNumberA] ? clone.duplicationA.blame[lineNumberA].author : '', - clone.duplicationA.blame[lineNumberA] && clone.duplicationB.blame[lineNumberB] - ? exports.compareDates(clone.duplicationA.blame[lineNumberA].date, clone.duplicationB.blame[lineNumberB].date) - : '', - lineNumberB, - clone.duplicationB.blame[lineNumberB] ? clone.duplicationB.blame[lineNumberB].author : '', - safe_1.grey(line), - ]; - } - else { - return [lineNumberA, lineNumberB, safe_1.grey(line)]; - } -} -exports.generateLine = generateLine; -function convertStatisticToArray(format, statistic) { - return [ - format, - `${statistic.sources}`, - `${statistic.lines}`, - `${statistic.tokens}`, - `${statistic.clones}`, - `${statistic.duplicatedLines} (${statistic.percentage}%)`, - `${statistic.duplicatedTokens} (${statistic.percentageTokens}%)`, - ]; -} -exports.convertStatisticToArray = convertStatisticToArray; -//# sourceMappingURL=reports.js.map - -/***/ }), - -/***/ 20733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -__export(__nccwpck_require__(69653)); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 69653: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const core_1 = __nccwpck_require__(84511); -const path_1 = __nccwpck_require__(71017); -class SkipLocalValidator { - validate(clone, options) { - const status = !this.shouldSkipClone(clone, options); - return { - status, - clone, - message: [ - `Sources of duplication located in same local folder (${clone.duplicationA.sourceId}, ${clone.duplicationB.sourceId})` - ] - }; - } - shouldSkipClone(clone, options) { - const path = core_1.getOption('path', options); - return path.some((dir) => SkipLocalValidator.isRelative(clone.duplicationA.sourceId, dir) && SkipLocalValidator.isRelative(clone.duplicationB.sourceId, dir)); - } - static isRelative(file, path) { - const rel = path_1.relative(path, file); - return rel !== '' && !rel.startsWith('..') && !path_1.isAbsolute(rel); - } -} -exports.SkipLocalValidator = SkipLocalValidator; -//# sourceMappingURL=skip-local.validator.js.map - -/***/ }), - -/***/ 71084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const path_1 = __nccwpck_require__(71017); -const finder_1 = __nccwpck_require__(39148); -const fs_extra_1 = __nccwpck_require__(5630); -const safe_1 = __nccwpck_require__(41997); -const pug = __nccwpck_require__(40316); -class HtmlReporter { - constructor(options) { - this.options = options; - } - report(clones, statistic) { - const jsonReporter = new finder_1.JsonReporter(this.options); - const json = jsonReporter.generateJson(clones, statistic); - const result = pug.renderFile(__nccwpck_require__.ab + "main.pug", json); - if (this.options.output) { - const destination = path_1.join(this.options.output, 'html/'); - try { - fs_extra_1.copySync(__nccwpck_require__.ab + "public", destination, { overwrite: true }); - const index = path_1.join(destination, 'index.html'); - fs_extra_1.writeFileSync(index, result); - fs_extra_1.writeFileSync(path_1.join(destination, 'jscpd-report.json'), JSON.stringify(json, null, ' ')); - console.log(safe_1.green(`HTML report saved to ${path_1.join(this.options.output, 'html/')}`)); - } - catch (e) { - console.log(safe_1.red(e)); - } - } - } -} -exports["default"] = HtmlReporter; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 85049: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const path_1 = __nccwpck_require__(71017); -exports.FORMATS = { - abap: { - exts: [], - }, - actionscript: { - exts: ['as'], - }, - ada: { - exts: ['ada'], - }, - apacheconf: { - exts: [], - }, - apl: { - exts: ['apl'], - }, - applescript: { - exts: [], - }, - arduino: { - exts: [], - }, - arff: { - exts: [], - }, - asciidoc: { - exts: [], - }, - asm6502: { - exts: [], - }, - aspnet: { - exts: ['asp', 'aspx'], - }, - autohotkey: { - exts: [], - }, - autoit: { - exts: [], - }, - bash: { - exts: ['sh', 'ksh', 'bash'], - }, - basic: { - exts: ['bas'], - }, - batch: { - exts: [], - }, - bison: { - exts: [], - }, - brainfuck: { - exts: ['b', 'bf'], - }, - bro: { - exts: [], - }, - c: { - exts: ['c', 'z80'], - }, - 'c-header': { - exts: ['h'], - parent: 'c', - }, - clike: { - exts: [], - }, - clojure: { - exts: ['cljs', 'clj', 'cljc', 'cljx', 'edn'], - }, - coffeescript: { - exts: ['coffee'], - }, - comments: { - exts: [] - }, - cpp: { - exts: ['cpp', 'c++', 'cc', 'cxx'], - }, - 'cpp-header': { - exts: ['hpp', 'h++', 'hh', 'hxx'], - parent: 'cpp', - }, - crystal: { - exts: ['cr'], - }, - csharp: { - exts: ['cs'], - }, - csp: { - exts: [], - }, - 'css-extras': { - exts: [], - }, - css: { - exts: ['css', 'gss'], - }, - d: { - exts: ['d'], - }, - dart: { - exts: ['dart'], - }, - diff: { - exts: ['diff', 'patch'], - }, - django: { - exts: [], - }, - docker: { - exts: [], - }, - eiffel: { - exts: ['e'], - }, - elixir: { - exts: [], - }, - elm: { - exts: ['elm'], - }, - erb: { - exts: [], - }, - erlang: { - exts: ['erl', 'erlang'], - }, - flow: { - exts: [], - }, - fortran: { - exts: ['f', 'for', 'f77', 'f90'], - }, - fsharp: { - exts: ['fs'], - }, - gedcom: { - exts: [], - }, - gherkin: { - exts: ['feature'], - }, - git: { - exts: [], - }, - glsl: { - exts: [], - }, - go: { - exts: ['go'], - }, - graphql: { - exts: ['graphql'], - }, - groovy: { - exts: ['groovy', 'gradle'], - }, - haml: { - exts: ['haml'], - }, - handlebars: { - exts: ['hb', 'hbs', 'handlebars'], - }, - haskell: { - exts: ['hs', 'lhs '], - }, - haxe: { - exts: ['hx', 'hxml'], - }, - hpkp: { - exts: [], - }, - hsts: { - exts: [], - }, - http: { - exts: [], - }, - ichigojam: { - exts: [], - }, - icon: { - exts: [], - }, - inform7: { - exts: [], - }, - ini: { - exts: ['ini'], - }, - io: { - exts: [], - }, - j: { - exts: [], - }, - java: { - exts: ['java'], - }, - javascript: { - exts: ['js', 'es', 'es6', 'mjs', 'cjs'], - }, - jolie: { - exts: [], - }, - json: { - exts: ['json', 'map', 'jsonld'], - }, - jsx: { - exts: ['jsx'], - }, - julia: { - exts: ['jl'], - }, - keymap: { - exts: [], - }, - kotlin: { - exts: ['kt', 'kts'], - }, - latex: { - exts: ['tex'], - }, - less: { - exts: ['less'], - }, - liquid: { - exts: [], - }, - lisp: { - exts: ['cl', 'lisp', 'el'], - }, - livescript: { - exts: ['ls'], - }, - lolcode: { - exts: [], - }, - lua: { - exts: ['lua'], - }, - makefile: { - exts: [], - }, - markdown: { - exts: ['md', 'markdown', 'mkd', 'txt'], - }, - markup: { - exts: ['html', 'htm', 'xml', 'xsl', 'xslt', 'svg', 'vue', 'ejs', 'jsp'], - }, - matlab: { - exts: [], - }, - mel: { - exts: [], - }, - mizar: { - exts: [], - }, - monkey: { - exts: [], - }, - n4js: { - exts: [], - }, - nasm: { - exts: [], - }, - nginx: { - exts: [], - }, - nim: { - exts: [], - }, - nix: { - exts: [], - }, - nsis: { - exts: ['nsh', 'nsi'], - }, - objectivec: { - exts: ['m', 'mm'], - }, - ocaml: { - exts: ['ocaml', 'ml', 'mli', 'mll', 'mly'], - }, - opencl: { - exts: [], - }, - oz: { - exts: ['oz'], - }, - parigp: { - exts: [], - }, - pascal: { - exts: ['pas', 'p'], - }, - perl: { - exts: ['pl', 'pm'], - }, - php: { - exts: ['php', 'phtml'], - }, - plsql: { - exts: ['plsql'], - }, - powershell: { - exts: ['ps1', 'psd1', 'psm1'], - }, - processing: { - exts: [], - }, - prolog: { - exts: ['pro'], - }, - properties: { - exts: ['properties'], - }, - protobuf: { - exts: ['proto'], - }, - pug: { - exts: ['pug', 'jade'], - }, - puppet: { - exts: ['pp', 'puppet'], - }, - pure: { - exts: [], - }, - python: { - exts: ['py', 'pyx', 'pxd', 'pxi'], - }, - q: { - exts: ['q'], - }, - qore: { - exts: [], - }, - r: { - exts: ['r', 'R'], - }, - reason: { - exts: [], - }, - renpy: { - exts: [], - }, - rest: { - exts: [], - }, - rip: { - exts: [], - }, - roboconf: { - exts: [], - }, - ruby: { - exts: ['rb'], - }, - rust: { - exts: ['rs'], - }, - sas: { - exts: ['sas'], - }, - sass: { - exts: ['sass'], - }, - scala: { - exts: ['scala'], - }, - scheme: { - exts: ['scm', 'ss'], - }, - scss: { - exts: ['scss'], - }, - smalltalk: { - exts: ['st'], - }, - smarty: { - exts: ['smarty', 'tpl'], - }, - soy: { - exts: ['soy'], - }, - sql: { - exts: ['sql', 'cql'], - }, - stylus: { - exts: ['styl', 'stylus'], - }, - swift: { - exts: ['swift'], - }, - tap: { - exts: ['tap'], - }, - tcl: { - exts: ['tcl'], - }, - textile: { - exts: ['textile'], - }, - tsx: { - exts: ['tsx'], - }, - tt2: { - exts: ['tt2'], - }, - twig: { - exts: ['twig'], - }, - typescript: { - exts: ['ts', 'mts', 'cts'], - }, - vbnet: { - exts: ['vb'], - }, - velocity: { - exts: ['vtl'], - }, - verilog: { - exts: ['v'], - }, - vhdl: { - exts: ['vhd', 'vhdl'], - }, - vim: { - exts: [], - }, - 'visual-basic': { - exts: ['vb'], - }, - wasm: { - exts: [], - }, - url: { - exts: [], - }, - wiki: { - exts: [], - }, - xeora: { - exts: [], - }, - xojo: { - exts: [], - }, - xquery: { - exts: ['xy', 'xquery'], - }, - yaml: { - exts: ['yaml', 'yml'], - }, -}; -function getSupportedFormats() { - return Object.keys(exports.FORMATS).filter((name) => name !== 'important' && name !== 'url'); -} -exports.getSupportedFormats = getSupportedFormats; -function getFormatByFile(path, formatsExts) { - const ext = path_1.extname(path).slice(1); - if (formatsExts && Object.keys(formatsExts).length) { - return Object.keys(formatsExts).find((format) => formatsExts[format].includes(ext)); - } - return Object.keys(exports.FORMATS).find((language) => exports.FORMATS[language].exts.includes(ext)); -} -exports.getFormatByFile = getFormatByFile; -//# sourceMappingURL=formats.js.map - -/***/ }), - -/***/ 53524: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const reprism = __nccwpck_require__(18042); -const abap = __nccwpck_require__(65444); -const actionscript = __nccwpck_require__(21019); -const ada = __nccwpck_require__(99040); -const apacheconf = __nccwpck_require__(70629); -const apl = __nccwpck_require__(13529); -const applescript = __nccwpck_require__(95394); -const arff = __nccwpck_require__(56245); -const asciidoc = __nccwpck_require__(86002); -const asm6502 = __nccwpck_require__(68737); -const aspnet = __nccwpck_require__(16326); -const autohotkey = __nccwpck_require__(3183); -const autoit = __nccwpck_require__(41502); -const bash = __nccwpck_require__(15209); -const basic = __nccwpck_require__(46676); -const batch = __nccwpck_require__(20986); -const brainfuck = __nccwpck_require__(64636); -const bro = __nccwpck_require__(57206); -const c = __nccwpck_require__(98220); -const clike = __nccwpck_require__(17403); -const clojure = __nccwpck_require__(45685); -const coffeescript = __nccwpck_require__(20525); -const cpp = __nccwpck_require__(26433); -const csharp = __nccwpck_require__(3204); -const csp = __nccwpck_require__(12115); -const cssExtras = __nccwpck_require__(16590); -const css = __nccwpck_require__(58302); -const d = __nccwpck_require__(60310); -const dart = __nccwpck_require__(14572); -const diff = __nccwpck_require__(35844); -const django = __nccwpck_require__(97535); -const docker = __nccwpck_require__(94508); -const eiffel = __nccwpck_require__(79209); -const elixir = __nccwpck_require__(74952); -const erlang = __nccwpck_require__(15691); -const flow = __nccwpck_require__(53794); -const fortran = __nccwpck_require__(90374); -const fsharp = __nccwpck_require__(63354); -const gedcom = __nccwpck_require__(25605); -const gherkin = __nccwpck_require__(14194); -const git = __nccwpck_require__(96602); -const glsl = __nccwpck_require__(96860); -const go = __nccwpck_require__(96509); -const graphql = __nccwpck_require__(6219); -const groovy = __nccwpck_require__(90897); -const haml = __nccwpck_require__(33412); -const handlebars = __nccwpck_require__(62023); -const haskell = __nccwpck_require__(2524); -const haxe = __nccwpck_require__(7267); -const hpkp = __nccwpck_require__(358); -const hsts = __nccwpck_require__(42669); -const http = __nccwpck_require__(7378); -const ichigojam = __nccwpck_require__(79406); -const icon = __nccwpck_require__(87849); -const inform7 = __nccwpck_require__(63411); -const ini = __nccwpck_require__(49597); -const io = __nccwpck_require__(28985); -const j = __nccwpck_require__(83738); -const java = __nccwpck_require__(47998); -const javascript = __nccwpck_require__(48430); -const jolie = __nccwpck_require__(37234); -const json = __nccwpck_require__(96317); -const jsx = __nccwpck_require__(16054); -const julia = __nccwpck_require__(18521); -const keyman = __nccwpck_require__(1453); -const kotlin = __nccwpck_require__(69707); -const latex = __nccwpck_require__(78387); -const less = __nccwpck_require__(25526); -const liquid = __nccwpck_require__(110); -const lisp = __nccwpck_require__(5716); -const livescript = __nccwpck_require__(4273); -const lolcode = __nccwpck_require__(78908); -const lua = __nccwpck_require__(28482); -const makefile = __nccwpck_require__(65822); -const markdown = __nccwpck_require__(20518); -const markupTemplating = __nccwpck_require__(8914); -const markup = __nccwpck_require__(42152); -const matlab = __nccwpck_require__(21372); -const mel = __nccwpck_require__(19177); -const mizar = __nccwpck_require__(37457); -const monkey = __nccwpck_require__(26314); -const n4js = __nccwpck_require__(41630); -const nasm = __nccwpck_require__(57062); -const nginx = __nccwpck_require__(44909); -const nim = __nccwpck_require__(64441); -const nix = __nccwpck_require__(51758); -const nsis = __nccwpck_require__(47159); -const objectivec = __nccwpck_require__(41466); -const ocaml = __nccwpck_require__(20505); -const opencl = __nccwpck_require__(24484); -const oz = __nccwpck_require__(70834); -const parigp = __nccwpck_require__(29775); -const parser = __nccwpck_require__(28480); -const pascal = __nccwpck_require__(98305); -const perl = __nccwpck_require__(46306); -const phpExtras = __nccwpck_require__(78800); -const php = __nccwpck_require__(92619); -const powershell = __nccwpck_require__(31896); -const processing = __nccwpck_require__(63028); -const prolog = __nccwpck_require__(11831); -const properties = __nccwpck_require__(6971); -const protobuf = __nccwpck_require__(9802); -const pug = __nccwpck_require__(47602); -const puppet = __nccwpck_require__(16015); -const pure = __nccwpck_require__(96047); -const python = __nccwpck_require__(42212); -const q = __nccwpck_require__(70061); -const qore = __nccwpck_require__(97631); -const r = __nccwpck_require__(20420); -const reason = __nccwpck_require__(39443); -const renpy = __nccwpck_require__(48755); -const rest = __nccwpck_require__(57652); -const rip = __nccwpck_require__(11090); -const roboconf = __nccwpck_require__(72149); -const ruby = __nccwpck_require__(40415); -const rust = __nccwpck_require__(93399); -const sas = __nccwpck_require__(96939); -const sass = __nccwpck_require__(37650); -const scala = __nccwpck_require__(60988); -const scheme = __nccwpck_require__(14150); -const scss = __nccwpck_require__(56838); -const smalltalk = __nccwpck_require__(81200); -const smarty = __nccwpck_require__(94171); -const soy = __nccwpck_require__(89135); -const stylus = __nccwpck_require__(94920); -const swift = __nccwpck_require__(58479); -const tcl = __nccwpck_require__(59758); -const textile = __nccwpck_require__(38347); -const tsx = __nccwpck_require__(13220); -const twig = __nccwpck_require__(99323); -const typescript = __nccwpck_require__(148); -const vbnet = __nccwpck_require__(15305); -const velocity = __nccwpck_require__(16657); -const verilog = __nccwpck_require__(26734); -const vhdl = __nccwpck_require__(19450); -const vim = __nccwpck_require__(38565); -const visualBasic = __nccwpck_require__(58229); -const wasm = __nccwpck_require__(63735); -const wiki = __nccwpck_require__(9213); -const xeora = __nccwpck_require__(93867); -const xojo = __nccwpck_require__(81975); -const yaml = __nccwpck_require__(54163); -const tap = __nccwpck_require__(33636); -const sql = __nccwpck_require__(19325); -const plsql = __nccwpck_require__(23678); -exports.languages = { - abap, actionscript, ada, apacheconf, apl, applescript, arff, - asciidoc, asm6502, aspnet, autohotkey, autoit, bash, basic, batch, - brainfuck, bro, c, clike, clojure, coffeescript, cpp, csharp, csp, cssExtras, - css, d, dart, diff, django, docker, eiffel, elixir, erlang, flow, fortran, fsharp, - gedcom, gherkin, git, glsl, go, graphql, groovy, haml, handlebars, haskell, haxe, - hpkp, hsts, http, ichigojam, icon, inform7, ini, io, j, java, javascript, jolie, - json, jsx, julia, keyman, kotlin, latex, less, liquid, lisp, livescript, - lolcode, lua, makefile, markdown, markupTemplating, markup, matlab, mel, mizar, - monkey, n4js, nasm, nginx, nim, nix, nsis, objectivec, ocaml, opencl, oz, parigp, - parser, pascal, perl, php, phpExtras, powershell, processing, prolog, - properties, protobuf, pug, puppet, pure, python, q, qore, r, reason, renpy, rest, - rip, roboconf, ruby, rust, sas, sass, scala, scheme, scss, smalltalk, smarty, soy, - stylus, swift, tcl, textile, twig, typescript, vbnet, velocity, verilog, vhdl, - vim, visualBasic, wasm, wiki, xeora, xojo, yaml, tsx, sql, plsql, tap -}; -exports.loadLanguages = () => { - reprism.loadLanguages(Object.values(exports.languages).map(v => v.default)); -}; -//# sourceMappingURL=grammar-loader.js.map - -/***/ }), - -/***/ 43439: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const SparkMD5 = __nccwpck_require__(70220); -function hash(value) { - return SparkMD5.hash(value); -} -exports.hash = hash; -//# sourceMappingURL=hash.js.map - -/***/ }), - -/***/ 92080: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tokenize_1 = __nccwpck_require__(74749); -__export(__nccwpck_require__(74749)); -__export(__nccwpck_require__(78199)); -__export(__nccwpck_require__(85049)); -class Tokenizer { - generateMaps(id, data, format, options) { - return tokenize_1.createTokenMapBasedOnCode(id, data, format, options); - } -} -exports.Tokenizer = Tokenizer; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 23678: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const grammar = { - language: 'plsql', - init(Prism) { - Prism.languages.plsql = Prism.languages.extend('sql', { - comment: [/\/\*[\s\S]*?\*\//, /--.*/], - }); - if (Prism.util.type(Prism.languages.plsql.keyword) !== 'Array') { - Prism.languages.plsql.keyword = [Prism.languages.plsql.keyword]; - } - Prism.languages.plsql.keyword.unshift(/\b(?:ACCESS|AGENT|AGGREGATE|ARRAY|ARROW|AT|ATTRIBUTE|AUDIT|AUTHID|BFILE_BASE|BLOB_BASE|BLOCK|BODY|BOTH|BOUND|BYTE|CALLING|CHAR_BASE|CHARSET(?:FORM|ID)|CLOB_BASE|COLAUTH|COLLECT|CLUSTERS?|COMPILED|COMPRESS|CONSTANT|CONSTRUCTOR|CONTEXT|CRASH|CUSTOMDATUM|DANGLING|DATE_BASE|DEFINE|DETERMINISTIC|DURATION|ELEMENT|EMPTY|EXCEPTIONS?|EXCLUSIVE|EXTERNAL|FINAL|FORALL|FORM|FOUND|GENERAL|HEAP|HIDDEN|IDENTIFIED|IMMEDIATE|INCLUDING|INCREMENT|INDICATOR|INDEXES|INDICES|INFINITE|INITIAL|ISOPEN|INSTANTIABLE|INTERFACE|INVALIDATE|JAVA|LARGE|LEADING|LENGTH|LIBRARY|LIKE[24C]|LIMITED|LONG|LOOP|MAP|MAXEXTENTS|MAXLEN|MEMBER|MINUS|MLSLABEL|MULTISET|NAME|NAN|NATIVE|NEW|NOAUDIT|NOCOMPRESS|NOCOPY|NOTFOUND|NOWAIT|NUMBER(?:_BASE)?|OBJECT|OCI(?:COLL|DATE|DATETIME|DURATION|INTERVAL|LOBLOCATOR|NUMBER|RAW|REF|REFCURSOR|ROWID|STRING|TYPE)|OFFLINE|ONLINE|ONLY|OPAQUE|OPERATOR|ORACLE|ORADATA|ORGANIZATION|ORL(?:ANY|VARY)|OTHERS|OVERLAPS|OVERRIDING|PACKAGE|PARALLEL_ENABLE|PARAMETERS?|PASCAL|PCTFREE|PIPE(?:LINED)?|PRAGMA|PRIOR|PRIVATE|RAISE|RANGE|RAW|RECORD|REF|REFERENCE|REM|REMAINDER|RESULT|RESOURCE|RETURNING|REVERSE|ROW(?:ID|NUM|TYPE)|SAMPLE|SB[124]|SEGMENT|SELF|SEPARATE|SEQUENCE|SHORT|SIZE(?:_T)?|SPARSE|SQL(?:CODE|DATA|NAME|STATE)|STANDARD|STATIC|STDDEV|STORED|STRING|STRUCT|STYLE|SUBMULTISET|SUBPARTITION|SUBSTITUTABLE|SUBTYPE|SUCCESSFUL|SYNONYM|SYSDATE|TABAUTH|TDO|THE|TIMEZONE_(?:ABBR|HOUR|MINUTE|REGION)|TRAILING|TRANSAC(?:TIONAL)?|TRUSTED|UB[124]|UID|UNDER|UNTRUSTED|VALIDATE|VALIST|VARCHAR2|VARIABLE|VARIANCE|VARRAY|VIEWS|VOID|WHENEVER|WRAPPED|ZONE)\b/i); - if (Prism.util.type(Prism.languages.plsql.operator) !== 'Array') { - Prism.languages.plsql.operator = [Prism.languages.plsql.operator]; - } - Prism.languages.plsql.operator.unshift(/:=/); - }, -}; -exports["default"] = grammar; -//# sourceMappingURL=plsql.js.map - -/***/ }), - -/***/ 19325: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const grammar = { - language: 'sql', - init(Prism) { - Prism.languages.sql = { - 'comment': { - pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/, - lookbehind: true, - }, - 'variable': [ - { - pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/, - greedy: true, - }, - /@[\w.$]+/, - ], - 'string': { - pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/, - greedy: true, - lookbehind: true, - }, - 'function': /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, - 'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i, - 'boolean': /\b(?:TRUE|FALSE|NULL)\b/i, - 'number': /\b0x[\da-f]+\b|\b\d+\.?\d*|\B\.\d+\b/i, - 'operator': /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i, - 'punctuation': /[;[\]()`,.]/, - }; - }, -}; -exports["default"] = grammar; -//# sourceMappingURL=sql.js.map - -/***/ }), - -/***/ 33636: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const grammar = { - language: 'tap', - init(Prism) { - Prism.languages.tap = { - fail: /not ok[^#{\n\r]*/, - pass: /ok[^#{\n\r]*/, - pragma: /pragma [+-][a-z]+/, - bailout: /bail out!.*/i, - version: /TAP version \d+/i, - plan: /\d+\.\.\d+(?: +#.*)?/, - subtest: { - pattern: /# Subtest(?:: .*)?/, - greedy: true - }, - punctuation: /[{}]/, - directive: /#.*/, - yamlish: { - pattern: /(^[ \t]*)---[\s\S]*?[\r\n][ \t]*\.\.\.$/m, - lookbehind: true, - inside: Prism.languages.yaml, - alias: 'language-yaml' - } - }; - }, -}; -exports["default"] = grammar; -//# sourceMappingURL=tap.js.map - -/***/ }), - -/***/ 78199: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const hash_1 = __nccwpck_require__(43439); -const TOKEN_HASH_LENGTH = 20; -function createTokenHash(token, hashFunction = undefined) { - return hashFunction ? - hashFunction(token.type + token.value).substr(0, TOKEN_HASH_LENGTH) : - hash_1.hash(token.type + token.value).substr(0, TOKEN_HASH_LENGTH); -} -function groupByFormat(tokens) { - const result = {}; - // TODO change to reduce - tokens.forEach((token) => { - (result[token.format] = result[token.format] ? [...result[token.format], token] : [token]); - }); - return result; -} -class TokensMap { - constructor(id, data, tokens, format, options) { - this.id = id; - this.data = data; - this.tokens = tokens; - this.format = format; - this.options = options; - this.position = 0; - this.hashMap = this.tokens.map((token) => { - if (options.ignoreCase) { - token.value = token.value.toLocaleLowerCase(); - } - return createTokenHash(token, this.options.hashFunction); - }).join(''); - } - getTokensCount() { - return this.tokens[this.tokens.length - 1].loc.end.position - this.tokens[0].loc.start.position; - } - getId() { - return this.id; - } - getLinesCount() { - return this.tokens[this.tokens.length - 1].loc.end.line - this.tokens[0].loc.start.line; - } - getFormat() { - return this.format; - } - [Symbol.iterator]() { - return this; - } - next() { - const hashFunction = this.options.hashFunction ? this.options.hashFunction : hash_1.hash; - const mapFrame = hashFunction(this.hashMap.substring(this.position * TOKEN_HASH_LENGTH, this.position * TOKEN_HASH_LENGTH + this.options.minTokens * TOKEN_HASH_LENGTH)).substring(0, TOKEN_HASH_LENGTH); - if (this.position < this.tokens.length - this.options.minTokens) { - this.position++; - return { - done: false, - value: { - id: mapFrame, - sourceId: this.getId(), - start: this.tokens[this.position - 1], - end: this.tokens[this.position + this.options.minTokens - 1], - }, - }; - } - else { - return { - done: true, - value: false, - }; - } - } -} -exports.TokensMap = TokensMap; -function generateMapsForFormats(id, data, tokens, options) { - return Object - .values(groupByFormat(tokens)) - .map((formatTokens) => new TokensMap(id, data, formatTokens, formatTokens[0].format, options)); -} -exports.generateMapsForFormats = generateMapsForFormats; -function createTokensMaps(id, data, tokens, options) { - return generateMapsForFormats(id, data, tokens, options); -} -exports.createTokensMaps = createTokensMaps; -//# sourceMappingURL=token-map.js.map - -/***/ }), - -/***/ 74749: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const reprism = __nccwpck_require__(18042); -const formats_1 = __nccwpck_require__(85049); -const token_map_1 = __nccwpck_require__(78199); -const grammar_loader_1 = __nccwpck_require__(53524); -const ignore = { - ignore: [ - { - pattern: /(jscpd:ignore-start)[\s\S]*?(?=jscpd:ignore-end)/, - lookbehind: true, - greedy: true, - }, - { - pattern: /jscpd:ignore-start/, - greedy: false, - }, - { - pattern: /jscpd:ignore-end/, - greedy: false, - }, - ], -}; -const punctuation = { - // eslint-disable-next-line @typescript-eslint/camelcase - new_line: /\n/, - empty: /\s+/, -}; -const initializeFormats = () => { - grammar_loader_1.loadLanguages(); - Object - .keys(reprism.default.languages) - .forEach((lang) => { - if (lang !== 'extend' && lang !== 'insertBefore' && lang !== 'DFS') { - reprism.default.languages[lang] = Object.assign(Object.assign(Object.assign({}, ignore), reprism.default.languages[lang]), punctuation); - } - }); -}; -initializeFormats(); -function getLanguagePrismName(lang) { - if (lang in formats_1.FORMATS && formats_1.FORMATS[lang].parent) { - return formats_1.FORMATS[lang].parent; - } - return lang; -} -function tokenize(code, language) { - let length = 0; - let line = 1; - let column = 1; - function sanitizeLangName(name) { - return name && name.replace ? name.replace('language-', '') : 'unknown'; - } - function createTokenFromString(token, lang) { - return [ - { - format: lang, - type: 'default', - value: token, - length: token.length, - }, - ]; - } - function calculateLocation(token, position) { - const result = token; - const lines = typeof result.value === 'string' && result.value.split ? result.value.split('\n') : []; - const newLines = lines.length - 1; - const start = { - line, - column, - position - }; - column = newLines >= 0 ? lines[lines.length - 1].length + 1 : column; - const end = { - line: line + newLines, - column, - position - }; - result.loc = { start, end }; - result.range = [length, length + result.length]; - length += result.length; - line += newLines; - return result; - } - function createTokenFromFlatToken(token, lang) { - return [ - { - format: lang, - type: token.type, - value: token.content, - length: token.length, - }, - ]; - } - function createTokens(token, lang) { - if (token.content && typeof token.content === 'string') { - return createTokenFromFlatToken(token, lang); - } - if (token.content && Array.isArray(token.content)) { - let res = []; - token.content.forEach((t) => (res = res.concat(createTokens(t, token.alias ? sanitizeLangName(token.alias) : lang)))); - return res; - } - return createTokenFromString(token, lang); - } - let tokens = []; - const grammar = reprism.default.languages[getLanguagePrismName(language)]; - if (!reprism.default.languages[getLanguagePrismName(language)]) { - console.warn('Warn: jscpd has issue with support of "' + getLanguagePrismName(language) + '"'); - return []; - } - reprism.default.tokenize(code, grammar) - .forEach((t) => (tokens = tokens.concat(createTokens(t, language)))); - return tokens - .filter((t) => t.format in formats_1.FORMATS) - .map((token, index) => calculateLocation(token, index)); -} -exports.tokenize = tokenize; -function setupIgnorePatterns(format, ignorePattern) { - const language = getLanguagePrismName(format); - const ignorePatterns = ignorePattern.map(pattern => ({ - pattern: new RegExp(pattern), - greedy: false, - })); - reprism.default.languages[language] = Object.assign(Object.assign({}, ignorePatterns), reprism.default.languages[language]); -} -function createTokenMapBasedOnCode(id, data, format, options = {}) { - const { mode, ignoreCase, ignorePattern } = options; - const tokens = tokenize(data, format) - .filter((token) => mode(token, options)); - if (ignorePattern) - setupIgnorePatterns(format, options.ignorePattern); - if (ignoreCase) { - return token_map_1.createTokensMaps(id, data, tokens.map((token) => { - token.value = token.value.toLocaleLowerCase(); - return token; - }), options); - } - return token_map_1.createTokensMaps(id, data, tokens, options); -} -exports.createTokenMapBasedOnCode = createTokenMapBasedOnCode; -//# sourceMappingURL=tokenize.js.map - /***/ }), /***/ 63803: @@ -59474,24 +57446,6 @@ class Agent extends http.Agent { exports.Agent = Agent; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 65063: -/***/ ((module) => { - -"use strict"; - - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; - - /***/ }), /***/ 81231: @@ -68197,69107 +66151,61426 @@ exports["default"] = assertNever; wrapAsync(task)((err, ...args) => { if (err === false) return taskCb(err); - if (args.length < 2) { - [result] = args; - } else { - result = args; - } - error = err; - taskCb(err ? null : {}); - }); - }, () => callback(error, result)); - } - - var tryEach$1 = awaitify(tryEach); - - /** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ - function unmemoize(fn) { - return (...args) => { - return (fn.unmemoized || fn)(...args); - }; - } - - /** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (callback). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - * @example - * - * var count = 0; - * async.whilst( - * function test(cb) { cb(null, count < 5); }, - * function iter(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ - function whilst(test, iteratee, callback) { - callback = onlyOnce(callback); - var _fn = wrapAsync(iteratee); - var _test = wrapAsync(test); - var results = []; - - function next(err, ...rest) { - if (err) return callback(err); - results = rest; - if (err === false) return; - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } - - return _test(check); - } - var whilst$1 = awaitify(whilst, 3); - - /** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (callback). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if a callback is not passed - * - * @example - * const results = [] - * let finished = false - * async.until(function test(cb) { - * cb(null, finished) - * }, function iter(next) { - * fetchPage(url, (err, body) => { - * if (err) return next(err) - * results = results.concat(body.objects) - * finished = !!body.next - * next(err) - * }) - * }, function done (err) { - * // all pages have been fetched - * }) - */ - function until(test, iteratee, callback) { - const _test = wrapAsync(test); - return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); - } - - /** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ - function waterfall (tasks, callback) { - callback = once(callback); - if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - task(...args, onlyOnce(next)); - } - - function next(err, ...args) { - if (err === false) return - if (err || taskIndex === tasks.length) { - return callback(err, ...args); - } - nextTask(args); - } - - nextTask([]); - } - - var waterfall$1 = awaitify(waterfall); - - /** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - - - var index = { - apply, - applyEach, - applyEachSeries, - asyncify, - auto, - autoInject, - cargo: cargo$1, - cargoQueue: cargo, - compose, - concat: concat$1, - concatLimit: concatLimit$1, - concatSeries: concatSeries$1, - constant: constant$1, - detect: detect$1, - detectLimit: detectLimit$1, - detectSeries: detectSeries$1, - dir, - doUntil, - doWhilst: doWhilst$1, - each, - eachLimit: eachLimit$1, - eachOf: eachOf$1, - eachOfLimit: eachOfLimit$1, - eachOfSeries: eachOfSeries$1, - eachSeries: eachSeries$1, - ensureAsync, - every: every$1, - everyLimit: everyLimit$1, - everySeries: everySeries$1, - filter: filter$1, - filterLimit: filterLimit$1, - filterSeries: filterSeries$1, - forever: forever$1, - groupBy, - groupByLimit: groupByLimit$1, - groupBySeries, - log, - map: map$1, - mapLimit: mapLimit$1, - mapSeries: mapSeries$1, - mapValues, - mapValuesLimit: mapValuesLimit$1, - mapValuesSeries, - memoize, - nextTick, - parallel, - parallelLimit, - priorityQueue, - queue, - race: race$1, - reduce: reduce$1, - reduceRight, - reflect, - reflectAll, - reject: reject$1, - rejectLimit: rejectLimit$1, - rejectSeries: rejectSeries$1, - retry, - retryable, - seq, - series, - setImmediate: setImmediate$1, - some: some$1, - someLimit: someLimit$1, - someSeries: someSeries$1, - sortBy: sortBy$1, - timeout, - times, - timesLimit, - timesSeries, - transform, - tryEach: tryEach$1, - unmemoize, - until, - waterfall: waterfall$1, - whilst: whilst$1, - - // aliases - all: every$1, - allLimit: everyLimit$1, - allSeries: everySeries$1, - any: some$1, - anyLimit: someLimit$1, - anySeries: someSeries$1, - find: detect$1, - findLimit: detectLimit$1, - findSeries: detectSeries$1, - flatMap: concat$1, - flatMapLimit: concatLimit$1, - flatMapSeries: concatSeries$1, - forEach: each, - forEachSeries: eachSeries$1, - forEachLimit: eachLimit$1, - forEachOf: eachOf$1, - forEachOfSeries: eachOfSeries$1, - forEachOfLimit: eachOfLimit$1, - inject: reduce$1, - foldl: reduce$1, - foldr: reduceRight, - select: filter$1, - selectLimit: filterLimit$1, - selectSeries: filterSeries$1, - wrapSync: asyncify, - during: whilst$1, - doDuring: doWhilst$1 - }; - - exports.all = every$1; - exports.allLimit = everyLimit$1; - exports.allSeries = everySeries$1; - exports.any = some$1; - exports.anyLimit = someLimit$1; - exports.anySeries = someSeries$1; - exports.apply = apply; - exports.applyEach = applyEach; - exports.applyEachSeries = applyEachSeries; - exports.asyncify = asyncify; - exports.auto = auto; - exports.autoInject = autoInject; - exports.cargo = cargo$1; - exports.cargoQueue = cargo; - exports.compose = compose; - exports.concat = concat$1; - exports.concatLimit = concatLimit$1; - exports.concatSeries = concatSeries$1; - exports.constant = constant$1; - exports.default = index; - exports.detect = detect$1; - exports.detectLimit = detectLimit$1; - exports.detectSeries = detectSeries$1; - exports.dir = dir; - exports.doDuring = doWhilst$1; - exports.doUntil = doUntil; - exports.doWhilst = doWhilst$1; - exports.during = whilst$1; - exports.each = each; - exports.eachLimit = eachLimit$1; - exports.eachOf = eachOf$1; - exports.eachOfLimit = eachOfLimit$1; - exports.eachOfSeries = eachOfSeries$1; - exports.eachSeries = eachSeries$1; - exports.ensureAsync = ensureAsync; - exports.every = every$1; - exports.everyLimit = everyLimit$1; - exports.everySeries = everySeries$1; - exports.filter = filter$1; - exports.filterLimit = filterLimit$1; - exports.filterSeries = filterSeries$1; - exports.find = detect$1; - exports.findLimit = detectLimit$1; - exports.findSeries = detectSeries$1; - exports.flatMap = concat$1; - exports.flatMapLimit = concatLimit$1; - exports.flatMapSeries = concatSeries$1; - exports.foldl = reduce$1; - exports.foldr = reduceRight; - exports.forEach = each; - exports.forEachLimit = eachLimit$1; - exports.forEachOf = eachOf$1; - exports.forEachOfLimit = eachOfLimit$1; - exports.forEachOfSeries = eachOfSeries$1; - exports.forEachSeries = eachSeries$1; - exports.forever = forever$1; - exports.groupBy = groupBy; - exports.groupByLimit = groupByLimit$1; - exports.groupBySeries = groupBySeries; - exports.inject = reduce$1; - exports.log = log; - exports.map = map$1; - exports.mapLimit = mapLimit$1; - exports.mapSeries = mapSeries$1; - exports.mapValues = mapValues; - exports.mapValuesLimit = mapValuesLimit$1; - exports.mapValuesSeries = mapValuesSeries; - exports.memoize = memoize; - exports.nextTick = nextTick; - exports.parallel = parallel; - exports.parallelLimit = parallelLimit; - exports.priorityQueue = priorityQueue; - exports.queue = queue; - exports.race = race$1; - exports.reduce = reduce$1; - exports.reduceRight = reduceRight; - exports.reflect = reflect; - exports.reflectAll = reflectAll; - exports.reject = reject$1; - exports.rejectLimit = rejectLimit$1; - exports.rejectSeries = rejectSeries$1; - exports.retry = retry; - exports.retryable = retryable; - exports.select = filter$1; - exports.selectLimit = filterLimit$1; - exports.selectSeries = filterSeries$1; - exports.seq = seq; - exports.series = series; - exports.setImmediate = setImmediate$1; - exports.some = some$1; - exports.someLimit = someLimit$1; - exports.someSeries = someSeries$1; - exports.sortBy = sortBy$1; - exports.timeout = timeout; - exports.times = times; - exports.timesLimit = timesLimit; - exports.timesSeries = timesSeries; - exports.transform = transform; - exports.tryEach = tryEach$1; - exports.unmemoize = unmemoize; - exports.until = until; - exports.waterfall = waterfall$1; - exports.whilst = whilst$1; - exports.wrapSync = asyncify; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); - - -/***/ }), - -/***/ 25995: -/***/ ((module) => { - -module.exports = r => { - const n = process.versions.node.split('.').map(x => parseInt(x, 10)) - r = r.split('.').map(x => parseInt(x, 10)) - return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2]))) -} - - -/***/ }), - -/***/ 33497: -/***/ ((module) => { - -function isBuffer (value) { - return Buffer.isBuffer(value) || value instanceof Uint8Array -} - -function isEncoding (encoding) { - return Buffer.isEncoding(encoding) -} - -function alloc (size, fill, encoding) { - return Buffer.alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - return Buffer.allocUnsafe(size) -} - -function allocUnsafeSlow (size) { - return Buffer.allocUnsafeSlow(size) -} - -function byteLength (string, encoding) { - return Buffer.byteLength(string, encoding) -} - -function compare (a, b) { - return Buffer.compare(a, b) -} - -function concat (buffers, totalLength) { - return Buffer.concat(buffers, totalLength) -} - -function copy (source, target, targetStart, start, end) { - return toBuffer(source).copy(target, targetStart, start, end) -} - -function equals (a, b) { - return toBuffer(a).equals(b) -} - -function fill (buffer, value, offset, end, encoding) { - return toBuffer(buffer).fill(value, offset, end, encoding) -} - -function from (value, encodingOrOffset, length) { - return Buffer.from(value, encodingOrOffset, length) -} - -function includes (buffer, value, byteOffset, encoding) { - return toBuffer(buffer).includes(value, byteOffset, encoding) -} - -function indexOf (buffer, value, byfeOffset, encoding) { - return toBuffer(buffer).indexOf(value, byfeOffset, encoding) -} - -function lastIndexOf (buffer, value, byteOffset, encoding) { - return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) -} - -function swap16 (buffer) { - return toBuffer(buffer).swap16() -} - -function swap32 (buffer) { - return toBuffer(buffer).swap32() -} - -function swap64 (buffer) { - return toBuffer(buffer).swap64() -} - -function toBuffer (buffer) { - if (Buffer.isBuffer(buffer)) return buffer - return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) -} - -function toString (buffer, encoding, start, end) { - return toBuffer(buffer).toString(encoding, start, end) -} - -function write (buffer, string, offset, length, encoding) { - return toBuffer(buffer).write(string, offset, length, encoding) -} - -function writeDoubleLE (buffer, value, offset) { - return toBuffer(buffer).writeDoubleLE(value, offset) -} - -function writeFloatLE (buffer, value, offset) { - return toBuffer(buffer).writeFloatLE(value, offset) -} - -function writeUInt32LE (buffer, value, offset) { - return toBuffer(buffer).writeUInt32LE(value, offset) -} - -function writeInt32LE (buffer, value, offset) { - return toBuffer(buffer).writeInt32LE(value, offset) -} - -function readDoubleLE (buffer, offset) { - return toBuffer(buffer).readDoubleLE(offset) -} - -function readFloatLE (buffer, offset) { - return toBuffer(buffer).readFloatLE(offset) -} - -function readUInt32LE (buffer, offset) { - return toBuffer(buffer).readUInt32LE(offset) -} - -function readInt32LE (buffer, offset) { - return toBuffer(buffer).readInt32LE(offset) -} - -function writeDoubleBE (buffer, value, offset) { - return toBuffer(buffer).writeDoubleBE(value, offset) -} - -function writeFloatBE (buffer, value, offset) { - return toBuffer(buffer).writeFloatBE(value, offset) -} - -function writeUInt32BE (buffer, value, offset) { - return toBuffer(buffer).writeUInt32BE(value, offset) -} - -function writeInt32BE (buffer, value, offset) { - return toBuffer(buffer).writeInt32BE(value, offset) -} - -function readDoubleBE (buffer, offset) { - return toBuffer(buffer).readDoubleBE(offset) -} - -function readFloatBE (buffer, offset) { - return toBuffer(buffer).readFloatBE(offset) -} - -function readUInt32BE (buffer, offset) { - return toBuffer(buffer).readUInt32BE(offset) -} - -function readInt32BE (buffer, offset) { - return toBuffer(buffer).readInt32BE(offset) -} - -module.exports = { - isBuffer, - isEncoding, - alloc, - allocUnsafe, - allocUnsafeSlow, - byteLength, - compare, - concat, - copy, - equals, - fill, - from, - includes, - indexOf, - lastIndexOf, - swap16, - swap32, - swap64, - toBuffer, - toString, - write, - writeDoubleLE, - writeFloatLE, - writeUInt32LE, - writeInt32LE, - readDoubleLE, - readFloatLE, - readUInt32LE, - readInt32LE, - writeDoubleBE, - writeFloatBE, - writeUInt32BE, - writeInt32BE, - readDoubleBE, - readFloatBE, - readUInt32BE, - readInt32BE - -} - - -/***/ }), - -/***/ 18098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const t = __importStar(__nccwpck_require__(7912)); -if (!(Array.isArray(t.TYPES) && - t.TYPES.every((t) => typeof t === 'string'))) { - throw new Error('@babel/types TYPES does not match the expected type.'); -} -const FLIPPED_ALIAS_KEYS = t - .FLIPPED_ALIAS_KEYS; -const TYPES = new Set(t.TYPES); -if (!(FLIPPED_ALIAS_KEYS && - // tslint:disable-next-line: strict-type-predicates - typeof FLIPPED_ALIAS_KEYS === 'object' && - Object.keys(FLIPPED_ALIAS_KEYS).every((key) => Array.isArray(FLIPPED_ALIAS_KEYS[key]) && - // tslint:disable-next-line: strict-type-predicates - FLIPPED_ALIAS_KEYS[key].every((v) => typeof v === 'string')))) { - throw new Error('@babel/types FLIPPED_ALIAS_KEYS does not match the expected type.'); -} -/** - * This serves thre functions: - * - * 1. Take any "aliases" and explode them to refecence the concrete types - * 2. Normalize all handlers to have an `{enter, exit}` pair, rather than raw functions - * 3. make the enter and exit handlers arrays, so that multiple handlers can be merged - */ -function explode(input) { - const results = {}; - for (const key in input) { - const aliases = FLIPPED_ALIAS_KEYS[key]; - if (aliases) { - for (const concreteKey of aliases) { - if (concreteKey in results) { - if (typeof input[key] === 'function') { - results[concreteKey].enter.push(input[key]); - } - else { - if (input[key].enter) - results[concreteKey].enter.push(input[key].enter); - if (input[key].exit) - results[concreteKey].exit.push(input[key].exit); - } - } - else { - if (typeof input[key] === 'function') { - results[concreteKey] = { - enter: [input[key]], - exit: [], - }; - } - else { - results[concreteKey] = { - enter: input[key].enter ? [input[key].enter] : [], - exit: input[key].exit ? [input[key].exit] : [], - }; - } - } - } - } - else if (TYPES.has(key)) { - if (key in results) { - if (typeof input[key] === 'function') { - results[key].enter.push(input[key]); - } - else { - if (input[key].enter) - results[key].enter.push(input[key].enter); - if (input[key].exit) - results[key].exit.push(input[key].exit); - } - } - else { - if (typeof input[key] === 'function') { - results[key] = { - enter: [input[key]], - exit: [], - }; - } - else { - results[key] = { - enter: input[key].enter ? [input[key].enter] : [], - exit: input[key].exit ? [input[key].exit] : [], - }; - } - } - } - } - return results; -} -exports["default"] = explode; -//# sourceMappingURL=explode.js.map - -/***/ }), - -/***/ 6407: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.recursive = exports.ancestor = exports.simple = void 0; -const t = __importStar(__nccwpck_require__(7912)); -const explode_1 = __importDefault(__nccwpck_require__(18098)); -const VISITOR_KEYS = t.VISITOR_KEYS; -if (!(VISITOR_KEYS && - // tslint:disable-next-line: strict-type-predicates - typeof VISITOR_KEYS === 'object' && - Object.keys(VISITOR_KEYS).every((key) => Array.isArray(VISITOR_KEYS[key]) && - // tslint:disable-next-line: strict-type-predicates - VISITOR_KEYS[key].every((v) => typeof v === 'string')))) { - throw new Error('@babel/types VISITOR_KEYS does not match the expected type.'); -} -function simple(visitors) { - const vis = explode_1.default(visitors); - return (node, state) => { - (function recurse(node) { - if (!node) - return; - const visitor = vis[node.type]; - if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { - for (const v of visitor.enter) { - v(node, state); - } - } - for (const key of VISITOR_KEYS[node.type] || []) { - const subNode = node[key]; - if (Array.isArray(subNode)) { - for (const subSubNode of subNode) { - recurse(subSubNode); - } - } - else { - recurse(subNode); - } - } - if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) { - for (const v of visitor.exit) { - v(node, state); - } - } - })(node); - }; -} -exports.simple = simple; -function ancestor(visitors) { - const vis = explode_1.default(visitors); - return (node, state) => { - const ancestors = []; - (function recurse(node) { - if (!node) - return; - const visitor = vis[node.type]; - const isNew = node !== ancestors[ancestors.length - 1]; - if (isNew) - ancestors.push(node); - if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { - for (const v of visitor.enter) { - v(node, state, ancestors); - } - } - for (const key of VISITOR_KEYS[node.type] || []) { - const subNode = node[key]; - if (Array.isArray(subNode)) { - for (const subSubNode of subNode) { - recurse(subSubNode); - } - } - else { - recurse(subNode); - } - } - if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) { - for (const v of visitor.exit) { - v(node, state, ancestors); - } - } - if (isNew) - ancestors.pop(); - })(node); - }; -} -exports.ancestor = ancestor; -function recursive(visitors) { - const vis = explode_1.default(visitors); - return (node, state) => { - (function recurse(node) { - if (!node) - return; - const visitor = vis[node.type]; - if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { - for (const v of visitor.enter) { - v(node, state, recurse); - } - } - else { - for (const key of VISITOR_KEYS[node.type] || []) { - const subNode = node[key]; - if (Array.isArray(subNode)) { - for (const subSubNode of subNode) { - recurse(subSubNode); - } - } - else { - recurse(subNode); - } - } - } - })(node); - }; -} -exports.recursive = recursive; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 9417: -/***/ ((module) => { - -"use strict"; - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; - } - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; - } - } - - return result; -} - - -/***/ }), - -/***/ 83682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(44670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} - -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} - -function HookCollection () { - var state = { - registry: {} - } - - var hook = register.bind(null, state) - bindApi(hook, state) - - return hook -} - -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true - } - return HookCollection() -} - -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - - -/***/ }), - -/***/ 5549: -/***/ ((module) => { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 44670: -/***/ ((module) => { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 6819: -/***/ ((module) => { - -module.exports = removeHook; - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; - } - - state.registry[name].splice(index, 1); -} - - -/***/ }), - -/***/ 66474: -/***/ ((module, exports, __nccwpck_require__) => { - -var Chainsaw = __nccwpck_require__(46533); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var Buffers = __nccwpck_require__(51590); -var Vars = __nccwpck_require__(13755); -var Stream = (__nccwpck_require__(12781).Stream); - -exports = module.exports = function (bufOrEm, eventName) { - if (Buffer.isBuffer(bufOrEm)) { - return exports.parse(bufOrEm); - } - - var s = exports.stream(); - if (bufOrEm && bufOrEm.pipe) { - bufOrEm.pipe(s); - } - else if (bufOrEm) { - bufOrEm.on(eventName || 'data', function (buf) { - s.write(buf); - }); - - bufOrEm.on('end', function () { - s.end(); - }); - } - return s; -}; - -exports.stream = function (input) { - if (input) return exports.apply(null, arguments); - - var pending = null; - function getBytes (bytes, cb, skip) { - pending = { - bytes : bytes, - skip : skip, - cb : function (buf) { - pending = null; - cb(buf); - }, - }; - dispatch(); - } - - var offset = null; - function dispatch () { - if (!pending) { - if (caughtEnd) done = true; - return; - } - if (typeof pending === 'function') { - pending(); - } - else { - var bytes = offset + pending.bytes; - - if (buffers.length >= bytes) { - var buf; - if (offset == null) { - buf = buffers.splice(0, bytes); - if (!pending.skip) { - buf = buf.slice(); - } - } - else { - if (!pending.skip) { - buf = buffers.slice(offset, bytes); - } - offset = bytes; - } - - if (pending.skip) { - pending.cb(); - } - else { - pending.cb(buf); - } - } - } - } - - function builder (saw) { - function next () { if (!done) saw.next() } - - var self = words(function (bytes, cb) { - return function (name) { - getBytes(bytes, function (buf) { - vars.set(name, cb(buf)); - next(); - }); - }; - }); - - self.tap = function (cb) { - saw.nest(cb, vars.store); - }; - - self.into = function (key, cb) { - if (!vars.get(key)) vars.set(key, {}); - var parent = vars; - vars = Vars(parent.get(key)); - - saw.nest(function () { - cb.apply(this, arguments); - this.tap(function () { - vars = parent; - }); - }, vars.store); - }; - - self.flush = function () { - vars.store = {}; - next(); - }; - - self.loop = function (cb) { - var end = false; - - saw.nest(false, function loop () { - this.vars = vars.store; - cb.call(this, function () { - end = true; - next(); - }, vars.store); - this.tap(function () { - if (end) saw.next() - else loop.call(this) - }.bind(this)); - }, vars.store); - }; - - self.buffer = function (name, bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function (buf) { - vars.set(name, buf); - next(); - }); - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function () { - next(); - }); - }; - - self.scan = function find (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - - var taken = 0; - pending = function () { - var pos = buffers.indexOf(search, offset + taken); - var i = pos-offset-taken; - if (pos !== -1) { - pending = null; - if (offset != null) { - vars.set( - name, - buffers.slice(offset, offset + taken + i) - ); - offset += taken + i + search.length; - } - else { - vars.set( - name, - buffers.slice(0, taken + i) - ); - buffers.splice(0, taken + i + search.length); - } - next(); - dispatch(); - } else { - i = Math.max(buffers.length - search.length - offset - taken, 0); - } - taken += i; - }; - dispatch(); - }; - - self.peek = function (cb) { - offset = 0; - saw.nest(function () { - cb.call(this, vars.store); - this.tap(function () { - offset = null; - }); - }); - }; - - return self; - }; - - var stream = Chainsaw.light(builder); - stream.writable = true; - - var buffers = Buffers(); - - stream.write = function (buf) { - buffers.push(buf); - dispatch(); - }; - - var vars = Vars(); - - var done = false, caughtEnd = false; - stream.end = function () { - caughtEnd = true; - }; - - stream.pipe = Stream.prototype.pipe; - Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { - stream[name] = EventEmitter.prototype[name]; - }); - - return stream; -}; - -exports.parse = function parse (buffer) { - var self = words(function (bytes, cb) { - return function (name) { - if (offset + bytes <= buffer.length) { - var buf = buffer.slice(offset, offset + bytes); - offset += bytes; - vars.set(name, cb(buf)); - } - else { - vars.set(name, null); - } - return self; - }; - }); - - var offset = 0; - var vars = Vars(); - self.vars = vars.store; - - self.tap = function (cb) { - cb.call(self, vars.store); - return self; - }; - - self.into = function (key, cb) { - if (!vars.get(key)) { - vars.set(key, {}); - } - var parent = vars; - vars = Vars(parent.get(key)); - cb.call(self, vars.store); - vars = parent; - return self; - }; - - self.loop = function (cb) { - var end = false; - var ender = function () { end = true }; - while (end === false) { - cb.call(self, ender, vars.store); - } - return self; - }; - - self.buffer = function (name, size) { - if (typeof size === 'string') { - size = vars.get(size); - } - var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); - offset += size; - vars.set(name, buf); - - return self; - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - offset += bytes; - - return self; - }; - - self.scan = function (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - vars.set(name, null); - - // simple but slow string search - for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { - for ( - var j = 0; - j < search.length && buffer[offset+i+j] === search[j]; - j++ - ); - if (j === search.length) break; - } - - vars.set(name, buffer.slice(offset, offset + i)); - offset += i + search.length; - return self; - }; - - self.peek = function (cb) { - var was = offset; - cb.call(self, vars.store); - offset = was; - return self; - }; - - self.flush = function () { - vars.store = {}; - return self; - }; - - self.eof = function () { - return offset >= buffer.length; - }; - - return self; -}; - -// convert byte strings to unsigned little endian numbers -function decodeLEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256,i) * bytes[i]; - } - return acc; -} - -// convert byte strings to unsigned big endian numbers -function decodeBEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; - } - return acc; -} - -// convert byte strings to signed big endian numbers -function decodeBEs (bytes) { - var val = decodeBEu(bytes); - if ((bytes[0] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - -// convert byte strings to signed little endian numbers -function decodeLEs (bytes) { - var val = decodeLEu(bytes); - if ((bytes[bytes.length - 1] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - -function words (decode) { - var self = {}; - - [ 1, 2, 4, 8 ].forEach(function (bytes) { - var bits = bytes * 8; - - self['word' + bits + 'le'] - = self['word' + bits + 'lu'] - = decode(bytes, decodeLEu); - - self['word' + bits + 'ls'] - = decode(bytes, decodeLEs); - - self['word' + bits + 'be'] - = self['word' + bits + 'bu'] - = decode(bytes, decodeBEu); - - self['word' + bits + 'bs'] - = decode(bytes, decodeBEs); - }); - - // word8be(n) == word8le(n) for all n - self.word8 = self.word8u = self.word8be; - self.word8s = self.word8bs; - - return self; -} - - -/***/ }), - -/***/ 13755: -/***/ ((module) => { - -module.exports = function (store) { - function getset (name, value) { - var node = vars.store; - var keys = name.split('.'); - keys.slice(0,-1).forEach(function (k) { - if (node[k] === undefined) node[k] = {}; - node = node[k] - }); - var key = keys[keys.length - 1]; - if (arguments.length == 1) { - return node[key]; - } - else { - return node[key] = value; - } - } - - var vars = { - get : function (name) { - return getset(name); - }, - set : function (name, value) { - return getset(name, value); - }, - store : store || {}, - }; - return vars; -}; - - -/***/ }), - -/***/ 21491: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWUtcmVzdWx0LmludGVyZmFjZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ibGFtZS1yZXN1bHQuaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ== - -/***/ }), - -/***/ 6686: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Blamer = void 0; -const git_1 = __nccwpck_require__(38295); -class Blamer { - async blameByFile(path) { - return this.getVCSBlamer()(path); - } - getVCSBlamer() { - return git_1.git; - } -} -exports.Blamer = Blamer; -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2JsYW1lci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFDQSxtQ0FBZ0M7QUFFaEMsTUFBYSxNQUFNO0lBQ1YsS0FBSyxDQUFDLFdBQVcsQ0FBQyxJQUFZO1FBQ25DLE9BQU8sSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ25DLENBQUM7SUFFTyxZQUFZO1FBQ2xCLE9BQU8sU0FBRyxDQUFDO0lBQ2IsQ0FBQztDQUNGO0FBUkQsd0JBUUMifQ== - -/***/ }), - -/***/ 56781: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const blamer_1 = __nccwpck_require__(6686); -__exportStar(__nccwpck_require__(21491), exports); -exports["default"] = blamer_1.Blamer; -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLHFDQUFrQztBQUVsQywyREFBeUM7QUFDekMsa0JBQWUsZUFBTSxDQUFDIn0= - -/***/ }), - -/***/ 38295: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.git = void 0; -const execa_1 = __importDefault(__nccwpck_require__(20920)); -const which_1 = __importDefault(__nccwpck_require__(34207)); -const node_fs_1 = __nccwpck_require__(87561); -const convertStringToObject = (sourceLine) => { - const matches = sourceLine.match(/(.+)\s+\((.+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (\+|\-)\d{4})\s+(\d+)\)(.*)/); - const [, rev, author, date, , line] = matches - ? [...matches] - : [null, '', '', '', '', '']; - return { - author, - date, - line, - rev - }; -}; -async function git(path) { - const blamedLines = {}; - const pathToGit = await (0, which_1.default)('git'); - if (!(0, node_fs_1.existsSync)(path)) { - throw new Error(`File ${path} does not exist`); - } - const result = execa_1.default.sync(pathToGit, ['blame', '-w', path]); - result.stdout.split('\n').forEach(line => { - if (line !== '') { - const blamedLine = convertStringToObject(line); - if (blamedLine.line) { - blamedLines[blamedLine.line] = blamedLine; - } - } - }); - return { - [path]: blamedLines - }; -} -exports.git = git; -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2l0LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3Zjcy9naXQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7O0FBQUEsa0RBQTBCO0FBQzFCLGtEQUEwQjtBQUUxQixxQ0FBcUM7QUFFckMsTUFBTSxxQkFBcUIsR0FBRyxDQUFDLFVBQWtCLEVBQWMsRUFBRTtJQUMvRCxNQUFNLE9BQU8sR0FBRyxVQUFVLENBQUMsS0FBSyxDQUM5QixrRkFBa0YsQ0FDbkYsQ0FBQztJQUNGLE1BQU0sQ0FBQyxFQUFFLEdBQUcsRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLEFBQUQsRUFBRyxJQUFJLENBQUMsR0FBRyxPQUFPO1FBQzNDLENBQUMsQ0FBQyxDQUFDLEdBQUcsT0FBTyxDQUFDO1FBQ2QsQ0FBQyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLENBQUMsQ0FBQztJQUMvQixPQUFPO1FBQ0wsTUFBTTtRQUNOLElBQUk7UUFDSixJQUFJO1FBQ0osR0FBRztLQUNKLENBQUM7QUFDSixDQUFDLENBQUM7QUFFSyxLQUFLLFVBQVUsR0FBRyxDQUFDLElBQVk7SUFDcEMsTUFBTSxXQUFXLEdBQW1DLEVBQUUsQ0FBQztJQUN2RCxNQUFNLFNBQVMsR0FBVyxNQUFNLElBQUEsZUFBSyxFQUFDLEtBQUssQ0FBQyxDQUFDO0lBRTdDLElBQUksQ0FBQyxJQUFBLG9CQUFVLEVBQUMsSUFBSSxDQUFDLEVBQUU7UUFDckIsTUFBTSxJQUFJLEtBQUssQ0FBQyxRQUFRLElBQUksaUJBQWlCLENBQUMsQ0FBQztLQUNoRDtJQUVELE1BQU0sTUFBTSxHQUFHLGVBQUssQ0FBQyxJQUFJLENBQUMsU0FBUyxFQUFFLENBQUMsT0FBTyxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO0lBQzVELE1BQU0sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUN2QyxJQUFJLElBQUksS0FBSyxFQUFFLEVBQUU7WUFDZixNQUFNLFVBQVUsR0FBRyxxQkFBcUIsQ0FBQyxJQUFJLENBQUMsQ0FBQztZQUMvQyxJQUFJLFVBQVUsQ0FBQyxJQUFJLEVBQUU7Z0JBQ25CLFdBQVcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEdBQUcsVUFBVSxDQUFDO2FBQzNDO1NBQ0Y7SUFDSCxDQUFDLENBQUMsQ0FBQztJQUNILE9BQU87UUFDTCxDQUFDLElBQUksQ0FBQyxFQUFFLFdBQVc7S0FDcEIsQ0FBQztBQUNKLENBQUM7QUFwQkQsa0JBb0JDIn0= - -/***/ }), - -/***/ 20920: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const path = __nccwpck_require__(71017); -const childProcess = __nccwpck_require__(32081); -const crossSpawn = __nccwpck_require__(72746); -const stripFinalNewline = __nccwpck_require__(88174); -const npmRunPath = __nccwpck_require__(20502); -const onetime = __nccwpck_require__(89082); -const makeError = __nccwpck_require__(11325); -const normalizeStdio = __nccwpck_require__(54149); -const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = __nccwpck_require__(77321); -const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = __nccwpck_require__(2658); -const {mergePromise, getSpawnedPromise} = __nccwpck_require__(51935); -const {joinCommand, parseCommand} = __nccwpck_require__(1099); - -const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; - -const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { - const env = extendEnv ? {...process.env, ...envOption} : envOption; - - if (preferLocal) { - return npmRunPath.env({env, cwd: localDir, execPath}); - } - - return env; -}; - -const handleArguments = (file, args, options = {}) => { - const parsed = crossSpawn._parse(file, args, options); - file = parsed.command; - args = parsed.args; - options = parsed.options; - - options = { - maxBuffer: DEFAULT_MAX_BUFFER, - buffer: true, - stripFinalNewline: true, - extendEnv: true, - preferLocal: false, - localDir: options.cwd || process.cwd(), - execPath: process.execPath, - encoding: 'utf8', - reject: true, - cleanup: true, - all: false, - windowsHide: true, - ...options - }; - - options.env = getEnv(options); - - options.stdio = normalizeStdio(options); - - if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { - // #116 - args.unshift('/q'); - } - - return {file, args, options, parsed}; -}; - -const handleOutput = (options, value, error) => { - if (typeof value !== 'string' && !Buffer.isBuffer(value)) { - // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` - return error === undefined ? undefined : ''; - } - - if (options.stripFinalNewline) { - return stripFinalNewline(value); - } - - return value; -}; - -const execa = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - - let spawned; - try { - spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); - } catch (error) { - // Ensure the returned error is always both a promise and a child process - const dummySpawned = new childProcess.ChildProcess(); - const errorPromise = Promise.reject(makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - })); - return mergePromise(dummySpawned, errorPromise); - } - - const spawnedPromise = getSpawnedPromise(spawned); - const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); - const processDone = setExitHandler(spawned, parsed.options, timedPromise); - - const context = {isCanceled: false}; - - spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); - spawned.cancel = spawnedCancel.bind(null, spawned, context); - - const handlePromise = async () => { - const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); - const stdout = handleOutput(parsed.options, stdoutResult); - const stderr = handleOutput(parsed.options, stderrResult); - const all = handleOutput(parsed.options, allResult); - - if (error || exitCode !== 0 || signal !== null) { - const returnedError = makeError({ - error, - exitCode, - signal, - stdout, - stderr, - all, - command, - parsed, - timedOut, - isCanceled: context.isCanceled, - killed: spawned.killed - }); - - if (!parsed.options.reject) { - return returnedError; - } - - throw returnedError; - } - - return { - command, - exitCode: 0, - stdout, - stderr, - all, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; - }; - - const handlePromiseOnce = onetime(handlePromise); - - crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); - - handleInput(spawned, parsed.options.input); - - spawned.all = makeAllStream(spawned, parsed.options); - - return mergePromise(spawned, handlePromiseOnce); -}; - -module.exports = execa; - -module.exports.sync = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - - validateInputSync(parsed.options); - - let result; - try { - result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); - } catch (error) { - throw makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - }); - } - - const stdout = handleOutput(parsed.options, result.stdout, result.error); - const stderr = handleOutput(parsed.options, result.stderr, result.error); - - if (result.error || result.status !== 0 || result.signal !== null) { - const error = makeError({ - stdout, - stderr, - error: result.error, - signal: result.signal, - exitCode: result.status, - command, - parsed, - timedOut: result.error && result.error.code === 'ETIMEDOUT', - isCanceled: false, - killed: result.signal !== null - }); - - if (!parsed.options.reject) { - return error; - } - - throw error; - } - - return { - command, - exitCode: 0, - stdout, - stderr, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; -}; - -module.exports.command = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa(file, args, options); -}; - -module.exports.commandSync = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa.sync(file, args, options); -}; - -module.exports.node = (scriptPath, args, options = {}) => { - if (args && !Array.isArray(args) && typeof args === 'object') { - options = args; - args = []; - } - - const stdio = normalizeStdio.node(options); - const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); - - const { - nodePath = process.execPath, - nodeOptions = defaultExecArgv - } = options; - - return execa( - nodePath, - [ - ...nodeOptions, - scriptPath, - ...(Array.isArray(args) ? args : []) - ], - { - ...options, - stdin: undefined, - stdout: undefined, - stderr: undefined, - stdio, - shell: false - } - ); -}; - - -/***/ }), - -/***/ 1099: -/***/ ((module) => { - -"use strict"; - -const SPACES_REGEXP = / +/g; - -const joinCommand = (file, args = []) => { - if (!Array.isArray(args)) { - return file; - } - - return [file, ...args].join(' '); -}; - -// Handle `execa.command()` -const parseCommand = command => { - const tokens = []; - for (const token of command.trim().split(SPACES_REGEXP)) { - // Allow spaces to be escaped by a backslash if not meant as a delimiter - const previousToken = tokens[tokens.length - 1]; - if (previousToken && previousToken.endsWith('\\')) { - // Merge previous token with current one - tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; - } else { - tokens.push(token); - } - } - - return tokens; -}; - -module.exports = { - joinCommand, - parseCommand -}; - - -/***/ }), - -/***/ 11325: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const {signalsByName} = __nccwpck_require__(27605); - -const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { - if (timedOut) { - return `timed out after ${timeout} milliseconds`; - } - - if (isCanceled) { - return 'was canceled'; - } - - if (errorCode !== undefined) { - return `failed with ${errorCode}`; - } - - if (signal !== undefined) { - return `was killed with ${signal} (${signalDescription})`; - } - - if (exitCode !== undefined) { - return `failed with exit code ${exitCode}`; - } - - return 'failed'; -}; - -const makeError = ({ - stdout, - stderr, - all, - error, - signal, - exitCode, - command, - timedOut, - isCanceled, - killed, - parsed: {options: {timeout}} -}) => { - // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. - // We normalize them to `undefined` - exitCode = exitCode === null ? undefined : exitCode; - signal = signal === null ? undefined : signal; - const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; - - const errorCode = error && error.code; - - const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); - const execaMessage = `Command ${prefix}: ${command}`; - const isError = Object.prototype.toString.call(error) === '[object Error]'; - const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; - const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); - - if (isError) { - error.originalMessage = error.message; - error.message = message; - } else { - error = new Error(message); - } - - error.shortMessage = shortMessage; - error.command = command; - error.exitCode = exitCode; - error.signal = signal; - error.signalDescription = signalDescription; - error.stdout = stdout; - error.stderr = stderr; - - if (all !== undefined) { - error.all = all; - } - - if ('bufferedData' in error) { - delete error.bufferedData; - } - - error.failed = true; - error.timedOut = Boolean(timedOut); - error.isCanceled = isCanceled; - error.killed = killed && !timedOut; - - return error; -}; - -module.exports = makeError; - - -/***/ }), - -/***/ 77321: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const os = __nccwpck_require__(22037); -const onExit = __nccwpck_require__(24931); - -const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; - -// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior -const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { - const killResult = kill(signal); - setKillTimeout(kill, signal, options, killResult); - return killResult; -}; - -const setKillTimeout = (kill, signal, options, killResult) => { - if (!shouldForceKill(signal, options, killResult)) { - return; - } - - const timeout = getForceKillAfterTimeout(options); - const t = setTimeout(() => { - kill('SIGKILL'); - }, timeout); - - // Guarded because there's no `.unref()` when `execa` is used in the renderer - // process in Electron. This cannot be tested since we don't run tests in - // Electron. - // istanbul ignore else - if (t.unref) { - t.unref(); - } -}; - -const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { - return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; -}; - -const isSigterm = signal => { - return signal === os.constants.signals.SIGTERM || - (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); -}; - -const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { - if (forceKillAfterTimeout === true) { - return DEFAULT_FORCE_KILL_TIMEOUT; - } - - if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { - throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); - } - - return forceKillAfterTimeout; -}; - -// `childProcess.cancel()` -const spawnedCancel = (spawned, context) => { - const killResult = spawned.kill(); - - if (killResult) { - context.isCanceled = true; - } -}; - -const timeoutKill = (spawned, signal, reject) => { - spawned.kill(signal); - reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); -}; - -// `timeout` option handling -const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { - if (timeout === 0 || timeout === undefined) { - return spawnedPromise; - } - - if (!Number.isFinite(timeout) || timeout < 0) { - throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); - } - - let timeoutId; - const timeoutPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - timeoutKill(spawned, killSignal, reject); - }, timeout); - }); - - const safeSpawnedPromise = spawnedPromise.finally(() => { - clearTimeout(timeoutId); - }); - - return Promise.race([timeoutPromise, safeSpawnedPromise]); -}; - -// `cleanup` option handling -const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { - if (!cleanup || detached) { - return timedPromise; - } - - const removeExitHandler = onExit(() => { - spawned.kill(); - }); - - return timedPromise.finally(() => { - removeExitHandler(); - }); -}; - -module.exports = { - spawnedKill, - spawnedCancel, - setupTimeout, - setExitHandler -}; - - -/***/ }), - -/***/ 51935: -/***/ ((module) => { - -"use strict"; - - -const nativePromisePrototype = (async () => {})().constructor.prototype; -const descriptors = ['then', 'catch', 'finally'].map(property => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) -]); - -// The return value is a mixin of `childProcess` and `Promise` -const mergePromise = (spawned, promise) => { - for (const [property, descriptor] of descriptors) { - // Starting the main `promise` is deferred to avoid consuming streams - const value = typeof promise === 'function' ? - (...args) => Reflect.apply(descriptor.value, promise(), args) : - descriptor.value.bind(promise); - - Reflect.defineProperty(spawned, property, {...descriptor, value}); - } - - return spawned; -}; - -// Use promises instead of `child_process` events -const getSpawnedPromise = spawned => { - return new Promise((resolve, reject) => { - spawned.on('exit', (exitCode, signal) => { - resolve({exitCode, signal}); - }); - - spawned.on('error', error => { - reject(error); - }); - - if (spawned.stdin) { - spawned.stdin.on('error', error => { - reject(error); - }); - } - }); -}; - -module.exports = { - mergePromise, - getSpawnedPromise -}; - - - -/***/ }), - -/***/ 54149: -/***/ ((module) => { - -"use strict"; - -const aliases = ['stdin', 'stdout', 'stderr']; - -const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined); - -const normalizeStdio = opts => { - if (!opts) { - return; - } - - const {stdio} = opts; - - if (stdio === undefined) { - return aliases.map(alias => opts[alias]); - } - - if (hasAlias(opts)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); - } - - if (typeof stdio === 'string') { - return stdio; - } - - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } - - const length = Math.max(stdio.length, aliases.length); - return Array.from({length}, (value, index) => stdio[index]); -}; - -module.exports = normalizeStdio; - -// `ipc` is pushed unless it is already present -module.exports.node = opts => { - const stdio = normalizeStdio(opts); - - if (stdio === 'ipc') { - return 'ipc'; - } - - if (stdio === undefined || typeof stdio === 'string') { - return [stdio, stdio, stdio, 'ipc']; - } - - if (stdio.includes('ipc')) { - return stdio; - } - - return [...stdio, 'ipc']; -}; - - -/***/ }), - -/***/ 2658: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const isStream = __nccwpck_require__(41554); -const getStream = __nccwpck_require__(80591); -const mergeStream = __nccwpck_require__(2621); - -// `input` option -const handleInput = (spawned, input) => { - // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 - // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 - if (input === undefined || spawned.stdin === undefined) { - return; - } - - if (isStream(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -}; - -// `all` interleaves `stdout` and `stderr` -const makeAllStream = (spawned, {all}) => { - if (!all || (!spawned.stdout && !spawned.stderr)) { - return; - } - - const mixed = mergeStream(); - - if (spawned.stdout) { - mixed.add(spawned.stdout); - } - - if (spawned.stderr) { - mixed.add(spawned.stderr); - } - - return mixed; -}; - -// On failure, `result.stdout|stderr|all` should contain the currently buffered stream -const getBufferedData = async (stream, streamPromise) => { - if (!stream) { - return; - } - - stream.destroy(); - - try { - return await streamPromise; - } catch (error) { - return error.bufferedData; - } -}; - -const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { - if (!stream || !buffer) { - return; - } - - if (encoding) { - return getStream(stream, {encoding, maxBuffer}); - } - - return getStream.buffer(stream, {maxBuffer}); -}; - -// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) -const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { - const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); - const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); - const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); - - try { - return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); - } catch (error) { - return Promise.all([ - {error, signal: error.signal, timedOut: error.timedOut}, - getBufferedData(stdout, stdoutPromise), - getBufferedData(stderr, stderrPromise), - getBufferedData(all, allPromise) - ]); - } -}; - -const validateInputSync = ({input}) => { - if (isStream(input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } -}; - -module.exports = { - handleInput, - makeAllStream, - getSpawnedResult, - validateInputSync -}; - - - -/***/ }), - -/***/ 33059: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); - -module.exports = options => { - options = {...options}; - - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; - - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } - - if (isBuffer) { - encoding = null; - } - - const stream = new PassThroughStream({objectMode}); - - if (encoding) { - stream.setEncoding(encoding); - } - - let length = 0; - const chunks = []; - - stream.on('data', chunk => { - chunks.push(chunk); - - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); - - stream.getBufferedValue = () => { - if (array) { - return chunks; - } - - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; - - stream.getBufferedLength = () => length; - - return stream; -}; - - -/***/ }), - -/***/ 80591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const {constants: BufferConstants} = __nccwpck_require__(14300); -const pump = __nccwpck_require__(18341); -const bufferStream = __nccwpck_require__(33059); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -async function getStream(inputStream, options) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } - - options = { - maxBuffer: Infinity, - ...options - }; - - const {maxBuffer} = options; - - let stream; - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } - - reject(error); - }; - - stream = pump(inputStream, bufferStream(options), error => { - if (error) { - rejectPromise(error); - return; - } - - resolve(); - }); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); - - return stream.getBufferedValue(); -} - -module.exports = getStream; -// TODO: Remove this for the next major release -module.exports["default"] = getStream; -module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); -module.exports.MaxBufferError = MaxBufferError; - - -/***/ }), - -/***/ 29778: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0; - -const SIGNALS=[ -{ -name:"SIGHUP", -number:1, -action:"terminate", -description:"Terminal closed", -standard:"posix"}, - -{ -name:"SIGINT", -number:2, -action:"terminate", -description:"User interruption with CTRL-C", -standard:"ansi"}, - -{ -name:"SIGQUIT", -number:3, -action:"core", -description:"User interruption with CTRL-\\", -standard:"posix"}, - -{ -name:"SIGILL", -number:4, -action:"core", -description:"Invalid machine instruction", -standard:"ansi"}, - -{ -name:"SIGTRAP", -number:5, -action:"core", -description:"Debugger breakpoint", -standard:"posix"}, - -{ -name:"SIGABRT", -number:6, -action:"core", -description:"Aborted", -standard:"ansi"}, - -{ -name:"SIGIOT", -number:6, -action:"core", -description:"Aborted", -standard:"bsd"}, - -{ -name:"SIGBUS", -number:7, -action:"core", -description: -"Bus error due to misaligned, non-existing address or paging error", -standard:"bsd"}, - -{ -name:"SIGEMT", -number:7, -action:"terminate", -description:"Command should be emulated but is not implemented", -standard:"other"}, - -{ -name:"SIGFPE", -number:8, -action:"core", -description:"Floating point arithmetic error", -standard:"ansi"}, - -{ -name:"SIGKILL", -number:9, -action:"terminate", -description:"Forced termination", -standard:"posix", -forced:true}, - -{ -name:"SIGUSR1", -number:10, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGSEGV", -number:11, -action:"core", -description:"Segmentation fault", -standard:"ansi"}, - -{ -name:"SIGUSR2", -number:12, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGPIPE", -number:13, -action:"terminate", -description:"Broken pipe or socket", -standard:"posix"}, - -{ -name:"SIGALRM", -number:14, -action:"terminate", -description:"Timeout or timer", -standard:"posix"}, - -{ -name:"SIGTERM", -number:15, -action:"terminate", -description:"Termination", -standard:"ansi"}, - -{ -name:"SIGSTKFLT", -number:16, -action:"terminate", -description:"Stack is empty or overflowed", -standard:"other"}, - -{ -name:"SIGCHLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"posix"}, - -{ -name:"SIGCLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"other"}, - -{ -name:"SIGCONT", -number:18, -action:"unpause", -description:"Unpaused", -standard:"posix", -forced:true}, - -{ -name:"SIGSTOP", -number:19, -action:"pause", -description:"Paused", -standard:"posix", -forced:true}, - -{ -name:"SIGTSTP", -number:20, -action:"pause", -description:"Paused using CTRL-Z or \"suspend\"", -standard:"posix"}, - -{ -name:"SIGTTIN", -number:21, -action:"pause", -description:"Background process cannot read terminal input", -standard:"posix"}, - -{ -name:"SIGBREAK", -number:21, -action:"terminate", -description:"User interruption with CTRL-BREAK", -standard:"other"}, - -{ -name:"SIGTTOU", -number:22, -action:"pause", -description:"Background process cannot write to terminal output", -standard:"posix"}, - -{ -name:"SIGURG", -number:23, -action:"ignore", -description:"Socket received out-of-band data", -standard:"bsd"}, - -{ -name:"SIGXCPU", -number:24, -action:"core", -description:"Process timed out", -standard:"bsd"}, - -{ -name:"SIGXFSZ", -number:25, -action:"core", -description:"File too big", -standard:"bsd"}, - -{ -name:"SIGVTALRM", -number:26, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGPROF", -number:27, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGWINCH", -number:28, -action:"ignore", -description:"Terminal window size changed", -standard:"bsd"}, - -{ -name:"SIGIO", -number:29, -action:"terminate", -description:"I/O is available", -standard:"other"}, - -{ -name:"SIGPOLL", -number:29, -action:"terminate", -description:"Watched event", -standard:"other"}, - -{ -name:"SIGINFO", -number:29, -action:"ignore", -description:"Request for process information", -standard:"other"}, - -{ -name:"SIGPWR", -number:30, -action:"terminate", -description:"Device running out of power", -standard:"systemv"}, - -{ -name:"SIGSYS", -number:31, -action:"core", -description:"Invalid system call", -standard:"other"}, - -{ -name:"SIGUNUSED", -number:31, -action:"terminate", -description:"Invalid system call", -standard:"other"}];exports.SIGNALS=SIGNALS; -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 27605: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037); - -var _signals=__nccwpck_require__(59519); -var _realtime=__nccwpck_require__(45904); - - - -const getSignalsByName=function(){ -const signals=(0,_signals.getSignals)(); -return signals.reduce(getSignalByName,{}); -}; - -const getSignalByName=function( -signalByNameMemo, -{name,number,description,supported,action,forced,standard}) -{ -return{ -...signalByNameMemo, -[name]:{name,number,description,supported,action,forced,standard}}; - -}; - -const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; - - - - -const getSignalsByNumber=function(){ -const signals=(0,_signals.getSignals)(); -const length=_realtime.SIGRTMAX+1; -const signalsA=Array.from({length},(value,number)=> -getSignalByNumber(number,signals)); - -return Object.assign({},...signalsA); -}; - -const getSignalByNumber=function(number,signals){ -const signal=findSignalByNumber(number,signals); - -if(signal===undefined){ -return{}; -} - -const{name,description,supported,action,forced,standard}=signal; -return{ -[number]:{ -name, -number, -description, -supported, -action, -forced, -standard}}; - - -}; - - - -const findSignalByNumber=function(number,signals){ -const signal=signals.find(({name})=>_os.constants.signals[name]===number); - -if(signal!==undefined){ -return signal; -} - -return signals.find(signalA=>signalA.number===number); -}; - -const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; -//# sourceMappingURL=main.js.map - -/***/ }), - -/***/ 45904: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0; -const getRealtimeSignals=function(){ -const length=SIGRTMAX-SIGRTMIN+1; -return Array.from({length},getRealtimeSignal); -};exports.getRealtimeSignals=getRealtimeSignals; - -const getRealtimeSignal=function(value,index){ -return{ -name:`SIGRT${index+1}`, -number:SIGRTMIN+index, -action:"terminate", -description:"Application-specific signal (realtime)", -standard:"posix"}; - -}; - -const SIGRTMIN=34; -const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; -//# sourceMappingURL=realtime.js.map - -/***/ }), - -/***/ 59519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037); - -var _core=__nccwpck_require__(29778); -var _realtime=__nccwpck_require__(45904); - - - -const getSignals=function(){ -const realtimeSignals=(0,_realtime.getRealtimeSignals)(); -const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); -return signals; -};exports.getSignals=getSignals; - - - - - - - -const normalizeSignal=function({ -name, -number:defaultNumber, -description, -action, -forced=false, -standard}) -{ -const{ -signals:{[name]:constantSignal}}= -_os.constants; -const supported=constantSignal!==undefined; -const number=supported?constantSignal:defaultNumber; -return{name,number,description,supported,action,forced,standard}; -}; -//# sourceMappingURL=signals.js.map - -/***/ }), - -/***/ 11174: -/***/ (function(module) { - -/** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } - - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; - - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; - - var parser = { - load: load, - overwrite: overwrite - }; - - var DLList; - - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } - - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } - - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } - - first() { - if (this._first != null) { - return this._first.value; - } - } - - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } - - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } - - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } - - }; - - var DLList_1 = DLList; - - var Events; - - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } - - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } - - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } - - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } - - }; - - var Events_1 = Events; - - var DLList$1, Events$1, Queues; - - DLList$1 = DLList_1; - - Events$1 = Events_1; - - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } - - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } - - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } - - push(job) { - return this._lists[job.options.priority].push(job); - } - - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } - - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } - - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } - - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } - - }; - - var Queues_1 = Queues; - - var BottleneckError; - - BottleneckError = class BottleneckError extends Error {}; - - var BottleneckError_1 = BottleneckError; - - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - - NUM_PRIORITIES = 10; - - DEFAULT_PRIORITY = 5; - - parser$1 = parser; - - BottleneckError$1 = BottleneckError_1; - - Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } - - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } - - _randomIndex() { - return Math.random().toString(36).slice(2); - } - - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } - - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } - - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } - - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } - - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } - - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } - - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } - - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } - - }; - - var Job_1 = Job; - - var BottleneckError$2, LocalDatastore, parser$2; - - parser$2 = parser; - - BottleneckError$2 = BottleneckError_1; - - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } - - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } - - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } - - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } - - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } - - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } - - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } - - async __running__() { - await this.yieldLoop(); - return this._running; - } - - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } - - async __done__() { - await this.yieldLoop(); - return this._done; - } - - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } - - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } - - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } - - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } - - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } - - isBlocked(now) { - return this._unblockTime >= now; - } - - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } - - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } - - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } - - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } - - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } - - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } - - }; - - var LocalDatastore_1 = LocalDatastore; - - var BottleneckError$3, States; - - BottleneckError$3 = BottleneckError_1; - - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } - - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } - - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } - - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } - - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } - - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } - - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } - - }; - - var States_1 = States; - - var DLList$2, Sync; - - DLList$2 = DLList_1; - - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } - - isEmpty() { - return this._queue.length === 0; - } - - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } - - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } - - }; - - var Sync_1 = Sync; - - var version = "2.19.5"; - var version$1 = { - version: version - }; - - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); - - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; - - parser$3 = parser; - - Events$2 = Events_1; - - RedisConnection$1 = require$$2; - - IORedisConnection$1 = require$$3; - - Scripts$1 = require$$4; - - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } - - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } - - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } - - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } - - keys() { - return Object.keys(this.instances); - } - - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } - - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } - - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } - - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } - - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; - - return Group; - - }).call(commonjsGlobal); - - var Group_1 = Group; - - var Batcher, Events$3, parser$4; - - parser$4 = parser; - - Events$3 = Events_1; - - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } - - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } - - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } - - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } - - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - - return Batcher; - - }).call(commonjsGlobal); - - var Batcher_1 = Batcher; - - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - - var require$$8 = getCjsExportFromNamespace(version$2); - - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; - - NUM_PRIORITIES$1 = 10; - - DEFAULT_PRIORITY$1 = 5; - - parser$5 = parser; - - Queues$1 = Queues_1; - - Job$1 = Job_1; - - LocalDatastore$1 = LocalDatastore_1; - - RedisDatastore$1 = require$$4$1; - - Events$4 = Events_1; - - States$1 = States_1; - - Sync$1 = Sync_1; - - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } - - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } - - ready() { - return this._store.ready; - } - - clients() { - return this._store.clients; - } - - channel() { - return `b_${this.id}`; - } - - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } - - publish(message) { - return this._store.__publish__(message); - } - - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } - - chain(_limiter) { - this._limiter = _limiter; - return this; - } - - queued(priority) { - return this._queues.queued(priority); - } - - clusterQueued() { - return this._store.__queued__(); - } - - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } - - running() { - return this._store.__running__(); - } - - done() { - return this._store.__done__(); - } - - jobStatus(id) { - return this._states.jobStatus(id); - } - - jobs(status) { - return this._states.statusJobs(status); - } - - counts() { - return this._states.statusCounts(); - } - - _randomIndex() { - return Math.random().toString(36).slice(2); - } - - check(weight = 1) { - return this._store.__check__(weight); - } - - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } - - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } - - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } - - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } - - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } - - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } - - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } - - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } - - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } - - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } - - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } - - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } - - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } - - currentReservoir() { - return this._store.__currentReservoir__(); - } - - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } - - } - Bottleneck.default = Bottleneck; - - Bottleneck.Events = Events$4; - - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; - - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; - - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; - - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; - - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; - - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; - - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; - - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; - - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; - - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; - - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; - - return Bottleneck; - - }).call(commonjsGlobal); - - var Bottleneck_1 = Bottleneck; - - var lib = Bottleneck_1; - - return lib; - -}))); - - -/***/ }), - -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var balanced = __nccwpck_require__(9417); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m) return [str]; - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - if (/\$$/.test(m.pre)) { - for (var k = 0; k < post.length; k++) { - var expansion = pre+ '{' + m.body + '}' + post[k]; - expansions.push(expansion); - } - } else { - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = []; - - for (var j = 0; j < n.length; j++) { - N.push.apply(N, expand(n[j], false)); - } - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - } - - return expansions; -} - - - -/***/ }), - -/***/ 50610: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const stringify = __nccwpck_require__(38750); -const compile = __nccwpck_require__(79434); -const expand = __nccwpck_require__(35873); -const parse = __nccwpck_require__(96477); - -/** - * Expand the given pattern or create a regex-compatible string. - * - * ```js - * const braces = require('braces'); - * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] - * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {String} - * @api public - */ - -const braces = (input, options = {}) => { - let output = []; - - if (Array.isArray(input)) { - for (let pattern of input) { - let result = braces.create(pattern, options); - if (Array.isArray(result)) { - output.push(...result); - } else { - output.push(result); - } - } - } else { - output = [].concat(braces.create(input, options)); - } - - if (options && options.expand === true && options.nodupes === true) { - output = [...new Set(output)]; - } - return output; -}; - -/** - * Parse the given `str` with the given `options`. - * - * ```js - * // braces.parse(pattern, [, options]); - * const ast = braces.parse('a/{b,c}/d'); - * console.log(ast); - * ``` - * @param {String} pattern Brace pattern to parse - * @param {Object} options - * @return {Object} Returns an AST - * @api public - */ - -braces.parse = (input, options = {}) => parse(input, options); - -/** - * Creates a braces string from an AST, or an AST node. - * - * ```js - * const braces = require('braces'); - * let ast = braces.parse('foo/{a,b}/bar'); - * console.log(stringify(ast.nodes[2])); //=> '{a,b}' - * ``` - * @param {String} `input` Brace pattern or AST. - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces.stringify = (input, options = {}) => { - if (typeof input === 'string') { - return stringify(braces.parse(input, options), options); - } - return stringify(input, options); -}; - -/** - * Compiles a brace pattern into a regex-compatible, optimized string. - * This method is called by the main [braces](#braces) function by default. - * - * ```js - * const braces = require('braces'); - * console.log(braces.compile('a/{b,c}/d')); - * //=> ['a/(b|c)/d'] - * ``` - * @param {String} `input` Brace pattern or AST. - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces.compile = (input, options = {}) => { - if (typeof input === 'string') { - input = braces.parse(input, options); - } - return compile(input, options); -}; - -/** - * Expands a brace pattern into an array. This method is called by the - * main [braces](#braces) function when `options.expand` is true. Before - * using this method it's recommended that you read the [performance notes](#performance)) - * and advantages of using [.compile](#compile) instead. - * - * ```js - * const braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/b/d', 'a/c/d']; - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces.expand = (input, options = {}) => { - if (typeof input === 'string') { - input = braces.parse(input, options); - } - - let result = expand(input, options); - - // filter out empty strings if specified - if (options.noempty === true) { - result = result.filter(Boolean); - } - - // filter out duplicates if specified - if (options.nodupes === true) { - result = [...new Set(result)]; - } - - return result; -}; - -/** - * Processes a brace pattern and returns either an expanded array - * (if `options.expand` is true), a highly optimized regex-compatible string. - * This method is called by the main [braces](#braces) function. - * - * ```js - * const braces = require('braces'); - * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) - * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ - -braces.create = (input, options = {}) => { - if (input === '' || input.length < 3) { - return [input]; - } - - return options.expand !== true - ? braces.compile(input, options) - : braces.expand(input, options); -}; - -/** - * Expose "braces" - */ - -module.exports = braces; - - -/***/ }), - -/***/ 79434: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const fill = __nccwpck_require__(6330); -const utils = __nccwpck_require__(45207); - -const compile = (ast, options = {}) => { - let walk = (node, parent = {}) => { - let invalidBlock = utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let invalid = invalidBlock === true || invalidNode === true; - let prefix = options.escapeInvalid === true ? '\\' : ''; - let output = ''; - - if (node.isOpen === true) { - return prefix + node.value; - } - if (node.isClose === true) { - return prefix + node.value; - } - - if (node.type === 'open') { - return invalid ? (prefix + node.value) : '('; - } - - if (node.type === 'close') { - return invalid ? (prefix + node.value) : ')'; - } - - if (node.type === 'comma') { - return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); - } - - if (node.value) { - return node.value; - } - - if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); - let range = fill(...args, { ...options, wrap: false, toRegex: true }); - - if (range.length !== 0) { - return args.length > 1 && range.length > 1 ? `(${range})` : range; - } - } - - if (node.nodes) { - for (let child of node.nodes) { - output += walk(child, node); - } - } - return output; - }; - - return walk(ast); -}; - -module.exports = compile; - - -/***/ }), - -/***/ 18774: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - MAX_LENGTH: 1024 * 64, - - // Digits - CHAR_0: '0', /* 0 */ - CHAR_9: '9', /* 9 */ - - // Alphabet chars. - CHAR_UPPERCASE_A: 'A', /* A */ - CHAR_LOWERCASE_A: 'a', /* a */ - CHAR_UPPERCASE_Z: 'Z', /* Z */ - CHAR_LOWERCASE_Z: 'z', /* z */ - - CHAR_LEFT_PARENTHESES: '(', /* ( */ - CHAR_RIGHT_PARENTHESES: ')', /* ) */ - - CHAR_ASTERISK: '*', /* * */ - - // Non-alphabetic chars. - CHAR_AMPERSAND: '&', /* & */ - CHAR_AT: '@', /* @ */ - CHAR_BACKSLASH: '\\', /* \ */ - CHAR_BACKTICK: '`', /* ` */ - CHAR_CARRIAGE_RETURN: '\r', /* \r */ - CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ - CHAR_COLON: ':', /* : */ - CHAR_COMMA: ',', /* , */ - CHAR_DOLLAR: '$', /* . */ - CHAR_DOT: '.', /* . */ - CHAR_DOUBLE_QUOTE: '"', /* " */ - CHAR_EQUAL: '=', /* = */ - CHAR_EXCLAMATION_MARK: '!', /* ! */ - CHAR_FORM_FEED: '\f', /* \f */ - CHAR_FORWARD_SLASH: '/', /* / */ - CHAR_HASH: '#', /* # */ - CHAR_HYPHEN_MINUS: '-', /* - */ - CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ - CHAR_LEFT_CURLY_BRACE: '{', /* { */ - CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ - CHAR_LINE_FEED: '\n', /* \n */ - CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ - CHAR_PERCENT: '%', /* % */ - CHAR_PLUS: '+', /* + */ - CHAR_QUESTION_MARK: '?', /* ? */ - CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ - CHAR_RIGHT_CURLY_BRACE: '}', /* } */ - CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ - CHAR_SEMICOLON: ';', /* ; */ - CHAR_SINGLE_QUOTE: '\'', /* ' */ - CHAR_SPACE: ' ', /* */ - CHAR_TAB: '\t', /* \t */ - CHAR_UNDERSCORE: '_', /* _ */ - CHAR_VERTICAL_LINE: '|', /* | */ - CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ -}; - - -/***/ }), - -/***/ 35873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const fill = __nccwpck_require__(6330); -const stringify = __nccwpck_require__(38750); -const utils = __nccwpck_require__(45207); - -const append = (queue = '', stash = '', enclose = false) => { - let result = []; - - queue = [].concat(queue); - stash = [].concat(stash); - - if (!stash.length) return queue; - if (!queue.length) { - return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; - } - - for (let item of queue) { - if (Array.isArray(item)) { - for (let value of item) { - result.push(append(value, stash, enclose)); - } - } else { - for (let ele of stash) { - if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); - } - } - } - return utils.flatten(result); -}; - -const expand = (ast, options = {}) => { - let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; - - let walk = (node, parent = {}) => { - node.queue = []; - - let p = parent; - let q = parent.queue; - - while (p.type !== 'brace' && p.type !== 'root' && p.parent) { - p = p.parent; - q = p.queue; - } - - if (node.invalid || node.dollar) { - q.push(append(q.pop(), stringify(node, options))); - return; - } - - if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { - q.push(append(q.pop(), ['{}'])); - return; - } - - if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); - - if (utils.exceedsLimit(...args, options.step, rangeLimit)) { - throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); - } - - let range = fill(...args, options); - if (range.length === 0) { - range = stringify(node, options); - } - - q.push(append(q.pop(), range)); - node.nodes = []; - return; - } - - let enclose = utils.encloseBrace(node); - let queue = node.queue; - let block = node; - - while (block.type !== 'brace' && block.type !== 'root' && block.parent) { - block = block.parent; - queue = block.queue; - } - - for (let i = 0; i < node.nodes.length; i++) { - let child = node.nodes[i]; - - if (child.type === 'comma' && node.type === 'brace') { - if (i === 1) queue.push(''); - queue.push(''); - continue; - } - - if (child.type === 'close') { - q.push(append(q.pop(), queue, enclose)); - continue; - } - - if (child.value && child.type !== 'open') { - queue.push(append(queue.pop(), child.value)); - continue; - } - - if (child.nodes) { - walk(child, node); - } - } - - return queue; - }; - - return utils.flatten(walk(ast)); -}; - -module.exports = expand; - - -/***/ }), - -/***/ 96477: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const stringify = __nccwpck_require__(38750); - -/** - * Constants - */ - -const { - MAX_LENGTH, - CHAR_BACKSLASH, /* \ */ - CHAR_BACKTICK, /* ` */ - CHAR_COMMA, /* , */ - CHAR_DOT, /* . */ - CHAR_LEFT_PARENTHESES, /* ( */ - CHAR_RIGHT_PARENTHESES, /* ) */ - CHAR_LEFT_CURLY_BRACE, /* { */ - CHAR_RIGHT_CURLY_BRACE, /* } */ - CHAR_LEFT_SQUARE_BRACKET, /* [ */ - CHAR_RIGHT_SQUARE_BRACKET, /* ] */ - CHAR_DOUBLE_QUOTE, /* " */ - CHAR_SINGLE_QUOTE, /* ' */ - CHAR_NO_BREAK_SPACE, - CHAR_ZERO_WIDTH_NOBREAK_SPACE -} = __nccwpck_require__(18774); - -/** - * parse - */ - -const parse = (input, options = {}) => { - if (typeof input !== 'string') { - throw new TypeError('Expected a string'); - } - - let opts = options || {}; - let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - if (input.length > max) { - throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); - } - - let ast = { type: 'root', input, nodes: [] }; - let stack = [ast]; - let block = ast; - let prev = ast; - let brackets = 0; - let length = input.length; - let index = 0; - let depth = 0; - let value; - let memo = {}; - - /** - * Helpers - */ - - const advance = () => input[index++]; - const push = node => { - if (node.type === 'text' && prev.type === 'dot') { - prev.type = 'text'; - } - - if (prev && prev.type === 'text' && node.type === 'text') { - prev.value += node.value; - return; - } - - block.nodes.push(node); - node.parent = block; - node.prev = prev; - prev = node; - return node; - }; - - push({ type: 'bos' }); - - while (index < length) { - block = stack[stack.length - 1]; - value = advance(); - - /** - * Invalid chars - */ - - if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { - continue; - } - - /** - * Escaped chars - */ - - if (value === CHAR_BACKSLASH) { - push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); - continue; - } - - /** - * Right square bracket (literal): ']' - */ - - if (value === CHAR_RIGHT_SQUARE_BRACKET) { - push({ type: 'text', value: '\\' + value }); - continue; - } - - /** - * Left square bracket: '[' - */ - - if (value === CHAR_LEFT_SQUARE_BRACKET) { - brackets++; - - let closed = true; - let next; - - while (index < length && (next = advance())) { - value += next; - - if (next === CHAR_LEFT_SQUARE_BRACKET) { - brackets++; - continue; - } - - if (next === CHAR_BACKSLASH) { - value += advance(); - continue; - } - - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - brackets--; - - if (brackets === 0) { - break; - } - } - } - - push({ type: 'text', value }); - continue; - } - - /** - * Parentheses - */ - - if (value === CHAR_LEFT_PARENTHESES) { - block = push({ type: 'paren', nodes: [] }); - stack.push(block); - push({ type: 'text', value }); - continue; - } - - if (value === CHAR_RIGHT_PARENTHESES) { - if (block.type !== 'paren') { - push({ type: 'text', value }); - continue; - } - block = stack.pop(); - push({ type: 'text', value }); - block = stack[stack.length - 1]; - continue; - } - - /** - * Quotes: '|"|` - */ - - if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - let open = value; - let next; - - if (options.keepQuotes !== true) { - value = ''; - } - - while (index < length && (next = advance())) { - if (next === CHAR_BACKSLASH) { - value += next + advance(); - continue; - } - - if (next === open) { - if (options.keepQuotes === true) value += next; - break; - } - - value += next; - } - - push({ type: 'text', value }); - continue; - } - - /** - * Left curly brace: '{' - */ - - if (value === CHAR_LEFT_CURLY_BRACE) { - depth++; - - let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; - let brace = { - type: 'brace', - open: true, - close: false, - dollar, - depth, - commas: 0, - ranges: 0, - nodes: [] - }; - - block = push(brace); - stack.push(block); - push({ type: 'open', value }); - continue; - } - - /** - * Right curly brace: '}' - */ - - if (value === CHAR_RIGHT_CURLY_BRACE) { - if (block.type !== 'brace') { - push({ type: 'text', value }); - continue; - } - - let type = 'close'; - block = stack.pop(); - block.close = true; - - push({ type, value }); - depth--; - - block = stack[stack.length - 1]; - continue; - } - - /** - * Comma: ',' - */ - - if (value === CHAR_COMMA && depth > 0) { - if (block.ranges > 0) { - block.ranges = 0; - let open = block.nodes.shift(); - block.nodes = [open, { type: 'text', value: stringify(block) }]; - } - - push({ type: 'comma', value }); - block.commas++; - continue; - } - - /** - * Dot: '.' - */ - - if (value === CHAR_DOT && depth > 0 && block.commas === 0) { - let siblings = block.nodes; - - if (depth === 0 || siblings.length === 0) { - push({ type: 'text', value }); - continue; - } - - if (prev.type === 'dot') { - block.range = []; - prev.value += value; - prev.type = 'range'; - - if (block.nodes.length !== 3 && block.nodes.length !== 5) { - block.invalid = true; - block.ranges = 0; - prev.type = 'text'; - continue; - } - - block.ranges++; - block.args = []; - continue; - } - - if (prev.type === 'range') { - siblings.pop(); - - let before = siblings[siblings.length - 1]; - before.value += prev.value + value; - prev = before; - block.ranges--; - continue; - } - - push({ type: 'dot', value }); - continue; - } - - /** - * Text - */ - - push({ type: 'text', value }); - } - - // Mark imbalanced braces and brackets as invalid - do { - block = stack.pop(); - - if (block.type !== 'root') { - block.nodes.forEach(node => { - if (!node.nodes) { - if (node.type === 'open') node.isOpen = true; - if (node.type === 'close') node.isClose = true; - if (!node.nodes) node.type = 'text'; - node.invalid = true; - } - }); - - // get the location of the block on parent.nodes (block's siblings) - let parent = stack[stack.length - 1]; - let index = parent.nodes.indexOf(block); - // replace the (invalid) block with it's nodes - parent.nodes.splice(index, 1, ...block.nodes); - } - } while (stack.length > 0); - - push({ type: 'eos' }); - return ast; -}; - -module.exports = parse; - - -/***/ }), - -/***/ 38750: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const utils = __nccwpck_require__(45207); - -module.exports = (ast, options = {}) => { - let stringify = (node, parent = {}) => { - let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let output = ''; - - if (node.value) { - if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { - return '\\' + node.value; - } - return node.value; - } - - if (node.value) { - return node.value; - } - - if (node.nodes) { - for (let child of node.nodes) { - output += stringify(child); - } - } - return output; - }; - - return stringify(ast); -}; - - - -/***/ }), - -/***/ 45207: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -exports.isInteger = num => { - if (typeof num === 'number') { - return Number.isInteger(num); - } - if (typeof num === 'string' && num.trim() !== '') { - return Number.isInteger(Number(num)); - } - return false; -}; - -/** - * Find a node of the given type - */ - -exports.find = (node, type) => node.nodes.find(node => node.type === type); - -/** - * Find a node of the given type - */ - -exports.exceedsLimit = (min, max, step = 1, limit) => { - if (limit === false) return false; - if (!exports.isInteger(min) || !exports.isInteger(max)) return false; - return ((Number(max) - Number(min)) / Number(step)) >= limit; -}; - -/** - * Escape the given node with '\\' before node.value - */ - -exports.escapeNode = (block, n = 0, type) => { - let node = block.nodes[n]; - if (!node) return; - - if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { - if (node.escaped !== true) { - node.value = '\\' + node.value; - node.escaped = true; - } - } -}; - -/** - * Returns true if the given brace node should be enclosed in literal braces - */ - -exports.encloseBrace = node => { - if (node.type !== 'brace') return false; - if ((node.commas >> 0 + node.ranges >> 0) === 0) { - node.invalid = true; - return true; - } - return false; -}; - -/** - * Returns true if a brace node is invalid. - */ - -exports.isInvalidBrace = block => { - if (block.type !== 'brace') return false; - if (block.invalid === true || block.dollar) return true; - if ((block.commas >> 0 + block.ranges >> 0) === 0) { - block.invalid = true; - return true; - } - if (block.open !== true || block.close !== true) { - block.invalid = true; - return true; - } - return false; -}; - -/** - * Returns true if a node is an open or close node - */ - -exports.isOpenOrClose = node => { - if (node.type === 'open' || node.type === 'close') { - return true; - } - return node.open === true || node.close === true; -}; - -/** - * Reduce an array of text nodes. - */ - -exports.reduce = nodes => nodes.reduce((acc, node) => { - if (node.type === 'text') acc.push(node.value); - if (node.type === 'range') node.type = 'text'; - return acc; -}, []); - -/** - * Flatten an array - */ - -exports.flatten = (...args) => { - const result = []; - const flat = arr => { - for (let i = 0; i < arr.length; i++) { - let ele = arr[i]; - Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); - } - return result; - }; - flat(args); - return result; -}; - - -/***/ }), - -/***/ 51590: -/***/ ((module) => { - -module.exports = Buffers; - -function Buffers (bufs) { - if (!(this instanceof Buffers)) return new Buffers(bufs); - this.buffers = bufs || []; - this.length = this.buffers.reduce(function (size, buf) { - return size + buf.length - }, 0); -} - -Buffers.prototype.push = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to push a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.push(buf); - this.length += buf.length; - } - return this.length; -}; - -Buffers.prototype.unshift = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to unshift a non-buffer'); - } - } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.unshift(buf); - this.length += buf.length; - } - return this.length; -}; - -Buffers.prototype.copy = function (dst, dStart, start, end) { - return this.slice(start, end).copy(dst, dStart, 0, end - start); -}; - -Buffers.prototype.splice = function (i, howMany) { - var buffers = this.buffers; - var index = i >= 0 ? i : this.length - i; - var reps = [].slice.call(arguments, 2); - - if (howMany === undefined) { - howMany = this.length - index; - } - else if (howMany > this.length - index) { - howMany = this.length - index; - } - - for (var i = 0; i < reps.length; i++) { - this.length += reps[i].length; - } - - var removed = new Buffers(); - var bytes = 0; - - var startBytes = 0; - for ( - var ii = 0; - ii < buffers.length && startBytes + buffers[ii].length < index; - ii ++ - ) { startBytes += buffers[ii].length } - - if (index - startBytes > 0) { - var start = index - startBytes; - - if (start + howMany < buffers[ii].length) { - removed.push(buffers[ii].slice(start, start + howMany)); - - var orig = buffers[ii]; - //var buf = new Buffer(orig.length - howMany); - var buf0 = new Buffer(start); - for (var i = 0; i < start; i++) { - buf0[i] = orig[i]; - } - - var buf1 = new Buffer(orig.length - start - howMany); - for (var i = start + howMany; i < orig.length; i++) { - buf1[ i - howMany - start ] = orig[i] - } - - if (reps.length > 0) { - var reps_ = reps.slice(); - reps_.unshift(buf0); - reps_.push(buf1); - buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); - ii += reps_.length; - reps = []; - } - else { - buffers.splice(ii, 1, buf0, buf1); - //buffers[ii] = buf; - ii += 2; - } - } - else { - removed.push(buffers[ii].slice(start)); - buffers[ii] = buffers[ii].slice(0, start); - ii ++; - } - } - - if (reps.length > 0) { - buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); - ii += reps.length; - } - - while (removed.length < howMany) { - var buf = buffers[ii]; - var len = buf.length; - var take = Math.min(len, howMany - removed.length); - - if (take === len) { - removed.push(buf); - buffers.splice(ii, 1); - } - else { - removed.push(buf.slice(0, take)); - buffers[ii] = buffers[ii].slice(take); - } - } - - this.length -= removed.length; - - return removed; -}; - -Buffers.prototype.slice = function (i, j) { - var buffers = this.buffers; - if (j === undefined) j = this.length; - if (i === undefined) i = 0; - - if (j > this.length) j = this.length; - - var startBytes = 0; - for ( - var si = 0; - si < buffers.length && startBytes + buffers[si].length <= i; - si ++ - ) { startBytes += buffers[si].length } - - var target = new Buffer(j - i); - - var ti = 0; - for (var ii = si; ti < j - i && ii < buffers.length; ii++) { - var len = buffers[ii].length; - - var start = ti === 0 ? i - startBytes : 0; - var end = ti + len >= j - i - ? Math.min(start + (j - i) - ti, len) - : len - ; - - buffers[ii].copy(target, ti, start, end); - ti += end - start; - } - - return target; -}; - -Buffers.prototype.pos = function (i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - var l = i, bi = 0, bu = null; - for (;;) { - bu = this.buffers[bi]; - if (l < bu.length) { - return {buf: bi, offset: l}; - } else { - l -= bu.length; - } - bi++; - } -}; - -Buffers.prototype.get = function get (i) { - var pos = this.pos(i); - - return this.buffers[pos.buf].get(pos.offset); -}; - -Buffers.prototype.set = function set (i, b) { - var pos = this.pos(i); - - return this.buffers[pos.buf].set(pos.offset, b); -}; - -Buffers.prototype.indexOf = function (needle, offset) { - if ("string" === typeof needle) { - needle = new Buffer(needle); - } else if (needle instanceof Buffer) { - // already a buffer - } else { - throw new Error('Invalid type for a search string'); - } - - if (!needle.length) { - return 0; - } - - if (!this.length) { - return -1; - } - - var i = 0, j = 0, match = 0, mstart, pos = 0; - - // start search from a particular point in the virtual buffer - if (offset) { - var p = this.pos(offset); - i = p.buf; - j = p.offset; - pos = offset; - } - - // for each character in virtual buffer - for (;;) { - while (j >= this.buffers[i].length) { - j = 0; - i++; - - if (i >= this.buffers.length) { - // search string not found - return -1; - } - } - - var char = this.buffers[i][j]; - - if (char == needle[match]) { - // keep track where match started - if (match == 0) { - mstart = { - i: i, - j: j, - pos: pos - }; - } - match++; - if (match == needle.length) { - // full match - return mstart.pos; - } - } else if (match != 0) { - // a partial match ended, go back to match starting position - // this will continue the search at the next character - i = mstart.i; - j = mstart.j; - pos = mstart.pos; - match = 0; - } - - j++; - pos++; - } -}; - -Buffers.prototype.toBuffer = function() { - return this.slice(); -} - -Buffers.prototype.toString = function(encoding, start, end) { - return this.slice(start, end).toString(encoding); -} - - -/***/ }), - -/***/ 86966: -/***/ ((module) => { - -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - -/** - * Module variables. - * @private - */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ - -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} - -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.split('.').map(function (s, i) { - return i === 0 - ? s.replace(formatThousandsRegExp, thousandsSeparator) - : s - }).join('.'); - } - - return str + unitSeparator + unit; -} - -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ - -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - if (isNaN(floatValue)) { - return null; - } - - return Math.floor(map[unit] * floatValue); -} - - -/***/ }), - -/***/ 28803: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var GetIntrinsic = __nccwpck_require__(74538); - -var callBind = __nccwpck_require__(62977); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - - -/***/ }), - -/***/ 62977: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); -var GetIntrinsic = __nccwpck_require__(74538); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - - -/***/ }), - -/***/ 46533: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Traverse = __nccwpck_require__(8588); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); - -module.exports = Chainsaw; -function Chainsaw (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - saw.record(); - return saw.chain(); -}; - -Chainsaw.light = function ChainsawLight (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - return saw.chain(); -}; - -Chainsaw.saw = function (builder, handlers) { - var saw = new EventEmitter; - saw.handlers = handlers; - saw.actions = []; - - saw.chain = function () { - var ch = Traverse(saw.handlers).map(function (node) { - if (this.isRoot) return node; - var ps = this.path; - - if (typeof node === 'function') { - this.update(function () { - saw.actions.push({ - path : ps, - args : [].slice.call(arguments) - }); - return ch; - }); - } - }); - - process.nextTick(function () { - saw.emit('begin'); - saw.next(); - }); - - return ch; - }; - - saw.pop = function () { - return saw.actions.shift(); - }; - - saw.next = function () { - var action = saw.pop(); - - if (!action) { - saw.emit('end'); - } - else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function (key) { node = node[key] }); - node.apply(saw.handlers, action.args); - } - }; - - saw.nest = function (cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; - - if (typeof cb === 'boolean') { - var autonext = cb; - cb = args.shift(); - } - - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); - - if (r !== undefined) s.handlers = r; - - // If we are recording... - if ("undefined" !== typeof saw.step) { - // ... our children should, too - s.record(); - } - - cb.apply(s.chain(), args); - if (autonext !== false) s.on('end', saw.next); - }; - - saw.record = function () { - upgradeChainsaw(saw); - }; - - ['trap', 'down', 'jump'].forEach(function (method) { - saw[method] = function () { - throw new Error("To use the trap, down and jump features, please "+ - "call record() first to start recording actions."); - }; - }); - - return saw; -}; - -function upgradeChainsaw(saw) { - saw.step = 0; - - // override pop - saw.pop = function () { - return saw.actions[saw.step++]; - }; - - saw.trap = function (name, cb) { - var ps = Array.isArray(name) ? name : [name]; - saw.actions.push({ - path : ps, - step : saw.step, - cb : cb, - trap : true - }); - }; - - saw.down = function (name) { - var ps = (Array.isArray(name) ? name : [name]).join('/'); - var i = saw.actions.slice(saw.step).map(function (x) { - if (x.trap && x.step <= saw.step) return false; - return x.path.join('/') == ps; - }).indexOf(true); - - if (i >= 0) saw.step += i; - else saw.step = saw.actions.length; - - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - // It's a trap! - saw.step = act.step; - act.cb(); - } - else saw.next(); - }; - - saw.jump = function (step) { - saw.step = step; - saw.next(); - }; -}; - - -/***/ }), - -/***/ 8937: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -var objIsRegex = __nccwpck_require__(96403); - -exports = (module.exports = parse); - -var TOKEN_TYPES = exports.TOKEN_TYPES = { - LINE_COMMENT: '//', - BLOCK_COMMENT: '/**/', - SINGLE_QUOTE: '\'', - DOUBLE_QUOTE: '"', - TEMPLATE_QUOTE: '`', - REGEXP: '//g' -} - -var BRACKETS = exports.BRACKETS = { - '(': ')', - '{': '}', - '[': ']' -}; -var BRACKETS_REVERSED = { - ')': '(', - '}': '{', - ']': '[' -}; - -exports.parse = parse; -function parse(src, state, options) { - options = options || {}; - state = state || exports.defaultState(); - var start = options.start || 0; - var end = options.end || src.length; - var index = start; - while (index < end) { - try { - parseChar(src[index], state); - } catch (ex) { - ex.index = index; - throw ex; - } - index++; - } - return state; -} - -exports.parseUntil = parseUntil; -function parseUntil(src, delimiter, options) { - options = options || {}; - var start = options.start || 0; - var index = start; - var state = exports.defaultState(); - while (index < src.length) { - if ((options.ignoreNesting || !state.isNesting(options)) && matches(src, delimiter, index)) { - var end = index; - return { - start: start, - end: end, - src: src.substring(start, end) - }; - } - try { - parseChar(src[index], state); - } catch (ex) { - ex.index = index; - throw ex; - } - index++; - } - var err = new Error('The end of the string was reached with no closing bracket found.'); - err.code = 'CHARACTER_PARSER:END_OF_STRING_REACHED'; - err.index = index; - throw err; -} - -exports.parseChar = parseChar; -function parseChar(character, state) { - if (character.length !== 1) { - var err = new Error('Character must be a string of length 1'); - err.name = 'InvalidArgumentError'; - err.code = 'CHARACTER_PARSER:CHAR_LENGTH_NOT_ONE'; - throw err; - } - state = state || exports.defaultState(); - state.src += character; - var wasComment = state.isComment(); - var lastChar = state.history ? state.history[0] : ''; - - - if (state.regexpStart) { - if (character === '/' || character == '*') { - state.stack.pop(); - } - state.regexpStart = false; - } - switch (state.current()) { - case TOKEN_TYPES.LINE_COMMENT: - if (character === '\n') { - state.stack.pop(); - } - break; - case TOKEN_TYPES.BLOCK_COMMENT: - if (state.lastChar === '*' && character === '/') { - state.stack.pop(); - } - break; - case TOKEN_TYPES.SINGLE_QUOTE: - if (character === '\'' && !state.escaped) { - state.stack.pop(); - } else if (character === '\\' && !state.escaped) { - state.escaped = true; - } else { - state.escaped = false; - } - break; - case TOKEN_TYPES.DOUBLE_QUOTE: - if (character === '"' && !state.escaped) { - state.stack.pop(); - } else if (character === '\\' && !state.escaped) { - state.escaped = true; - } else { - state.escaped = false; - } - break; - case TOKEN_TYPES.TEMPLATE_QUOTE: - if (character === '`' && !state.escaped) { - state.stack.pop(); - state.hasDollar = false; - } else if (character === '\\' && !state.escaped) { - state.escaped = true; - state.hasDollar = false; - } else if (character === '$' && !state.escaped) { - state.hasDollar = true; - } else if (character === '{' && state.hasDollar) { - state.stack.push(BRACKETS[character]); - } else { - state.escaped = false; - state.hasDollar = false; - } - break; - case TOKEN_TYPES.REGEXP: - if (character === '/' && !state.escaped) { - state.stack.pop(); - } else if (character === '\\' && !state.escaped) { - state.escaped = true; - } else { - state.escaped = false; - } - break; - default: - if (character in BRACKETS) { - state.stack.push(BRACKETS[character]); - } else if (character in BRACKETS_REVERSED) { - if (state.current() !== character) { - var err = new SyntaxError('Mismatched Bracket: ' + character); - err.code = 'CHARACTER_PARSER:MISMATCHED_BRACKET'; - throw err; - }; - state.stack.pop(); - } else if (lastChar === '/' && character === '/') { - // Don't include comments in history - state.history = state.history.substr(1); - state.stack.push(TOKEN_TYPES.LINE_COMMENT); - } else if (lastChar === '/' && character === '*') { - // Don't include comment in history - state.history = state.history.substr(1); - state.stack.push(TOKEN_TYPES.BLOCK_COMMENT); - } else if (character === '/' && isRegexp(state.history)) { - state.stack.push(TOKEN_TYPES.REGEXP); - // N.B. if the next character turns out to be a `*` or a `/` - // then this isn't actually a regexp - state.regexpStart = true; - } else if (character === '\'') { - state.stack.push(TOKEN_TYPES.SINGLE_QUOTE); - } else if (character === '"') { - state.stack.push(TOKEN_TYPES.DOUBLE_QUOTE); - } else if (character === '`') { - state.stack.push(TOKEN_TYPES.TEMPLATE_QUOTE); - } - break; - } - if (!state.isComment() && !wasComment) { - state.history = character + state.history; - } - state.lastChar = character; // store last character for ending block comments - return state; -} - -exports.defaultState = function () { return new State() }; -function State() { - this.stack = []; - - this.regexpStart = false; - this.escaped = false; - this.hasDollar = false; - - this.src = ''; - this.history = '' - this.lastChar = '' -} -State.prototype.current = function () { - return this.stack[this.stack.length - 1]; -}; -State.prototype.isString = function () { - return ( - this.current() === TOKEN_TYPES.SINGLE_QUOTE || - this.current() === TOKEN_TYPES.DOUBLE_QUOTE || - this.current() === TOKEN_TYPES.TEMPLATE_QUOTE - ); -} -State.prototype.isComment = function () { - return this.current() === TOKEN_TYPES.LINE_COMMENT || this.current() === TOKEN_TYPES.BLOCK_COMMENT; -} -State.prototype.isNesting = function (opts) { - if ( - opts && opts.ignoreLineComment && - this.stack.length === 1 && this.stack[0] === TOKEN_TYPES.LINE_COMMENT - ) { - // if we are only inside a line comment, and line comments are ignored - // don't count it as nesting - return false; - } - return !!this.stack.length; -} - -function matches(str, matcher, i) { - if (objIsRegex(matcher)) { - return matcher.test(str.substr(i || 0)); - } else { - return str.substr(i || 0, matcher.length) === matcher; - } -} - -exports.isPunctuator = isPunctuator -function isPunctuator(c) { - if (!c) return true; // the start of a string is a punctuator - var code = c.charCodeAt(0) - - switch (code) { - case 46: // . dot - case 40: // ( open bracket - case 41: // ) close bracket - case 59: // ; semicolon - case 44: // , comma - case 123: // { open curly brace - case 125: // } close curly brace - case 91: // [ - case 93: // ] - case 58: // : - case 63: // ? - case 126: // ~ - case 37: // % - case 38: // & - case 42: // *: - case 43: // + - case 45: // - - case 47: // / - case 60: // < - case 62: // > - case 94: // ^ - case 124: // | - case 33: // ! - case 61: // = - return true; - default: - return false; - } -} - -exports.isKeyword = isKeyword -function isKeyword(id) { - return (id === 'if') || (id === 'in') || (id === 'do') || (id === 'var') || (id === 'for') || (id === 'new') || - (id === 'try') || (id === 'let') || (id === 'this') || (id === 'else') || (id === 'case') || - (id === 'void') || (id === 'with') || (id === 'enum') || (id === 'while') || (id === 'break') || (id === 'catch') || - (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super') || - (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || - (id === 'import') || (id === 'default') || (id === 'finally') || (id === 'extends') || (id === 'function') || - (id === 'continue') || (id === 'debugger') || (id === 'package') || (id === 'private') || (id === 'interface') || - (id === 'instanceof') || (id === 'implements') || (id === 'protected') || (id === 'public') || (id === 'static'); -} + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } -function isRegexp(history) { - //could be start of regexp or divide sign + var tryEach$1 = awaitify(tryEach); - history = history.replace(/^\s*/, ''); + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } - //unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide - if (history[0] === ')') return false; - //unless it's a function expression, it's a regexp, so we assume it's a regexp - if (history[0] === '}') return true; - //any punctuation means it's a regexp - if (isPunctuator(history[0])) return true; - //if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`) - if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0].split('').reverse().join(''))) return true; + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; - return false; -} + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } -/***/ }), + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); -/***/ 2101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } -module.exports = __nccwpck_require__(16136); + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; -/***/ }), + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } -/***/ 66168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } -const { info, debug } = __nccwpck_require__(65829); -const utils = __nccwpck_require__(98911); + nextTask([]); + } -class Cell { - /** - * A representation of a cell within the table. - * Implementations must have `init` and `draw` methods, - * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties. - * @param options - * @constructor - */ - constructor(options) { - this.setOptions(options); + var waterfall$1 = awaitify(waterfall); /** - * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to - * `init` being called; - * @type {Number} + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static */ - this.x = null; - this.y = null; - } - - setOptions(options) { - if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) { - options = { content: '' + options }; - } - options = options || {}; - this.options = options; - let content = options.content; - if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) { - this.content = String(content); - } else if (!content) { - this.content = this.options.href || ''; - } else { - throw new Error('Content needs to be a primitive, got: ' + typeof content); - } - this.colSpan = options.colSpan || 1; - this.rowSpan = options.rowSpan || 1; - if (this.options.href) { - Object.defineProperty(this, 'href', { - get() { - return this.options.href; - }, - }); - } - } - mergeTableOptions(tableOptions, cells) { - this.cells = cells; - - let optionsChars = this.options.chars || {}; - let tableChars = tableOptions.chars; - let chars = (this.chars = {}); - CHAR_NAMES.forEach(function (name) { - setOption(optionsChars, tableChars, name, chars); - }); - this.truncate = this.options.truncate || tableOptions.truncate; + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, - let style = (this.options.style = this.options.style || {}); - let tableStyle = tableOptions.style; - setOption(style, tableStyle, 'padding-left', this); - setOption(style, tableStyle, 'padding-right', this); - this.head = style.head || tableStyle.head; - this.border = style.border || tableStyle.border; + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; - this.fixedWidth = tableOptions.colWidths[this.x]; - this.lines = this.computeLines(tableOptions); + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; - this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; - this.desiredHeight = this.lines.length; - } + Object.defineProperty(exports, '__esModule', { value: true }); - computeLines(tableOptions) { - const tableWordWrap = tableOptions.wordWrap || tableOptions.textWrap; - const { wordWrap = tableWordWrap } = this.options; - if (this.fixedWidth && wordWrap) { - this.fixedWidth -= this.paddingLeft + this.paddingRight; - if (this.colSpan) { - let i = 1; - while (i < this.colSpan) { - this.fixedWidth += tableOptions.colWidths[this.x + i]; - i++; - } - } - const { wrapOnWordBoundary: tableWrapOnWordBoundary = true } = tableOptions; - const { wrapOnWordBoundary = tableWrapOnWordBoundary } = this.options; - return this.wrapLines(utils.wordWrap(this.fixedWidth, this.content, wrapOnWordBoundary)); - } - return this.wrapLines(this.content.split('\n')); - } +})); - wrapLines(computedLines) { - const lines = utils.colorizeLines(computedLines); - if (this.href) { - return lines.map((line) => utils.hyperlink(this.href, line)); - } - return lines; - } - /** - * Initializes the Cells data structure. - * - * @param tableOptions - A fully populated set of tableOptions. - * In addition to the standard default values, tableOptions must have fully populated the - * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number - * of columns or rows (respectively) in this table, and each array item must be a Number. - * - */ - init(tableOptions) { - let x = this.x; - let y = this.y; - this.widths = tableOptions.colWidths.slice(x, x + this.colSpan); - this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan); - this.width = this.widths.reduce(sumPlusOne, -1); - this.height = this.heights.reduce(sumPlusOne, -1); +/***/ }), - this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; - this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; +/***/ 33497: +/***/ ((module) => { - this.drawRight = x + this.colSpan == tableOptions.colWidths.length; - } +function isBuffer (value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array +} - /** - * Draws the given line of the cell. - * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`. - * @param lineNum - can be `top`, `bottom` or a numerical line number. - * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how - * many rows below it's being called from. Otherwise it's undefined. - * @returns {String} The representation of this line. - */ - draw(lineNum, spanningCell) { - if (lineNum == 'top') return this.drawTop(this.drawRight); - if (lineNum == 'bottom') return this.drawBottom(this.drawRight); - let content = utils.truncate(this.content, 10, this.truncate); - if (!lineNum) { - info(`${this.y}-${this.x}: ${this.rowSpan - lineNum}x${this.colSpan} Cell ${content}`); - } else { - // debug(`${lineNum}-${this.x}: 1x${this.colSpan} RowSpanCell ${content}`); - } - let padLen = Math.max(this.height - this.lines.length, 0); - let padTop; - switch (this.vAlign) { - case 'center': - padTop = Math.ceil(padLen / 2); - break; - case 'bottom': - padTop = padLen; - break; - default: - padTop = 0; - } - if (lineNum < padTop || lineNum >= padTop + this.lines.length) { - return this.drawEmpty(this.drawRight, spanningCell); - } - let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; - return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); - } +function isEncoding (encoding) { + return Buffer.isEncoding(encoding) +} - /** - * Renders the top line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawTop(drawRight) { - let content = []; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - this.widths.forEach(function (width, index) { - content.push(this._topLeftChar(index)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); - }, this); - } else { - content.push(this._topLeftChar(0)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); - } - if (drawRight) { - content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); - } - return this.wrapWithStyleColors('border', content.join('')); - } +function alloc (size, fill, encoding) { + return Buffer.alloc(size, fill, encoding) +} - _topLeftChar(offset) { - let x = this.x + offset; - let leftChar; - if (this.y == 0) { - leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; - } else { - if (x == 0) { - leftChar = 'leftMid'; - } else { - leftChar = offset == 0 ? 'midMid' : 'bottomMid'; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; - if (spanAbove) { - leftChar = offset == 0 ? 'topMid' : 'mid'; - } - if (offset == 0) { - let i = 1; - while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { - i++; - } - if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { - leftChar = 'leftMid'; - } - } - } - } - } - return this.chars[leftChar]; - } +function allocUnsafe (size) { + return Buffer.allocUnsafe(size) +} - wrapWithStyleColors(styleProperty, content) { - if (this[styleProperty] && this[styleProperty].length) { - try { - let colors = __nccwpck_require__(59256); - for (let i = this[styleProperty].length - 1; i >= 0; i--) { - colors = colors[this[styleProperty][i]]; - } - return colors(content); - } catch (e) { - return content; - } - } else { - return content; - } - } +function allocUnsafeSlow (size) { + return Buffer.allocUnsafeSlow(size) +} - /** - * Renders a line of text. - * @param lineNum - Which line of text to render. This is not necessarily the line within the cell. - * There may be top-padding above the first line of text. - * @param drawRight - true if this method should render the right edge of the cell. - * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even - * if the text fits. This is used when the cell is vertically truncated. If `false` the text should - * only include the truncation symbol if the text will not fit horizontally within the cell width. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } - } - let leftPadding = utils.repeat(' ', this.paddingLeft); - let right = drawRight ? this.chars['right'] : ''; - let rightPadding = utils.repeat(' ', this.paddingRight); - let line = this.lines[lineNum]; - let len = this.width - (this.paddingLeft + this.paddingRight); - if (forceTruncationSymbol) line += this.truncate || '…'; - let content = utils.truncate(line, len, this.truncate); - content = utils.pad(content, len, ' ', this.hAlign); - content = leftPadding + content + rightPadding; - return this.stylizeLine(left, content, right); - } +function byteLength (string, encoding) { + return Buffer.byteLength(string, encoding) +} - stylizeLine(left, content, right) { - left = this.wrapWithStyleColors('border', left); - right = this.wrapWithStyleColors('border', right); - if (this.y === 0) { - content = this.wrapWithStyleColors('head', content); - } - return left + content + right; - } +function compare (a, b) { + return Buffer.compare(a, b) +} - /** - * Renders the bottom line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawBottom(drawRight) { - let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; - let content = utils.repeat(this.chars.bottom, this.width); - let right = drawRight ? this.chars['bottomRight'] : ''; - return this.wrapWithStyleColors('border', left + content + right); - } +function concat (buffers, totalLength) { + return Buffer.concat(buffers, totalLength) +} - /** - * Renders a blank line of text within the cell. Used for top and/or bottom padding. - * @param drawRight - true if this method should render the right edge of the cell. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawEmpty(drawRight, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } - } - let right = drawRight ? this.chars['right'] : ''; - let content = utils.repeat(' ', this.width); - return this.stylizeLine(left, content, right); - } +function copy (source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end) } -class ColSpanCell { - /** - * A Cell that doesn't do anything. It just draws empty lines. - * Used as a placeholder in column spanning. - * @constructor - */ - constructor() {} +function equals (a, b) { + return toBuffer(a).equals(b) +} - draw(lineNum) { - if (typeof lineNum === 'number') { - debug(`${this.y}-${this.x}: 1x1 ColSpanCell`); - } - return ''; - } +function fill (buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding) +} - init() {} +function from (value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length) +} - mergeTableOptions() {} +function includes (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding) } -class RowSpanCell { - /** - * A placeholder Cell for a Cell that spans multiple rows. - * It delegates rendering to the original cell, but adds the appropriate offset. - * @param originalCell - * @constructor - */ - constructor(originalCell) { - this.originalCell = originalCell; - } +function indexOf (buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding) +} - init(tableOptions) { - let y = this.y; - let originalY = this.originalCell.y; - this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); - } +function lastIndexOf (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) +} - draw(lineNum) { - if (lineNum == 'top') { - return this.originalCell.draw(this.offset, this.cellOffset); - } - if (lineNum == 'bottom') { - return this.originalCell.draw('bottom'); - } - debug(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`); - return this.originalCell.draw(this.offset + 1 + lineNum); - } +function swap16 (buffer) { + return toBuffer(buffer).swap16() +} - mergeTableOptions() {} +function swap32 (buffer) { + return toBuffer(buffer).swap32() } -function firstDefined(...args) { - return args.filter((v) => v !== undefined && v !== null).shift(); +function swap64 (buffer) { + return toBuffer(buffer).swap64() } -// HELPER FUNCTIONS -function setOption(objA, objB, nameB, targetObj) { - let nameA = nameB.split('-'); - if (nameA.length > 1) { - nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); - nameA = nameA.join(''); - targetObj[nameA] = firstDefined(objA[nameA], objA[nameB], objB[nameA], objB[nameB]); - } else { - targetObj[nameB] = firstDefined(objA[nameB], objB[nameB]); - } +function toBuffer (buffer) { + if (Buffer.isBuffer(buffer)) return buffer + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) } -function findDimension(dimensionTable, startingIndex, span) { - let ret = dimensionTable[startingIndex]; - for (let i = 1; i < span; i++) { - ret += 1 + dimensionTable[startingIndex + i]; - } - return ret; +function toString (buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end) } -function sumPlusOne(a, b) { - return a + b + 1; -} - -let CHAR_NAMES = [ - 'top', - 'top-mid', - 'top-left', - 'top-right', - 'bottom', - 'bottom-mid', - 'bottom-left', - 'bottom-right', - 'left', - 'left-mid', - 'mid', - 'mid-mid', - 'right', - 'right-mid', - 'middle', -]; +function write (buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding) +} -module.exports = Cell; -module.exports.ColSpanCell = ColSpanCell; -module.exports.RowSpanCell = RowSpanCell; +function writeDoubleLE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) +} +function writeFloatLE (buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) +} -/***/ }), +function writeUInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) +} -/***/ 65829: -/***/ ((module) => { +function writeInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) +} -let messages = []; -let level = 0; +function readDoubleLE (buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) +} -const debug = (msg, min) => { - if (level >= min) { - messages.push(msg); - } -}; +function readFloatLE (buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) +} -debug.WARN = 1; -debug.INFO = 2; -debug.DEBUG = 3; +function readUInt32LE (buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset) +} -debug.reset = () => { - messages = []; -}; +function readInt32LE (buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) +} -debug.setDebugLevel = (v) => { - level = v; -}; +function writeDoubleBE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleBE(value, offset) +} -debug.warn = (msg) => debug(msg, debug.WARN); -debug.info = (msg) => debug(msg, debug.INFO); -debug.debug = (msg) => debug(msg, debug.DEBUG); +function writeFloatBE (buffer, value, offset) { + return toBuffer(buffer).writeFloatBE(value, offset) +} -debug.debugMessages = () => messages; +function writeUInt32BE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32BE(value, offset) +} -module.exports = debug; +function writeInt32BE (buffer, value, offset) { + return toBuffer(buffer).writeInt32BE(value, offset) +} +function readDoubleBE (buffer, offset) { + return toBuffer(buffer).readDoubleBE(offset) +} -/***/ }), +function readFloatBE (buffer, offset) { + return toBuffer(buffer).readFloatBE(offset) +} -/***/ 93875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function readUInt32BE (buffer, offset) { + return toBuffer(buffer).readUInt32BE(offset) +} -const { warn, debug } = __nccwpck_require__(65829); -const Cell = __nccwpck_require__(66168); -const { ColSpanCell, RowSpanCell } = Cell; +function readInt32BE (buffer, offset) { + return toBuffer(buffer).readInt32BE(offset) +} -(function () { - function next(alloc, col) { - if (alloc[col] > 0) { - return next(alloc, col + 1); - } - return col; - } - - function layoutTable(table) { - let alloc = {}; - table.forEach(function (row, rowIndex) { - let col = 0; - row.forEach(function (cell) { - cell.y = rowIndex; - // Avoid erroneous call to next() on first row - cell.x = rowIndex ? next(alloc, col) : col; - const rowSpan = cell.rowSpan || 1; - const colSpan = cell.colSpan || 1; - if (rowSpan > 1) { - for (let cs = 0; cs < colSpan; cs++) { - alloc[cell.x + cs] = rowSpan; - } - } - col = cell.x + colSpan; - }); - Object.keys(alloc).forEach((idx) => { - alloc[idx]--; - if (alloc[idx] < 1) delete alloc[idx]; - }); - }); - } +module.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE, + writeDoubleBE, + writeFloatBE, + writeUInt32BE, + writeInt32BE, + readDoubleBE, + readFloatBE, + readUInt32BE, + readInt32BE - function maxWidth(table) { - let mw = 0; - table.forEach(function (row) { - row.forEach(function (cell) { - mw = Math.max(mw, cell.x + (cell.colSpan || 1)); - }); - }); - return mw; - } +} - function maxHeight(table) { - return table.length; - } - function cellsConflict(cell1, cell2) { - let yMin1 = cell1.y; - let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); - let yMin2 = cell2.y; - let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); - let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); +/***/ }), - let xMin1 = cell1.x; - let xMax1 = cell1.x - 1 + (cell1.colSpan || 1); - let xMin2 = cell2.x; - let xMax2 = cell2.x - 1 + (cell2.colSpan || 1); - let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); +/***/ 18098: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return yConflict && xConflict; - } +"use strict"; - function conflictExists(rows, x, y) { - let i_max = Math.min(rows.length - 1, y); - let cell = { x: x, y: y }; - for (let i = 0; i <= i_max; i++) { - let row = rows[i]; - for (let j = 0; j < row.length; j++) { - if (cellsConflict(cell, row[j])) { - return true; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const t = __importStar(__nccwpck_require__(7912)); +if (!(Array.isArray(t.TYPES) && + t.TYPES.every((t) => typeof t === 'string'))) { + throw new Error('@babel/types TYPES does not match the expected type.'); +} +const FLIPPED_ALIAS_KEYS = t + .FLIPPED_ALIAS_KEYS; +const TYPES = new Set(t.TYPES); +if (!(FLIPPED_ALIAS_KEYS && + // tslint:disable-next-line: strict-type-predicates + typeof FLIPPED_ALIAS_KEYS === 'object' && + Object.keys(FLIPPED_ALIAS_KEYS).every((key) => Array.isArray(FLIPPED_ALIAS_KEYS[key]) && + // tslint:disable-next-line: strict-type-predicates + FLIPPED_ALIAS_KEYS[key].every((v) => typeof v === 'string')))) { + throw new Error('@babel/types FLIPPED_ALIAS_KEYS does not match the expected type.'); +} +/** + * This serves thre functions: + * + * 1. Take any "aliases" and explode them to refecence the concrete types + * 2. Normalize all handlers to have an `{enter, exit}` pair, rather than raw functions + * 3. make the enter and exit handlers arrays, so that multiple handlers can be merged + */ +function explode(input) { + const results = {}; + for (const key in input) { + const aliases = FLIPPED_ALIAS_KEYS[key]; + if (aliases) { + for (const concreteKey of aliases) { + if (concreteKey in results) { + if (typeof input[key] === 'function') { + results[concreteKey].enter.push(input[key]); + } + else { + if (input[key].enter) + results[concreteKey].enter.push(input[key].enter); + if (input[key].exit) + results[concreteKey].exit.push(input[key].exit); + } + } + else { + if (typeof input[key] === 'function') { + results[concreteKey] = { + enter: [input[key]], + exit: [], + }; + } + else { + results[concreteKey] = { + enter: input[key].enter ? [input[key].enter] : [], + exit: input[key].exit ? [input[key].exit] : [], + }; + } + } + } + } + else if (TYPES.has(key)) { + if (key in results) { + if (typeof input[key] === 'function') { + results[key].enter.push(input[key]); + } + else { + if (input[key].enter) + results[key].enter.push(input[key].enter); + if (input[key].exit) + results[key].exit.push(input[key].exit); + } + } + else { + if (typeof input[key] === 'function') { + results[key] = { + enter: [input[key]], + exit: [], + }; + } + else { + results[key] = { + enter: input[key].enter ? [input[key].enter] : [], + exit: input[key].exit ? [input[key].exit] : [], + }; + } + } } - } } - return false; - } + return results; +} +exports["default"] = explode; +//# sourceMappingURL=explode.js.map - function allBlank(rows, y, xMin, xMax) { - for (let x = xMin; x < xMax; x++) { - if (conflictExists(rows, x, y)) { - return false; - } - } - return true; - } +/***/ }), - function addRowSpanCells(table) { - table.forEach(function (row, rowIndex) { - row.forEach(function (cell) { - for (let i = 1; i < cell.rowSpan; i++) { - let rowSpanCell = new RowSpanCell(cell); - rowSpanCell.x = cell.x; - rowSpanCell.y = cell.y + i; - rowSpanCell.colSpan = cell.colSpan; - insertCell(rowSpanCell, table[rowIndex + i]); - } - }); - }); - } +/***/ 6407: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - function addColSpanCells(cellRows) { - for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { - let cellColumns = cellRows[rowIndex]; - for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { - let cell = cellColumns[columnIndex]; - for (let k = 1; k < cell.colSpan; k++) { - let colSpanCell = new ColSpanCell(); - colSpanCell.x = cell.x + k; - colSpanCell.y = cell.y; - cellColumns.splice(columnIndex + 1, 0, colSpanCell); - } - } - } - } +"use strict"; - function insertCell(cell, row) { - let x = 0; - while (x < row.length && row[x].x < cell.x) { - x++; - } - row.splice(x, 0, cell); - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.recursive = exports.ancestor = exports.simple = void 0; +const t = __importStar(__nccwpck_require__(7912)); +const explode_1 = __importDefault(__nccwpck_require__(18098)); +const VISITOR_KEYS = t.VISITOR_KEYS; +if (!(VISITOR_KEYS && + // tslint:disable-next-line: strict-type-predicates + typeof VISITOR_KEYS === 'object' && + Object.keys(VISITOR_KEYS).every((key) => Array.isArray(VISITOR_KEYS[key]) && + // tslint:disable-next-line: strict-type-predicates + VISITOR_KEYS[key].every((v) => typeof v === 'string')))) { + throw new Error('@babel/types VISITOR_KEYS does not match the expected type.'); +} +function simple(visitors) { + const vis = explode_1.default(visitors); + return (node, state) => { + (function recurse(node) { + if (!node) + return; + const visitor = vis[node.type]; + if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { + for (const v of visitor.enter) { + v(node, state); + } + } + for (const key of VISITOR_KEYS[node.type] || []) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (const subSubNode of subNode) { + recurse(subSubNode); + } + } + else { + recurse(subNode); + } + } + if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) { + for (const v of visitor.exit) { + v(node, state); + } + } + })(node); + }; +} +exports.simple = simple; +function ancestor(visitors) { + const vis = explode_1.default(visitors); + return (node, state) => { + const ancestors = []; + (function recurse(node) { + if (!node) + return; + const visitor = vis[node.type]; + const isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) + ancestors.push(node); + if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { + for (const v of visitor.enter) { + v(node, state, ancestors); + } + } + for (const key of VISITOR_KEYS[node.type] || []) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (const subSubNode of subNode) { + recurse(subSubNode); + } + } + else { + recurse(subNode); + } + } + if (visitor === null || visitor === void 0 ? void 0 : visitor.exit) { + for (const v of visitor.exit) { + v(node, state, ancestors); + } + } + if (isNew) + ancestors.pop(); + })(node); + }; +} +exports.ancestor = ancestor; +function recursive(visitors) { + const vis = explode_1.default(visitors); + return (node, state) => { + (function recurse(node) { + if (!node) + return; + const visitor = vis[node.type]; + if (visitor === null || visitor === void 0 ? void 0 : visitor.enter) { + for (const v of visitor.enter) { + v(node, state, recurse); + } + } + else { + for (const key of VISITOR_KEYS[node.type] || []) { + const subNode = node[key]; + if (Array.isArray(subNode)) { + for (const subSubNode of subNode) { + recurse(subSubNode); + } + } + else { + recurse(subNode); + } + } + } + })(node); + }; +} +exports.recursive = recursive; +//# sourceMappingURL=index.js.map - function fillInTable(table) { - let h_max = maxHeight(table); - let w_max = maxWidth(table); - debug(`Max rows: ${h_max}; Max cols: ${w_max}`); - for (let y = 0; y < h_max; y++) { - for (let x = 0; x < w_max; x++) { - if (!conflictExists(table, x, y)) { - let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; - x++; - while (x < w_max && !conflictExists(table, x, y)) { - opts.colSpan++; - x++; - } - let y2 = y + 1; - while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { - opts.rowSpan++; - y2++; - } - let cell = new Cell(opts); - cell.x = opts.x; - cell.y = opts.y; - warn(`Missing cell at ${cell.y}-${cell.x}.`); - insertCell(cell, table[y]); - } - } - } - } +/***/ }), + +/***/ 9417: +/***/ ((module) => { - function generateCells(rows) { - return rows.map(function (row) { - if (!Array.isArray(row)) { - let key = Object.keys(row)[0]; - row = row[key]; - if (Array.isArray(row)) { - row = row.slice(); - row.unshift(key); - } else { - row = [key, row]; - } - } - return row.map(function (cell) { - return new Cell(cell); - }); - }); - } +"use strict"; - function makeTableLayout(rows) { - let cellRows = generateCells(rows); - layoutTable(cellRows); - fillInTable(cellRows); - addRowSpanCells(cellRows); - addColSpanCells(cellRows); - return cellRows; - } +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); - module.exports = { - makeTableLayout: makeTableLayout, - layoutTable: layoutTable, - addRowSpanCells: addRowSpanCells, - maxWidth: maxWidth, - fillInTable: fillInTable, - computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), - computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) }; -})(); +} -function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { - return function (vals, table) { - let result = []; - let spanners = []; - let auto = {}; - table.forEach(function (row) { - row.forEach(function (cell) { - if ((cell[colSpan] || 1) > 1) { - spanners.push(cell); - } else { - result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); - } - }); - }); +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} - vals.forEach(function (val, index) { - if (typeof val === 'number') { - result[index] = val; - } - }); +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - //spanners.forEach(function(cell){ - for (let k = spanners.length - 1; k >= 0; k--) { - let cell = spanners[k]; - let span = cell[colSpan]; - let col = cell[x]; - let existingWidth = result[col]; - let editableCols = typeof vals[col] === 'number' ? 0 : 1; - if (typeof existingWidth === 'number') { - for (let i = 1; i < span; i++) { - existingWidth += 1 + result[col + i]; - if (typeof vals[col + i] !== 'number') { - editableCols++; - } - } + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; } else { - existingWidth = desiredWidth === 'desiredWidth' ? cell.desiredWidth - 1 : 1; - if (!auto[col] || auto[col] < existingWidth) { - auto[col] = existingWidth; + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; } - } - if (cell[desiredWidth] > existingWidth) { - let i = 0; - while (editableCols > 0 && cell[desiredWidth] > existingWidth) { - if (typeof vals[col + i] !== 'number') { - let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); - existingWidth += dif; - result[col + i] += dif; - editableCols--; - } - i++; - } + bi = str.indexOf(b, i + 1); } + + i = ai < bi && ai >= 0 ? ai : bi; } - Object.assign(vals, result, auto); - for (let j = 0; j < vals.length; j++) { - vals[j] = Math.max(forcedMin, vals[j] || 0); + if (begs.length) { + result = [ left, right ]; } - }; + } + + return result; } /***/ }), -/***/ 16136: +/***/ 83682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const debug = __nccwpck_require__(65829); -const utils = __nccwpck_require__(98911); -const tableLayout = __nccwpck_require__(93875); +var register = __nccwpck_require__(44670) +var addHook = __nccwpck_require__(5549) +var removeHook = __nccwpck_require__(6819) -class Table extends Array { - constructor(opts) { - super(); +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) - const options = utils.mergeOptions(opts); - Object.defineProperty(this, 'options', { - value: options, - enumerable: options.debug, - }); +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef - if (options.debug) { - switch (typeof options.debug) { - case 'boolean': - debug.setDebugLevel(debug.WARN); - break; - case 'number': - debug.setDebugLevel(options.debug); - break; - case 'string': - debug.setDebugLevel(parseInt(options.debug, 10)); - break; - default: - debug.setDebugLevel(debug.WARN); - debug.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof options.debug}`); - } - Object.defineProperty(this, 'messages', { - get() { - return debug.debugMessages(); - }, - }); - } + ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind] + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) + }) +} + +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} - toString() { - let array = this; - let headersPresent = this.options.head && this.options.head.length; - if (headersPresent) { - array = [this.options.head]; - if (this.length) { - array.push.apply(array, this); - } - } else { - this.options.style.head = []; - } +function HookCollection () { + var state = { + registry: {} + } + + var hook = register.bind(null, state) + bindApi(hook, state) - let cells = tableLayout.makeTableLayout(array); + return hook +} - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.mergeTableOptions(this.options, cells); - }, this); - }, this); +var collectionHookDeprecationMessageDisplayed = false +function Hook () { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') + collectionHookDeprecationMessageDisplayed = true + } + return HookCollection() +} - tableLayout.computeWidths(this.options.colWidths, cells); - tableLayout.computeHeights(this.options.rowHeights, cells); +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.init(this.options); - }, this); - }, this); +module.exports = Hook +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook +module.exports.Singular = Hook.Singular +module.exports.Collection = Hook.Collection - let result = []; - for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { - let row = cells[rowIndex]; - let heightOfRow = this.options.rowHeights[rowIndex]; +/***/ }), - if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { - doDraw(row, 'top', result); - } +/***/ 5549: +/***/ ((module) => { - for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { - doDraw(row, lineNum, result); - } +module.exports = addHook; - if (rowIndex + 1 == cells.length) { - doDraw(row, 'bottom', result); - } - } +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - return result.join('\n'); + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; } - get width() { - let str = this.toString().split('\n'); - return str[0].length; + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; } -} -Table.reset = () => debug.reset(); + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } -function doDraw(row, lineNum, result) { - let line = []; - row.forEach(function (cell) { - line.push(cell.draw(lineNum)); + state.registry[name].push({ + hook: hook, + orig: orig, }); - let str = line.join(''); - if (str.length) result.push(str); } -module.exports = Table; - /***/ }), -/***/ 98911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const stringWidth = __nccwpck_require__(42577); - -function codeRegex(capture) { - return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; -} - -function strlen(str) { - let code = codeRegex(); - let stripped = ('' + str).replace(code, ''); - let split = stripped.split('\n'); - return split.reduce(function (memo, s) { - return stringWidth(s) > memo ? stringWidth(s) : memo; - }, 0); -} +/***/ 44670: +/***/ ((module) => { -function repeat(str, times) { - return Array(times + 1).join(str); -} +module.exports = register; -function pad(str, len, pad, dir) { - let length = strlen(str); - if (len + 1 >= length) { - let padlen = len - length; - switch (dir) { - case 'right': { - str = repeat(pad, padlen) + str; - break; - } - case 'center': { - let right = Math.ceil(padlen / 2); - let left = padlen - right; - str = repeat(pad, left) + str + repeat(pad, right); - break; - } - default: { - str = str + repeat(pad, padlen); - break; - } - } +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); } - return str; -} - -let codeCache = {}; - -function addToCodeCache(name, on, off) { - on = '\u001b[' + on + 'm'; - off = '\u001b[' + off + 'm'; - codeCache[on] = { set: name, to: true }; - codeCache[off] = { set: name, to: false }; - codeCache[name] = { on: on, off: off }; -} - -//https://github.com/Marak/colors.js/blob/master/lib/styles.js -addToCodeCache('bold', 1, 22); -addToCodeCache('italics', 3, 23); -addToCodeCache('underline', 4, 24); -addToCodeCache('inverse', 7, 27); -addToCodeCache('strikethrough', 9, 29); -function updateState(state, controlChars) { - let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; - if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { - state.lastForegroundAdded = controlChars[0]; - return; - } - if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { - state.lastBackgroundAdded = controlChars[0]; - return; - } - if (controlCode === 0) { - for (let i in state) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(state, i)) { - delete state[i]; - } - } - return; - } - let info = codeCache[controlChars[0]]; - if (info) { - state[info.set] = info.to; + if (!options) { + options = {}; } -} -function readState(line) { - let code = codeRegex(true); - let controlChars = code.exec(line); - let state = {}; - while (controlChars !== null) { - updateState(state, controlChars); - controlChars = code.exec(line); + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); } - return state; -} -function unwindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; - - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; - - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret += codeCache[key].off; + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - }); - - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret += '\u001b[49m'; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret += '\u001b[39m'; - } - return ret; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } -function rewindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; - - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret = codeCache[key].on + ret; - } - }); +/***/ }), - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret = lastBackgroundAdded + ret; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret = lastForegroundAdded + ret; - } +/***/ 6819: +/***/ ((module) => { - return ret; -} +module.exports = removeHook; -function truncateWidth(str, desiredLength) { - if (str.length === strlen(str)) { - return str.substr(0, desiredLength); +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; } - while (strlen(str) > desiredLength) { - str = str.slice(0, -1); + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; } - return str; + state.registry[name].splice(index, 1); } -function truncateWidthWithAnsi(str, desiredLength) { - let code = codeRegex(true); - let split = str.split(codeRegex()); - let splitIndex = 0; - let retLen = 0; - let ret = ''; - let myArray; - let state = {}; - while (retLen < desiredLength) { - myArray = code.exec(str); - let toAdd = split[splitIndex]; - splitIndex++; - if (retLen + strlen(toAdd) > desiredLength) { - toAdd = truncateWidth(toAdd, desiredLength - retLen); - } - ret += toAdd; - retLen += strlen(toAdd); +/***/ }), - if (retLen < desiredLength) { - if (!myArray) { - break; - } // full-width chars may cause a whitespace which cannot be filled - ret += myArray[0]; - updateState(state, myArray); - } - } +/***/ 66474: +/***/ ((module, exports, __nccwpck_require__) => { - return unwindState(state, ret); -} +var Chainsaw = __nccwpck_require__(46533); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); +var Buffers = __nccwpck_require__(51590); +var Vars = __nccwpck_require__(13755); +var Stream = (__nccwpck_require__(12781).Stream); -function truncate(str, desiredLength, truncateChar) { - truncateChar = truncateChar || '…'; - let lengthOfStr = strlen(str); - if (lengthOfStr <= desiredLength) { - return str; - } - desiredLength -= strlen(truncateChar); +exports = module.exports = function (bufOrEm, eventName) { + if (Buffer.isBuffer(bufOrEm)) { + return exports.parse(bufOrEm); + } + + var s = exports.stream(); + if (bufOrEm && bufOrEm.pipe) { + bufOrEm.pipe(s); + } + else if (bufOrEm) { + bufOrEm.on(eventName || 'data', function (buf) { + s.write(buf); + }); + + bufOrEm.on('end', function () { + s.end(); + }); + } + return s; +}; - let ret = truncateWidthWithAnsi(str, desiredLength); +exports.stream = function (input) { + if (input) return exports.apply(null, arguments); + + var pending = null; + function getBytes (bytes, cb, skip) { + pending = { + bytes : bytes, + skip : skip, + cb : function (buf) { + pending = null; + cb(buf); + }, + }; + dispatch(); + } + + var offset = null; + function dispatch () { + if (!pending) { + if (caughtEnd) done = true; + return; + } + if (typeof pending === 'function') { + pending(); + } + else { + var bytes = offset + pending.bytes; + + if (buffers.length >= bytes) { + var buf; + if (offset == null) { + buf = buffers.splice(0, bytes); + if (!pending.skip) { + buf = buf.slice(); + } + } + else { + if (!pending.skip) { + buf = buffers.slice(offset, bytes); + } + offset = bytes; + } + + if (pending.skip) { + pending.cb(); + } + else { + pending.cb(buf); + } + } + } + } + + function builder (saw) { + function next () { if (!done) saw.next() } + + var self = words(function (bytes, cb) { + return function (name) { + getBytes(bytes, function (buf) { + vars.set(name, cb(buf)); + next(); + }); + }; + }); + + self.tap = function (cb) { + saw.nest(cb, vars.store); + }; + + self.into = function (key, cb) { + if (!vars.get(key)) vars.set(key, {}); + var parent = vars; + vars = Vars(parent.get(key)); + + saw.nest(function () { + cb.apply(this, arguments); + this.tap(function () { + vars = parent; + }); + }, vars.store); + }; + + self.flush = function () { + vars.store = {}; + next(); + }; + + self.loop = function (cb) { + var end = false; + + saw.nest(false, function loop () { + this.vars = vars.store; + cb.call(this, function () { + end = true; + next(); + }, vars.store); + this.tap(function () { + if (end) saw.next() + else loop.call(this) + }.bind(this)); + }, vars.store); + }; + + self.buffer = function (name, bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function (buf) { + vars.set(name, buf); + next(); + }); + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function () { + next(); + }); + }; + + self.scan = function find (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + + var taken = 0; + pending = function () { + var pos = buffers.indexOf(search, offset + taken); + var i = pos-offset-taken; + if (pos !== -1) { + pending = null; + if (offset != null) { + vars.set( + name, + buffers.slice(offset, offset + taken + i) + ); + offset += taken + i + search.length; + } + else { + vars.set( + name, + buffers.slice(0, taken + i) + ); + buffers.splice(0, taken + i + search.length); + } + next(); + dispatch(); + } else { + i = Math.max(buffers.length - search.length - offset - taken, 0); + } + taken += i; + }; + dispatch(); + }; + + self.peek = function (cb) { + offset = 0; + saw.nest(function () { + cb.call(this, vars.store); + this.tap(function () { + offset = null; + }); + }); + }; + + return self; + }; + + var stream = Chainsaw.light(builder); + stream.writable = true; + + var buffers = Buffers(); + + stream.write = function (buf) { + buffers.push(buf); + dispatch(); + }; + + var vars = Vars(); + + var done = false, caughtEnd = false; + stream.end = function () { + caughtEnd = true; + }; + + stream.pipe = Stream.prototype.pipe; + Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { + stream[name] = EventEmitter.prototype[name]; + }); + + return stream; +}; - return ret + truncateChar; -} +exports.parse = function parse (buffer) { + var self = words(function (bytes, cb) { + return function (name) { + if (offset + bytes <= buffer.length) { + var buf = buffer.slice(offset, offset + bytes); + offset += bytes; + vars.set(name, cb(buf)); + } + else { + vars.set(name, null); + } + return self; + }; + }); + + var offset = 0; + var vars = Vars(); + self.vars = vars.store; + + self.tap = function (cb) { + cb.call(self, vars.store); + return self; + }; + + self.into = function (key, cb) { + if (!vars.get(key)) { + vars.set(key, {}); + } + var parent = vars; + vars = Vars(parent.get(key)); + cb.call(self, vars.store); + vars = parent; + return self; + }; + + self.loop = function (cb) { + var end = false; + var ender = function () { end = true }; + while (end === false) { + cb.call(self, ender, vars.store); + } + return self; + }; + + self.buffer = function (name, size) { + if (typeof size === 'string') { + size = vars.get(size); + } + var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); + offset += size; + vars.set(name, buf); + + return self; + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + offset += bytes; + + return self; + }; + + self.scan = function (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + vars.set(name, null); + + // simple but slow string search + for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { + for ( + var j = 0; + j < search.length && buffer[offset+i+j] === search[j]; + j++ + ); + if (j === search.length) break; + } + + vars.set(name, buffer.slice(offset, offset + i)); + offset += i + search.length; + return self; + }; + + self.peek = function (cb) { + var was = offset; + cb.call(self, vars.store); + offset = was; + return self; + }; + + self.flush = function () { + vars.store = {}; + return self; + }; + + self.eof = function () { + return offset >= buffer.length; + }; + + return self; +}; -function defaultOptions() { - return { - chars: { - top: '─', - 'top-mid': '┬', - 'top-left': '┌', - 'top-right': '┐', - bottom: '─', - 'bottom-mid': '┴', - 'bottom-left': '└', - 'bottom-right': '┘', - left: '│', - 'left-mid': '├', - mid: '─', - 'mid-mid': '┼', - right: '│', - 'right-mid': '┤', - middle: '│', - }, - truncate: '…', - colWidths: [], - rowHeights: [], - colAligns: [], - rowAligns: [], - style: { - 'padding-left': 1, - 'padding-right': 1, - head: ['red'], - border: ['grey'], - compact: false, - }, - head: [], - }; +// convert byte strings to unsigned little endian numbers +function decodeLEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256,i) * bytes[i]; + } + return acc; } -function mergeOptions(options, defaults) { - options = options || {}; - defaults = defaults || defaultOptions(); - let ret = Object.assign({}, defaults, options); - ret.chars = Object.assign({}, defaults.chars, options.chars); - ret.style = Object.assign({}, defaults.style, options.style); - return ret; +// convert byte strings to unsigned big endian numbers +function decodeBEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; + } + return acc; } -// Wrap on word boundary -function wordWrap(maxLength, input) { - let lines = []; - let split = input.split(/(\s+)/g); - let line = []; - let lineLength = 0; - let whitespace; - for (let i = 0; i < split.length; i += 2) { - let word = split[i]; - let newLength = lineLength + strlen(word); - if (lineLength > 0 && whitespace) { - newLength += whitespace.length; - } - if (newLength > maxLength) { - if (lineLength !== 0) { - lines.push(line.join('')); - } - line = [word]; - lineLength = strlen(word); - } else { - line.push(whitespace || '', word); - lineLength = newLength; +// convert byte strings to signed big endian numbers +function decodeBEs (bytes) { + var val = decodeBEu(bytes); + if ((bytes[0] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); } - whitespace = split[i + 1]; - } - if (lineLength) { - lines.push(line.join('')); - } - return lines; + return val; } -// Wrap text (ignoring word boundaries) -function textWrap(maxLength, input) { - let lines = []; - let line = ''; - function pushLine(str, ws) { - if (line.length && ws) line += ws; - line += str; - while (line.length > maxLength) { - lines.push(line.slice(0, maxLength)); - line = line.slice(maxLength); +// convert byte strings to signed little endian numbers +function decodeLEs (bytes) { + var val = decodeLEu(bytes); + if ((bytes[bytes.length - 1] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); } - } - let split = input.split(/(\s+)/g); - for (let i = 0; i < split.length; i += 2) { - pushLine(split[i], i && split[i - 1]); - } - if (line.length) lines.push(line); - return lines; + return val; } -function multiLineWordWrap(maxLength, input, wrapOnWordBoundary = true) { - let output = []; - input = input.split('\n'); - const handler = wrapOnWordBoundary ? wordWrap : textWrap; - for (let i = 0; i < input.length; i++) { - output.push.apply(output, handler(maxLength, input[i])); - } - return output; +function words (decode) { + var self = {}; + + [ 1, 2, 4, 8 ].forEach(function (bytes) { + var bits = bytes * 8; + + self['word' + bits + 'le'] + = self['word' + bits + 'lu'] + = decode(bytes, decodeLEu); + + self['word' + bits + 'ls'] + = decode(bytes, decodeLEs); + + self['word' + bits + 'be'] + = self['word' + bits + 'bu'] + = decode(bytes, decodeBEu); + + self['word' + bits + 'bs'] + = decode(bytes, decodeBEs); + }); + + // word8be(n) == word8le(n) for all n + self.word8 = self.word8u = self.word8be; + self.word8s = self.word8bs; + + return self; } -function colorizeLines(input) { - let state = {}; - let output = []; - for (let i = 0; i < input.length; i++) { - let line = rewindState(state, input[i]); - state = readState(line); - let temp = Object.assign({}, state); - output.push(unwindState(temp, line)); - } - return output; -} -/** - * Credit: Matheus Sampaio https://github.com/matheussampaio - */ -function hyperlink(url, text) { - const OSC = '\u001B]'; - const BEL = '\u0007'; - const SEP = ';'; +/***/ }), - return [OSC, '8', SEP, SEP, url || text, BEL, text, OSC, '8', SEP, SEP, BEL].join(''); -} +/***/ 13755: +/***/ ((module) => { -module.exports = { - strlen: strlen, - repeat: repeat, - pad: pad, - truncate: truncate, - mergeOptions: mergeOptions, - wordWrap: multiLineWordWrap, - colorizeLines: colorizeLines, - hyperlink, +module.exports = function (store) { + function getset (name, value) { + var node = vars.store; + var keys = name.split('.'); + keys.slice(0,-1).forEach(function (k) { + if (node[k] === undefined) node[k] = {}; + node = node[k] + }); + var key = keys[keys.length - 1]; + if (arguments.length == 1) { + return node[key]; + } + else { + return node[key] = value; + } + } + + var vars = { + get : function (name) { + return getset(name); + }, + set : function (name, value) { + return getset(name, value); + }, + store : store || {}, + }; + return vars; }; /***/ }), -/***/ 43595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* - -The MIT License (MIT) - -Original Library - - Copyright (c) Marak Squires - -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +/***/ 21491: +/***/ ((__unused_webpack_module, exports) => { -*/ +"use strict"; -var colors = {}; -module['exports'] = colors; +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWUtcmVzdWx0LmludGVyZmFjZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ibGFtZS1yZXN1bHQuaW50ZXJmYWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ== -colors.themes = {}; +/***/ }), -var util = __nccwpck_require__(73837); -var ansiStyles = colors.styles = __nccwpck_require__(73104); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); +/***/ 6686: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -colors.supportsColor = (__nccwpck_require__(10662).supportsColor); +"use strict"; -if (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Blamer = void 0; +const git_1 = __nccwpck_require__(38295); +class Blamer { + async blameByFile(path) { + return this.getVCSBlamer()(path); + } + getVCSBlamer() { + return git_1.git; + } } +exports.Blamer = Blamer; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmxhbWVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2JsYW1lci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFDQSxtQ0FBZ0M7QUFFaEMsTUFBYSxNQUFNO0lBQ1YsS0FBSyxDQUFDLFdBQVcsQ0FBQyxJQUFZO1FBQ25DLE9BQU8sSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ25DLENBQUM7SUFFTyxZQUFZO1FBQ2xCLE9BQU8sU0FBRyxDQUFDO0lBQ2IsQ0FBQztDQUNGO0FBUkQsd0JBUUMifQ== -colors.enable = function() { - colors.enabled = true; -}; +/***/ }), -colors.disable = function() { - colors.enabled = false; -}; +/***/ 56781: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); -}; +"use strict"; -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const blamer_1 = __nccwpck_require__(6686); +__exportStar(__nccwpck_require__(21491), exports); +exports["default"] = blamer_1.Blamer; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLHFDQUFrQztBQUVsQywyREFBeUM7QUFDekMsa0JBQWUsZUFBTSxDQUFDIn0= - var styleMap = ansiStyles[style]; +/***/ }), - // Stylize should work for non-ANSI styles, too - if(!styleMap && style in colors){ - // Style maps like trap operate as functions on strings; - // they don't have properties like open or close. - return colors[style](str); - } +/***/ 38295: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return styleMap.open + str + styleMap.close; -}; +"use strict"; -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return str.replace(matchOperatorsRe, '\\$&'); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - -function build(_styles) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - builder._styles = _styles; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - builder.__proto__ = proto; - return builder; -} - -var styles = (function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = - new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.git = void 0; +const execa_1 = __importDefault(__nccwpck_require__(20920)); +const which_1 = __importDefault(__nccwpck_require__(34207)); +const fs_1 = __nccwpck_require__(57147); +const convertStringToObject = (sourceLine) => { + const matches = sourceLine.match(/(.+)\s+\((.+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (\+|\-)\d{4})\s+(\d+)\)(.*)/); + const [, rev, author, date, , line] = matches + ? [...matches] + : [null, '', '', '', '', '']; + return { + author, + date, + line, + rev }; - }); - return ret; -})(); - -var proto = defineProps(function colors() {}, styles); - -function applyStyle() { - var args = Array.prototype.slice.call(arguments); - - var str = args.map(function(arg) { - // Use weak equality check so we can colorize null/undefined in safe mode - if (arg != null && arg.constructor === String) { - return arg; - } else { - return util.inspect(arg); - } - }).join(' '); - - if (!colors.enabled || !str) { - return str; - } - - var newLinesPresent = str.indexOf('\n') != -1; - - var nestedStyles = this._styles; - - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - if (newLinesPresent) { - str = str.replace(newLineRegex, function(match) { - return code.close + match + code.open; - }); +}; +async function git(path) { + const blamedLines = {}; + const pathToGit = await (0, which_1.default)('git'); + if (!(0, fs_1.existsSync)(path)) { + throw new Error(`File ${path} does not exist`); } - } - - return str; -} - -colors.setTheme = function(theme) { - if (typeof theme === 'string') { - console.log('colors.setTheme now only accepts an object, not a string. ' + - 'If you are trying to set a theme from a file, it is now your (the ' + - 'caller\'s) responsibility to require the file. The old syntax ' + - 'looked like colors.setTheme(__dirname + ' + - '\'/../themes/generic-logging.js\'); The new syntax looks like '+ - 'colors.setTheme(require(__dirname + ' + - '\'/../themes/generic-logging.js\'));'); - return; - } - for (var style in theme) { - (function(style) { - colors[style] = function(str) { - if (typeof theme[style] === 'object') { - var out = str; - for (var i in theme[style]) { - out = colors[theme[style][i]](out); - } - return out; + const result = execa_1.default.sync(pathToGit, ['blame', '-w', path]); + result.stdout.split('\n').forEach(line => { + if (line !== '') { + const blamedLine = convertStringToObject(line); + if (blamedLine.line) { + blamedLines[blamedLine.line] = blamedLine; + } } - return colors[theme[style]](str); - }; - })(style); - } -}; - -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, + }); + return { + [path]: blamedLines }; - }); - return ret; } +exports.git = git; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2l0LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3Zjcy9naXQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7O0FBQUEsa0RBQTBCO0FBQzFCLGtEQUEwQjtBQUUxQiwyQkFBZ0M7QUFFaEMsTUFBTSxxQkFBcUIsR0FBRyxDQUFDLFVBQWtCLEVBQWMsRUFBRTtJQUMvRCxNQUFNLE9BQU8sR0FBRyxVQUFVLENBQUMsS0FBSyxDQUM5QixrRkFBa0YsQ0FDbkYsQ0FBQztJQUNGLE1BQU0sQ0FBQyxFQUFFLEdBQUcsRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLEFBQUQsRUFBRyxJQUFJLENBQUMsR0FBRyxPQUFPO1FBQzNDLENBQUMsQ0FBQyxDQUFDLEdBQUcsT0FBTyxDQUFDO1FBQ2QsQ0FBQyxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLENBQUMsQ0FBQztJQUMvQixPQUFPO1FBQ0wsTUFBTTtRQUNOLElBQUk7UUFDSixJQUFJO1FBQ0osR0FBRztLQUNKLENBQUM7QUFDSixDQUFDLENBQUM7QUFFSyxLQUFLLFVBQVUsR0FBRyxDQUFDLElBQVk7SUFDcEMsTUFBTSxXQUFXLEdBQW1DLEVBQUUsQ0FBQztJQUN2RCxNQUFNLFNBQVMsR0FBVyxNQUFNLElBQUEsZUFBSyxFQUFDLEtBQUssQ0FBQyxDQUFDO0lBRTdDLElBQUksQ0FBQyxJQUFBLGVBQVUsRUFBQyxJQUFJLENBQUMsRUFBRTtRQUNyQixNQUFNLElBQUksS0FBSyxDQUFDLFFBQVEsSUFBSSxpQkFBaUIsQ0FBQyxDQUFDO0tBQ2hEO0lBRUQsTUFBTSxNQUFNLEdBQUcsZUFBSyxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsQ0FBQyxPQUFPLEVBQUUsSUFBSSxFQUFFLElBQUksQ0FBQyxDQUFDLENBQUM7SUFDNUQsTUFBTSxDQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ3ZDLElBQUksSUFBSSxLQUFLLEVBQUUsRUFBRTtZQUNmLE1BQU0sVUFBVSxHQUFHLHFCQUFxQixDQUFDLElBQUksQ0FBQyxDQUFDO1lBQy9DLElBQUksVUFBVSxDQUFDLElBQUksRUFBRTtnQkFDbkIsV0FBVyxDQUFDLFVBQVUsQ0FBQyxJQUFJLENBQUMsR0FBRyxVQUFVLENBQUM7YUFDM0M7U0FDRjtJQUNILENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTztRQUNMLENBQUMsSUFBSSxDQUFDLEVBQUUsV0FBVztLQUNwQixDQUFDO0FBQ0osQ0FBQztBQXBCRCxrQkFvQkMifQ== -var sequencer = function sequencer(map, str) { - var exploded = str.split(''); - exploded = exploded.map(map); - return exploded.join(''); -}; - -// custom formatter methods -colors.trap = __nccwpck_require__(31302); -colors.zalgo = __nccwpck_require__(97743); +/***/ }), -// maps -colors.maps = {}; -colors.maps.america = __nccwpck_require__(76936)(colors); -colors.maps.zebra = __nccwpck_require__(12989)(colors); -colors.maps.rainbow = __nccwpck_require__(75210)(colors); -colors.maps.random = __nccwpck_require__(13441)(colors); +/***/ 20920: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); -} +"use strict"; -defineProps(colors, init()); +const path = __nccwpck_require__(71017); +const childProcess = __nccwpck_require__(32081); +const crossSpawn = __nccwpck_require__(72746); +const stripFinalNewline = __nccwpck_require__(88174); +const npmRunPath = __nccwpck_require__(20502); +const onetime = __nccwpck_require__(89082); +const makeError = __nccwpck_require__(11325); +const normalizeStdio = __nccwpck_require__(54149); +const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = __nccwpck_require__(77321); +const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = __nccwpck_require__(2658); +const {mergePromise, getSpawnedPromise} = __nccwpck_require__(51935); +const {joinCommand, parseCommand} = __nccwpck_require__(1099); +const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; -/***/ }), +const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { + const env = extendEnv ? {...process.env, ...envOption} : envOption; -/***/ 31302: -/***/ ((module) => { + if (preferLocal) { + return npmRunPath.env({env, cwd: localDir, execPath}); + } -module['exports'] = function runTheTrap(text, options) { - var result = ''; - text = text || 'Run the trap, drop the bass'; - text = text.split(''); - var trap = { - a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], - b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], - c: ['\u00a9', '\u023b', '\u03fe'], - d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], - e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', - '\u0a6c'], - f: ['\u04fa'], - g: ['\u0262'], - h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], - i: ['\u0f0f'], - j: ['\u0134'], - k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], - l: ['\u0139'], - m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], - n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], - o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', - '\u06dd', '\u0e4f'], - p: ['\u01f7', '\u048e'], - q: ['\u09cd'], - r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], - s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], - t: ['\u0141', '\u0166', '\u0373'], - u: ['\u01b1', '\u054d'], - v: ['\u05d8'], - w: ['\u0428', '\u0460', '\u047c', '\u0d70'], - x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], - y: ['\u00a5', '\u04b0', '\u04cb'], - z: ['\u01b5', '\u0240'], - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [' ']; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== 'undefined') { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; + return env; }; +const handleArguments = (file, args, options = {}) => { + const parsed = crossSpawn._parse(file, args, options); + file = parsed.command; + args = parsed.args; + options = parsed.options; -/***/ }), - -/***/ 97743: -/***/ ((module) => { - -// please no -module['exports'] = function zalgo(text, options) { - text = text || ' he is here '; - var soul = { - 'up': [ - '̍', '̎', '̄', '̅', - '̿', '̑', '̆', '̐', - '͒', '͗', '͑', '̇', - '̈', '̊', '͂', '̓', - '̈', '͊', '͋', '͌', - '̃', '̂', '̌', '͐', - '̀', '́', '̋', '̏', - '̒', '̓', '̔', '̽', - '̉', 'ͣ', 'ͤ', 'ͥ', - 'ͦ', 'ͧ', 'ͨ', 'ͩ', - 'ͪ', 'ͫ', 'ͬ', 'ͭ', - 'ͮ', 'ͯ', '̾', '͛', - '͆', '̚', - ], - 'down': [ - '̖', '̗', '̘', '̙', - '̜', '̝', '̞', '̟', - '̠', '̤', '̥', '̦', - '̩', '̪', '̫', '̬', - '̭', '̮', '̯', '̰', - '̱', '̲', '̳', '̹', - '̺', '̻', '̼', 'ͅ', - '͇', '͈', '͉', '͍', - '͎', '͓', '͔', '͕', - '͖', '͙', '͚', '̣', - ], - 'mid': [ - '̕', '̛', '̀', '́', - '͘', '̡', '̢', '̧', - '̨', '̴', '̵', '̶', - '͜', '͝', '͞', - '͟', '͠', '͢', '̸', - '̷', '͡', ' ҉', - ], - }; - var all = [].concat(soul.up, soul.down, soul.mid); - - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } + options = { + maxBuffer: DEFAULT_MAX_BUFFER, + buffer: true, + stripFinalNewline: true, + extendEnv: true, + preferLocal: false, + localDir: options.cwd || process.cwd(), + execPath: process.execPath, + encoding: 'utf8', + reject: true, + cleanup: true, + all: false, + windowsHide: true, + ...options + }; - function isChar(character) { - var bool = false; - all.filter(function(i) { - bool = (i === character); - }); - return bool; - } + options.env = getEnv(options); + options.stdio = normalizeStdio(options); - function heComes(text, options) { - var result = ''; - var counts; - var l; - options = options || {}; - options['up'] = - typeof options['up'] !== 'undefined' ? options['up'] : true; - options['mid'] = - typeof options['mid'] !== 'undefined' ? options['mid'] : true; - options['down'] = - typeof options['down'] !== 'undefined' ? options['down'] : true; - options['size'] = - typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; - text = text.split(''); - for (l in text) { - if (isChar(l)) { - continue; - } - result = result + text[l]; - counts = {'up': 0, 'down': 0, 'mid': 0}; - switch (options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } + if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { + // #116 + args.unshift('/q'); + } - var arr = ['up', 'mid', 'down']; - for (var d in arr) { - var index = arr[d]; - for (var i = 0; i <= counts[index]; i++) { - if (options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - } - // don't summon him - return heComes(text, options); + return {file, args, options, parsed}; }; +const handleOutput = (options, value, error) => { + if (typeof value !== 'string' && !Buffer.isBuffer(value)) { + // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` + return error === undefined ? undefined : ''; + } + if (options.stripFinalNewline) { + return stripFinalNewline(value); + } -/***/ }), - -/***/ 76936: -/***/ ((module) => { - -module['exports'] = function(colors) { - return function(letter, i, exploded) { - if (letter === ' ') return letter; - switch (i%3) { - case 0: return colors.red(letter); - case 1: return colors.white(letter); - case 2: return colors.blue(letter); - } - }; + return value; }; +const execa = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); -/***/ }), - -/***/ 75210: -/***/ ((module) => { - -module['exports'] = function(colors) { - // RoY G BiV - var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; - return function(letter, i, exploded) { - if (letter === ' ') { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; -}; + let spawned; + try { + spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); + } catch (error) { + // Ensure the returned error is always both a promise and a child process + const dummySpawned = new childProcess.ChildProcess(); + const errorPromise = Promise.reject(makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + parsed, + timedOut: false, + isCanceled: false, + killed: false + })); + return mergePromise(dummySpawned, errorPromise); + } + const spawnedPromise = getSpawnedPromise(spawned); + const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); + const processDone = setExitHandler(spawned, parsed.options, timedPromise); + const context = {isCanceled: false}; -/***/ }), + spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); + spawned.cancel = spawnedCancel.bind(null, spawned, context); -/***/ 13441: -/***/ ((module) => { + const handlePromise = async () => { + const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); + const stdout = handleOutput(parsed.options, stdoutResult); + const stderr = handleOutput(parsed.options, stderrResult); + const all = handleOutput(parsed.options, allResult); -module['exports'] = function(colors) { - var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', - 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', - 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; - return function(letter, i, exploded) { - return letter === ' ' ? letter : - colors[ - available[Math.round(Math.random() * (available.length - 2))] - ](letter); - }; -}; + if (error || exitCode !== 0 || signal !== null) { + const returnedError = makeError({ + error, + exitCode, + signal, + stdout, + stderr, + all, + command, + parsed, + timedOut, + isCanceled: context.isCanceled, + killed: spawned.killed + }); + if (!parsed.options.reject) { + return returnedError; + } -/***/ }), + throw returnedError; + } -/***/ 12989: -/***/ ((module) => { + return { + command, + exitCode: 0, + stdout, + stderr, + all, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; + }; -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; + const handlePromiseOnce = onetime(handlePromise); + crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); -/***/ }), + handleInput(spawned, parsed.options.input); -/***/ 73104: -/***/ ((module) => { + spawned.all = makeAllStream(spawned, parsed.options); -/* -The MIT License (MIT) + return mergePromise(spawned, handlePromiseOnce); +}; -Copyright (c) Sindre Sorhus (sindresorhus.com) +module.exports = execa; -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +module.exports.sync = (file, args, options) => { + const parsed = handleArguments(file, args, options); + const command = joinCommand(file, args); -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + validateInputSync(parsed.options); -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + let result; + try { + result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options); + } catch (error) { + throw makeError({ + error, + stdout: '', + stderr: '', + all: '', + command, + parsed, + timedOut: false, + isCanceled: false, + killed: false + }); + } -*/ + const stdout = handleOutput(parsed.options, result.stdout, result.error); + const stderr = handleOutput(parsed.options, result.stderr, result.error); -var styles = {}; -module['exports'] = styles; - -var codes = { - reset: [0, 0], - - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], - - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], - - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgGray: [100, 49], - bgGrey: [100, 49], - - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], - - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49], - -}; - -Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = '\u001b[' + val[0] + 'm'; - style.close = '\u001b[' + val[1] + 'm'; -}); + if (result.error || result.status !== 0 || result.signal !== null) { + const error = makeError({ + stdout, + stderr, + error: result.error, + signal: result.signal, + exitCode: result.status, + command, + parsed, + timedOut: result.error && result.error.code === 'ETIMEDOUT', + isCanceled: false, + killed: result.signal !== null + }); + if (!parsed.options.reject) { + return error; + } -/***/ }), + throw error; + } -/***/ 10223: -/***/ ((module) => { + return { + command, + exitCode: 0, + stdout, + stderr, + failed: false, + timedOut: false, + isCanceled: false, + killed: false + }; +}; -"use strict"; -/* -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ +module.exports.command = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa(file, args, options); +}; +module.exports.commandSync = (command, options) => { + const [file, ...args] = parseCommand(command); + return execa.sync(file, args, options); +}; +module.exports.node = (scriptPath, args, options = {}) => { + if (args && !Array.isArray(args) && typeof args === 'object') { + options = args; + args = []; + } -module.exports = function(flag, argv) { - argv = argv || process.argv; + const stdio = normalizeStdio.node(options); + const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); + const { + nodePath = process.execPath, + nodeOptions = defaultExecArgv + } = options; - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + return execa( + nodePath, + [ + ...nodeOptions, + scriptPath, + ...(Array.isArray(args) ? args : []) + ], + { + ...options, + stdin: undefined, + stdout: undefined, + stderr: undefined, + stdio, + shell: false + } + ); }; /***/ }), -/***/ 10662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1099: +/***/ ((module) => { "use strict"; -/* -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ +const SPACES_REGEXP = / +/g; +const joinCommand = (file, args = []) => { + if (!Array.isArray(args)) { + return file; + } -var os = __nccwpck_require__(22037); -var hasFlag = __nccwpck_require__(10223); + return [file, ...args].join(' '); +}; -var env = process.env; +// Handle `execa.command()` +const parseCommand = command => { + const tokens = []; + for (const token of command.trim().split(SPACES_REGEXP)) { + // Allow spaces to be escaped by a backslash if not meant as a delimiter + const previousToken = tokens[tokens.length - 1]; + if (previousToken && previousToken.endsWith('\\')) { + // Merge previous token with current one + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } -var forceColor = void 0; -if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') - || hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 - || parseInt(env.FORCE_COLOR, 10) !== 0; -} + return tokens; +}; -function translateLevel(level) { - if (level === 0) { - return false; - } +module.exports = { + joinCommand, + parseCommand +}; - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; -} -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } +/***/ }), - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } +/***/ 11325: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (hasFlag('color=256')) { - return 2; - } +"use strict"; - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } +const {signalsByName} = __nccwpck_require__(27605); - var min = forceColor ? 1 : 0; +const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { + if (timedOut) { + return `timed out after ${timeout} milliseconds`; + } - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first - // Windows release that supports 256 colors. Windows 10 build 14931 is the - // first release that supports 16m/TrueColor. - var osRelease = os.release().split('.'); - if (Number(process.versions.node.split('.')[0]) >= 8 - && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + if (isCanceled) { + return 'was canceled'; + } - return 1; - } + if (errorCode !== undefined) { + return `failed with ${errorCode}`; + } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } + if (signal !== undefined) { + return `was killed with ${signal} (${signalDescription})`; + } - return min; - } + if (exitCode !== undefined) { + return `failed with exit code ${exitCode}`; + } - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); - } + return 'failed'; +}; - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +const makeError = ({ + stdout, + stderr, + all, + error, + signal, + exitCode, + command, + timedOut, + isCanceled, + killed, + parsed: {options: {timeout}} +}) => { + // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. + // We normalize them to `undefined` + exitCode = exitCode === null ? undefined : exitCode; + signal = signal === null ? undefined : signal; + const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } + const errorCode = error && error.code; - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); + const execaMessage = `Command ${prefix}: ${command}`; + const isError = Object.prototype.toString.call(error) === '[object Error]'; + const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; + const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + if (isError) { + error.originalMessage = error.message; + error.message = message; + } else { + error = new Error(message); + } - if ('COLORTERM' in env) { - return 1; - } + error.shortMessage = shortMessage; + error.command = command; + error.exitCode = exitCode; + error.signal = signal; + error.signalDescription = signalDescription; + error.stdout = stdout; + error.stderr = stderr; - if (env.TERM === 'dumb') { - return min; - } + if (all !== undefined) { + error.all = all; + } - return min; -} + if ('bufferedData' in error) { + delete error.bufferedData; + } -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); -} + error.failed = true; + error.timedOut = Boolean(timedOut); + error.isCanceled = isCanceled; + error.killed = killed && !timedOut; -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), + return error; }; +module.exports = makeError; + /***/ }), -/***/ 41997: +/***/ 77321: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -// Remark: Requiring this file will use the "safe" colors API, -// which will not touch String.prototype. -// -// var colors = require('colors/safe'); -// colors.red("foo") -// -// -var colors = __nccwpck_require__(43595); -module['exports'] = colors; - +"use strict"; -/***/ }), +const os = __nccwpck_require__(22037); +const onExit = __nccwpck_require__(24931); -/***/ 92240: -/***/ ((module) => { +const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var ArchiveEntry = module.exports = function() {}; +// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior +const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +}; -ArchiveEntry.prototype.getName = function() {}; +const setKillTimeout = (kill, signal, options, killResult) => { + if (!shouldForceKill(signal, options, killResult)) { + return; + } -ArchiveEntry.prototype.getSize = function() {}; + const timeout = getForceKillAfterTimeout(options); + const t = setTimeout(() => { + kill('SIGKILL'); + }, timeout); -ArchiveEntry.prototype.getLastModifiedDate = function() {}; + // Guarded because there's no `.unref()` when `execa` is used in the renderer + // process in Electron. This cannot be tested since we don't run tests in + // Electron. + // istanbul ignore else + if (t.unref) { + t.unref(); + } +}; -ArchiveEntry.prototype.isDirectory = function() {}; +const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { + return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; +}; -/***/ }), +const isSigterm = signal => { + return signal === os.constants.signals.SIGTERM || + (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); +}; -/***/ 36728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { + if (forceKillAfterTimeout === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var isStream = __nccwpck_require__(41554); -var Transform = (__nccwpck_require__(45193).Transform); + if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { + throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); + } -var ArchiveEntry = __nccwpck_require__(92240); -var util = __nccwpck_require__(95208); + return forceKillAfterTimeout; +}; -var ArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ArchiveOutputStream)) { - return new ArchiveOutputStream(options); - } +// `childProcess.cancel()` +const spawnedCancel = (spawned, context) => { + const killResult = spawned.kill(); - Transform.call(this, options); + if (killResult) { + context.isCanceled = true; + } +}; - this.offset = 0; - this._archive = { - finish: false, - finished: false, - processing: false - }; +const timeoutKill = (spawned, signal, reject) => { + spawned.kill(signal); + reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); }; -inherits(ArchiveOutputStream, Transform); +// `timeout` option handling +const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { + if (timeout === 0 || timeout === undefined) { + return spawnedPromise; + } -ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { - // scaffold only -}; + if (!Number.isFinite(timeout) || timeout < 0) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } -ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { - // scaffold only -}; + let timeoutId; + const timeoutPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + timeoutKill(spawned, killSignal, reject); + }, timeout); + }); -ArchiveOutputStream.prototype._emitErrorCallback = function(err) { - if (err) { - this.emit('error', err); - } -}; + const safeSpawnedPromise = spawnedPromise.finally(() => { + clearTimeout(timeoutId); + }); -ArchiveOutputStream.prototype._finish = function(ae) { - // scaffold only + return Promise.race([timeoutPromise, safeSpawnedPromise]); }; -ArchiveOutputStream.prototype._normalizeEntry = function(ae) { - // scaffold only +// `cleanup` option handling +const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { + if (!cleanup || detached) { + return timedPromise; + } + + const removeExitHandler = onExit(() => { + spawned.kill(); + }); + + return timedPromise.finally(() => { + removeExitHandler(); + }); }; -ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { - callback(null, chunk); +module.exports = { + spawnedKill, + spawnedCancel, + setupTimeout, + setExitHandler }; -ArchiveOutputStream.prototype.entry = function(ae, source, callback) { - source = source || null; - if (typeof callback !== 'function') { - callback = this._emitErrorCallback.bind(this); - } +/***/ }), - if (!(ae instanceof ArchiveEntry)) { - callback(new Error('not a valid instance of ArchiveEntry')); - return; - } +/***/ 51935: +/***/ ((module) => { - if (this._archive.finish || this._archive.finished) { - callback(new Error('unacceptable entry after finish')); - return; - } +"use strict"; - if (this._archive.processing) { - callback(new Error('already processing an entry')); - return; - } - this._archive.processing = true; - this._normalizeEntry(ae); - this._entry = ae; +const nativePromisePrototype = (async () => {})().constructor.prototype; +const descriptors = ['then', 'catch', 'finally'].map(property => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) +]); - source = util.normalizeInputSource(source); +// The return value is a mixin of `childProcess` and `Promise` +const mergePromise = (spawned, promise) => { + for (const [property, descriptor] of descriptors) { + // Starting the main `promise` is deferred to avoid consuming streams + const value = typeof promise === 'function' ? + (...args) => Reflect.apply(descriptor.value, promise(), args) : + descriptor.value.bind(promise); - if (Buffer.isBuffer(source)) { - this._appendBuffer(ae, source, callback); - } else if (isStream(source)) { - this._appendStream(ae, source, callback); - } else { - this._archive.processing = false; - callback(new Error('input source must be valid Stream or Buffer instance')); - return; - } + Reflect.defineProperty(spawned, property, {...descriptor, value}); + } - return this; + return spawned; }; -ArchiveOutputStream.prototype.finish = function() { - if (this._archive.processing) { - this._archive.finish = true; - return; - } +// Use promises instead of `child_process` events +const getSpawnedPromise = spawned => { + return new Promise((resolve, reject) => { + spawned.on('exit', (exitCode, signal) => { + resolve({exitCode, signal}); + }); - this._finish(); + spawned.on('error', error => { + reject(error); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', error => { + reject(error); + }); + } + }); }; -ArchiveOutputStream.prototype.getBytesWritten = function() { - return this.offset; +module.exports = { + mergePromise, + getSpawnedPromise }; -ArchiveOutputStream.prototype.write = function(chunk, cb) { - if (chunk) { - this.offset += chunk.length; - } - return Transform.prototype.write.call(this, chunk, cb); -}; /***/ }), -/***/ 11704: +/***/ 54149: /***/ ((module) => { -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - WORD: 4, - DWORD: 8, - EMPTY: Buffer.alloc(0), +"use strict"; - SHORT: 2, - SHORT_MASK: 0xffff, - SHORT_SHIFT: 16, - SHORT_ZERO: Buffer.from(Array(2)), - LONG: 4, - LONG_ZERO: Buffer.from(Array(4)), +const aliases = ['stdin', 'stdout', 'stderr']; - MIN_VERSION_INITIAL: 10, - MIN_VERSION_DATA_DESCRIPTOR: 20, - MIN_VERSION_ZIP64: 45, - VERSION_MADEBY: 45, +const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined); - METHOD_STORED: 0, - METHOD_DEFLATED: 8, +const normalizeStdio = opts => { + if (!opts) { + return; + } - PLATFORM_UNIX: 3, - PLATFORM_FAT: 0, + const {stdio} = opts; - SIG_LFH: 0x04034b50, - SIG_DD: 0x08074b50, - SIG_CFH: 0x02014b50, - SIG_EOCD: 0x06054b50, - SIG_ZIP64_EOCD: 0x06064B50, - SIG_ZIP64_EOCD_LOC: 0x07064B50, + if (stdio === undefined) { + return aliases.map(alias => opts[alias]); + } - ZIP64_MAGIC_SHORT: 0xffff, - ZIP64_MAGIC: 0xffffffff, - ZIP64_EXTRA_ID: 0x0001, + if (hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); + } - ZLIB_NO_COMPRESSION: 0, - ZLIB_BEST_SPEED: 1, - ZLIB_BEST_COMPRESSION: 9, - ZLIB_DEFAULT_COMPRESSION: -1, + if (typeof stdio === 'string') { + return stdio; + } - MODE_MASK: 0xFFF, - DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH - DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } - EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) - EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 + const length = Math.max(stdio.length, aliases.length); + return Array.from({length}, (value, index) => stdio[index]); +}; - // Unix file types - S_IFMT: 61440, // 0170000 type of file mask - S_IFIFO: 4096, // 010000 named pipe (fifo) - S_IFCHR: 8192, // 020000 character special - S_IFDIR: 16384, // 040000 directory - S_IFBLK: 24576, // 060000 block special - S_IFREG: 32768, // 0100000 regular - S_IFLNK: 40960, // 0120000 symbolic link - S_IFSOCK: 49152, // 0140000 socket +module.exports = normalizeStdio; - // DOS file type flags - S_DOS_A: 32, // 040 Archive - S_DOS_D: 16, // 020 Directory - S_DOS_V: 8, // 010 Volume - S_DOS_S: 4, // 04 System - S_DOS_H: 2, // 02 Hidden - S_DOS_R: 1 // 01 Read Only +// `ipc` is pushed unless it is already present +module.exports.node = opts => { + const stdio = normalizeStdio(opts); + + if (stdio === 'ipc') { + return 'ipc'; + } + + if (stdio === undefined || typeof stdio === 'string') { + return [stdio, stdio, stdio, 'ipc']; + } + + if (stdio.includes('ipc')) { + return stdio; + } + + return [...stdio, 'ipc']; }; /***/ }), -/***/ 63229: +/***/ 2658: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var zipUtil = __nccwpck_require__(68682); - -var DATA_DESCRIPTOR_FLAG = 1 << 3; -var ENCRYPTION_FLAG = 1 << 0; -var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; -var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; -var STRONG_ENCRYPTION_FLAG = 1 << 6; -var UFT8_NAMES_FLAG = 1 << 11; - -var GeneralPurposeBit = module.exports = function() { - if (!(this instanceof GeneralPurposeBit)) { - return new GeneralPurposeBit(); - } +"use strict"; - this.descriptor = false; - this.encryption = false; - this.utf8 = false; - this.numberOfShannonFanoTrees = 0; - this.strongEncryption = false; - this.slidingDictionarySize = 0; +const isStream = __nccwpck_require__(41554); +const getStream = __nccwpck_require__(80591); +const mergeStream = __nccwpck_require__(2621); - return this; -}; +// `input` option +const handleInput = (spawned, input) => { + // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 + // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 + if (input === undefined || spawned.stdin === undefined) { + return; + } -GeneralPurposeBit.prototype.encode = function() { - return zipUtil.getShortBytes( - (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | - (this.utf8 ? UFT8_NAMES_FLAG : 0) | - (this.encryption ? ENCRYPTION_FLAG : 0) | - (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) - ); + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } }; -GeneralPurposeBit.prototype.parse = function(buf, offset) { - var flag = zipUtil.getShortBytesValue(buf, offset); - var gbp = new GeneralPurposeBit(); +// `all` interleaves `stdout` and `stderr` +const makeAllStream = (spawned, {all}) => { + if (!all || (!spawned.stdout && !spawned.stderr)) { + return; + } - gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); - gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); - gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); - gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); - gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); - gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); + const mixed = mergeStream(); - return gbp; -}; + if (spawned.stdout) { + mixed.add(spawned.stdout); + } -GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { - this.numberOfShannonFanoTrees = n; -}; + if (spawned.stderr) { + mixed.add(spawned.stderr); + } -GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { - return this.numberOfShannonFanoTrees; + return mixed; }; -GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { - this.slidingDictionarySize = n; -}; +// On failure, `result.stdout|stderr|all` should contain the currently buffered stream +const getBufferedData = async (stream, streamPromise) => { + if (!stream) { + return; + } -GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { - return this.slidingDictionarySize; -}; + stream.destroy(); -GeneralPurposeBit.prototype.useDataDescriptor = function(b) { - this.descriptor = b; + try { + return await streamPromise; + } catch (error) { + return error.bufferedData; + } }; -GeneralPurposeBit.prototype.usesDataDescriptor = function() { - return this.descriptor; -}; +const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { + if (!stream || !buffer) { + return; + } -GeneralPurposeBit.prototype.useEncryption = function(b) { - this.encryption = b; -}; + if (encoding) { + return getStream(stream, {encoding, maxBuffer}); + } -GeneralPurposeBit.prototype.usesEncryption = function() { - return this.encryption; + return getStream.buffer(stream, {maxBuffer}); }; -GeneralPurposeBit.prototype.useStrongEncryption = function(b) { - this.strongEncryption = b; -}; +// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) +const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { + const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); + const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); + const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); -GeneralPurposeBit.prototype.usesStrongEncryption = function() { - return this.strongEncryption; + try { + return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); + } catch (error) { + return Promise.all([ + {error, signal: error.signal, timedOut: error.timedOut}, + getBufferedData(stdout, stdoutPromise), + getBufferedData(stderr, stderrPromise), + getBufferedData(all, allPromise) + ]); + } }; -GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { - this.utf8 = b; +const validateInputSync = ({input}) => { + if (isStream(input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } }; -GeneralPurposeBit.prototype.usesUTF8ForNames = function() { - return this.utf8; +module.exports = { + handleInput, + makeAllStream, + getSpawnedResult, + validateInputSync }; -/***/ }), - -/***/ 70713: -/***/ ((module) => { - -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - /** - * Bits used for permissions (and sticky bit) - */ - PERM_MASK: 4095, // 07777 - /** - * Bits used to indicate the filesystem object type. - */ - FILE_TYPE_FLAG: 61440, // 0170000 - /** - * Indicates symbolic links. - */ - LINK_FLAG: 40960, // 0120000 +/***/ }), - /** - * Indicates plain files. - */ - FILE_FLAG: 32768, // 0100000 +/***/ 33059: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Indicates directories. - */ - DIR_FLAG: 16384, // 040000 +"use strict"; - // ---------------------------------------------------------- - // somewhat arbitrary choices that are quite common for shared - // installations - // ----------------------------------------------------------- +const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); - /** - * Default permissions for symbolic links. - */ - DEFAULT_LINK_PERM: 511, // 0777 +module.exports = options => { + options = {...options}; - /** - * Default permissions for directories. - */ - DEFAULT_DIR_PERM: 493, // 0755 + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; - /** - * Default permissions for plain files. - */ - DEFAULT_FILE_PERM: 420 // 0644 -}; + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } -/***/ }), + if (isBuffer) { + encoding = null; + } -/***/ 68682: -/***/ ((module) => { + const stream = new PassThroughStream({objectMode}); -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var util = module.exports = {}; + if (encoding) { + stream.setEncoding(encoding); + } -util.dateToDos = function(d, forceLocalTime) { - forceLocalTime = forceLocalTime || false; + let length = 0; + const chunks = []; - var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); + stream.on('data', chunk => { + chunks.push(chunk); - if (year < 1980) { - return 2162688; // 1980-1-1 00:00:00 - } else if (year >= 2044) { - return 2141175677; // 2043-12-31 23:59:58 - } + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); - var val = { - year: year, - month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), - date: forceLocalTime ? d.getDate() : d.getUTCDate(), - hours: forceLocalTime ? d.getHours() : d.getUTCHours(), - minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), - seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() - }; + stream.getBufferedValue = () => { + if (array) { + return chunks; + } - return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | - (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); -}; + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; -util.dosToDate = function(dos) { - return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); -}; + stream.getBufferedLength = () => length; -util.fromDosTime = function(buf) { - return util.dosToDate(buf.readUInt32LE(0)); + return stream; }; -util.getEightBytes = function(v) { - var buf = Buffer.alloc(8); - buf.writeUInt32LE(v % 0x0100000000, 0); - buf.writeUInt32LE((v / 0x0100000000) | 0, 4); - return buf; -}; +/***/ }), -util.getShortBytes = function(v) { - var buf = Buffer.alloc(2); - buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); +/***/ 80591: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return buf; -}; +"use strict"; -util.getShortBytesValue = function(buf, offset) { - return buf.readUInt16LE(offset); -}; +const {constants: BufferConstants} = __nccwpck_require__(14300); +const pump = __nccwpck_require__(18341); +const bufferStream = __nccwpck_require__(33059); -util.getLongBytes = function(v) { - var buf = Buffer.alloc(4); - buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} - return buf; -}; +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } -util.getLongBytesValue = function(buf, offset) { - return buf.readUInt32LE(offset); -}; + options = { + maxBuffer: Infinity, + ...options + }; -util.toDosTime = function(d) { - return util.getLongBytes(util.dateToDos(d)); -}; + const {maxBuffer} = options; -/***/ }), + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } -/***/ 3179: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + reject(error); + }; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var normalizePath = __nccwpck_require__(55388); + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } -var ArchiveEntry = __nccwpck_require__(92240); -var GeneralPurposeBit = __nccwpck_require__(63229); -var UnixStat = __nccwpck_require__(70713); + resolve(); + }); -var constants = __nccwpck_require__(11704); -var zipUtil = __nccwpck_require__(68682); + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); -var ZipArchiveEntry = module.exports = function(name) { - if (!(this instanceof ZipArchiveEntry)) { - return new ZipArchiveEntry(name); - } + return stream.getBufferedValue(); +} - ArchiveEntry.call(this); +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports["default"] = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; - this.platform = constants.PLATFORM_FAT; - this.method = -1; - this.name = null; - this.size = 0; - this.csize = 0; - this.gpb = new GeneralPurposeBit(); - this.crc = 0; - this.time = -1; +/***/ }), - this.minver = constants.MIN_VERSION_INITIAL; - this.mode = -1; - this.extra = null; - this.exattr = 0; - this.inattr = 0; - this.comment = null; +/***/ 29778: +/***/ ((__unused_webpack_module, exports) => { - if (name) { - this.setName(name); - } -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0; -inherits(ZipArchiveEntry, ArchiveEntry); +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { - return this.getExtra(); -}; +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, -/** - * Returns the comment set for the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getComment = function() { - return this.comment !== null ? this.comment : ''; -}; +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, -/** - * Returns the compressed size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCompressedSize = function() { - return this.csize; -}; +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, -/** - * Returns the CRC32 digest for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCrc = function() { - return this.crc; -}; +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, -/** - * Returns the external file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getExternalAttributes = function() { - return this.exattr; -}; +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getExtra = function() { - return this.extra !== null ? this.extra : constants.EMPTY; -}; +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, -/** - * Returns the general purpose bits related to the entry. - * - * @returns {GeneralPurposeBit} - */ -ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { - return this.gpb; -}; +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, -/** - * Returns the internal file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getInternalAttributes = function() { - return this.inattr; -}; +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, -/** - * Returns the last modified date of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getLastModifiedDate = function() { - return this.getTime(); -}; +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { - return this.getExtra(); -}; +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, -/** - * Returns the compression method used on the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getMethod = function() { - return this.method; -}; +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, -/** - * Returns the filename of the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getName = function() { - return this.name; -}; +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, -/** - * Returns the platform on which the entry was made. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getPlatform = function() { - return this.platform; -}; +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, -/** - * Returns the size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getSize = function() { - return this.size; -}; +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, -/** - * Returns a date object representing the last modified date of the entry. - * - * @returns {number|Date} - */ -ZipArchiveEntry.prototype.getTime = function() { - return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; -}; +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, -/** - * Returns the DOS timestamp for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getTimeDos = function() { - return this.time !== -1 ? this.time : 0; -}; +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, -/** - * Returns the UNIX file permissions for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getUnixMode = function() { - return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); -}; +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, -/** - * Returns the version of ZIP needed to extract the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { - return this.minver; -}; +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, -/** - * Sets the comment of the entry. - * - * @param comment - */ -ZipArchiveEntry.prototype.setComment = function(comment) { - if (Buffer.byteLength(comment) !== comment.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); - } +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, - this.comment = comment; -}; +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, -/** - * Sets the compressed size of the entry. - * - * @param size - */ -ZipArchiveEntry.prototype.setCompressedSize = function(size) { - if (size < 0) { - throw new Error('invalid entry compressed size'); - } +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, - this.csize = size; -}; +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, -/** - * Sets the checksum of the entry. - * - * @param crc - */ -ZipArchiveEntry.prototype.setCrc = function(crc) { - if (crc < 0) { - throw new Error('invalid entry crc32'); - } +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, - this.crc = crc; -}; +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, -/** - * Sets the external file attributes of the entry. - * - * @param attr - */ -ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { - this.exattr = attr >>> 0; -}; +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, -/** - * Sets the extra fields related to the entry. - * - * @param extra - */ -ZipArchiveEntry.prototype.setExtra = function(extra) { - this.extra = extra; -}; +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, -/** - * Sets the general purpose bits related to the entry. - * - * @param gpb - */ -ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { - if (!(gpb instanceof GeneralPurposeBit)) { - throw new Error('invalid entry GeneralPurposeBit'); - } +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, - this.gpb = gpb; -}; +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, -/** - * Sets the internal file attributes of the entry. - * - * @param attr - */ -ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { - this.inattr = attr; -}; +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, -/** - * Sets the compression method of the entry. - * - * @param method - */ -ZipArchiveEntry.prototype.setMethod = function(method) { - if (method < 0) { - throw new Error('invalid entry compression method'); - } +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, - this.method = method; -}; +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, -/** - * Sets the name of the entry. - * - * @param name - * @param prependSlash - */ -ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { - name = normalizePath(name, false) - .replace(/^\w+:/, '') - .replace(/^(\.\.\/|\/)+/, ''); +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, - if (prependSlash) { - name = `/${name}`; - } +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, - if (Buffer.byteLength(name) !== name.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); - } +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, - this.name = name; -}; +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, -/** - * Sets the platform on which the entry was made. - * - * @param platform - */ -ZipArchiveEntry.prototype.setPlatform = function(platform) { - this.platform = platform; -}; +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, -/** - * Sets the size of the entry. - * - * @param size - */ -ZipArchiveEntry.prototype.setSize = function(size) { - if (size < 0) { - throw new Error('invalid entry size'); - } +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];exports.SIGNALS=SIGNALS; +//# sourceMappingURL=core.js.map - this.size = size; -}; +/***/ }), -/** - * Sets the time of the entry. - * - * @param time - * @param forceLocalTime - */ -ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { - if (!(time instanceof Date)) { - throw new Error('invalid entry time'); - } +/***/ 27605: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.time = zipUtil.dateToDos(time, forceLocalTime); -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037); -/** - * Sets the UNIX file permissions for the entry. - * - * @param mode - */ -ZipArchiveEntry.prototype.setUnixMode = function(mode) { - mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; +var _signals=__nccwpck_require__(59519); +var _realtime=__nccwpck_require__(45904); - var extattr = 0; - extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); - this.setExternalAttributes(extattr); - this.mode = mode & constants.MODE_MASK; - this.platform = constants.PLATFORM_UNIX; -}; -/** - * Sets the version of ZIP needed to extract this entry. - * - * @param minver - */ -ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { - this.minver = minver; +const getSignalsByName=function(){ +const signals=(0,_signals.getSignals)(); +return signals.reduce(getSignalByName,{}); }; -/** - * Returns true if this entry represents a directory. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isDirectory = function() { - return this.getName().slice(-1) === '/'; -}; +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return{ +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; -/** - * Returns true if this entry represents a unix symlink, - * in which case the entry's content contains the target path - * for the symlink. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isUnixSymlink = function() { - return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; }; -/** - * Returns true if this entry is using the ZIP64 extension of ZIP. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isZip64 = function() { - return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; -}; +const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; -/***/ }), -/***/ 44432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var crc32 = __nccwpck_require__(83201); -var {CRC32Stream} = __nccwpck_require__(5101); -var {DeflateCRC32Stream} = __nccwpck_require__(5101); +const getSignalsByNumber=function(){ +const signals=(0,_signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); -var ArchiveOutputStream = __nccwpck_require__(36728); -var ZipArchiveEntry = __nccwpck_require__(3179); -var GeneralPurposeBit = __nccwpck_require__(63229); +return Object.assign({},...signalsA); +}; -var constants = __nccwpck_require__(11704); -var util = __nccwpck_require__(95208); -var zipUtil = __nccwpck_require__(68682); +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); -var ZipArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ZipArchiveOutputStream)) { - return new ZipArchiveOutputStream(options); - } +if(signal===undefined){ +return{}; +} - options = this.options = this._defaults(options); +const{name,description,supported,action,forced,standard}=signal; +return{ +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; - ArchiveOutputStream.call(this, options); - this._entry = null; - this._entries = []; - this._archive = { - centralLength: 0, - centralOffset: 0, - comment: '', - finish: false, - finished: false, - processing: false, - forceZip64: options.forceZip64, - forceLocalTime: options.forceLocalTime - }; }; -inherits(ZipArchiveOutputStream, ArchiveOutputStream); -ZipArchiveOutputStream.prototype._afterAppend = function(ae) { - this._entries.push(ae); - if (ae.getGeneralPurposeBit().usesDataDescriptor()) { - this._writeDataDescriptor(ae); - } +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); - this._archive.processing = false; - this._entry = null; +if(signal!==undefined){ +return signal; +} - if (this._archive.finish && !this._archive.finished) { - this._finish(); - } +return signals.find(signalA=>signalA.number===number); }; -ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { - if (source.length === 0) { - ae.setMethod(constants.METHOD_STORED); - } +const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; +//# sourceMappingURL=main.js.map - var method = ae.getMethod(); +/***/ }), - if (method === constants.METHOD_STORED) { - ae.setSize(source.length); - ae.setCompressedSize(source.length); - ae.setCrc(crc32.buf(source) >>> 0); - } +/***/ 45904: +/***/ ((__unused_webpack_module, exports) => { - this._writeLocalFileHeader(ae); +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};exports.getRealtimeSignals=getRealtimeSignals; + +const getRealtimeSignal=function(value,index){ +return{ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; - if (method === constants.METHOD_STORED) { - this.write(source); - this._afterAppend(ae); - callback(null, ae); - return; - } else if (method === constants.METHOD_DEFLATED) { - this._smartStream(ae, callback).end(source); - return; - } else { - callback(new Error('compression method ' + method + ' not implemented')); - return; - } }; -ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); +const SIGRTMIN=34; +const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; +//# sourceMappingURL=realtime.js.map - this._writeLocalFileHeader(ae); +/***/ }), - var smart = this._smartStream(ae, callback); - source.once('error', function(err) { - smart.emit('error', err); - smart.end(); - }) - source.pipe(smart); -}; +/***/ 59519: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -ZipArchiveOutputStream.prototype._defaults = function(o) { - if (typeof o !== 'object') { - o = {}; - } +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037); - if (typeof o.zlib !== 'object') { - o.zlib = {}; - } +var _core=__nccwpck_require__(29778); +var _realtime=__nccwpck_require__(45904); - if (typeof o.zlib.level !== 'number') { - o.zlib.level = constants.ZLIB_BEST_SPEED; - } - o.forceZip64 = !!o.forceZip64; - o.forceLocalTime = !!o.forceLocalTime; - return o; -}; +const getSignals=function(){ +const realtimeSignals=(0,_realtime.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};exports.getSignals=getSignals; -ZipArchiveOutputStream.prototype._finish = function() { - this._archive.centralOffset = this.offset; - this._entries.forEach(function(ae) { - this._writeCentralFileHeader(ae); - }.bind(this)); - this._archive.centralLength = this.offset - this._archive.centralOffset; - if (this.isZip64()) { - this._writeCentralDirectoryZip64(); - } - this._writeCentralDirectoryEnd(); - this._archive.processing = false; - this._archive.finish = true; - this._archive.finished = true; - this.end(); + +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return{name,number,description,supported,action,forced,standard}; }; +//# sourceMappingURL=signals.js.map -ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { - if (ae.getMethod() === -1) { - ae.setMethod(constants.METHOD_DEFLATED); - } +/***/ }), - if (ae.getMethod() === constants.METHOD_DEFLATED) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); - } +/***/ 11174: +/***/ (function(module) { - if (ae.getTime() === -1) { - ae.setTime(new Date(), this._archive.forceLocalTime); - } +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; - ae._offsets = { - file: 0, - data: 0, - contents: 0, - }; -}; + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { - var deflate = ae.getMethod() === constants.METHOD_DEFLATED; - var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); - var error = null; + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } - function handleStuff() { - var digest = process.digest().readUInt32BE(0); - ae.setCrc(digest); - ae.setSize(process.size()); - ae.setCompressedSize(process.size(true)); - this._afterAppend(ae); - callback(error, ae); - } + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; - process.once('end', handleStuff.bind(this)); - process.once('error', function(err) { - error = err; - }); + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; - process.pipe(this, { end: false }); + var parser = { + load: load, + overwrite: overwrite + }; - return process; -}; + var DLList; -ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { - var records = this._entries.length; - var size = this._archive.centralLength; - var offset = this._archive.centralOffset; + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } - if (this.isZip64()) { - records = constants.ZIP64_MAGIC_SHORT; - size = constants.ZIP64_MAGIC; - offset = constants.ZIP64_MAGIC; - } + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } - // signature - this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } - // disk numbers - this.write(constants.SHORT_ZERO); - this.write(constants.SHORT_ZERO); + first() { + if (this._first != null) { + return this._first.value; + } + } - // number of entries - this.write(zipUtil.getShortBytes(records)); - this.write(zipUtil.getShortBytes(records)); + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - // length and location of CD - this.write(zipUtil.getLongBytes(size)); - this.write(zipUtil.getLongBytes(offset)); + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - // archive comment - var comment = this.getComment(); - var commentLength = Buffer.byteLength(comment); - this.write(zipUtil.getShortBytes(commentLength)); - this.write(comment); -}; + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } -ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); + }; - // size of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(44)); + var DLList_1 = DLList; - // version made by - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); + var Events; - // version to extract - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - // disk numbers - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } - // number of entries - this.write(zipUtil.getEightBytes(this._entries.length)); - this.write(zipUtil.getEightBytes(this._entries.length)); + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } - // length and location of CD - this.write(zipUtil.getEightBytes(this._archive.centralLength)); - this.write(zipUtil.getEightBytes(this._archive.centralOffset)); + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } - // extensible data sector - // not implemented at this time + }; - // end of central directory locator - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); + var Events_1 = Events; - // disk number holding the ZIP64 EOCD record - this.write(constants.LONG_ZERO); + var DLList$1, Events$1, Queues; - // relative offset of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); + DLList$1 = DLList_1; - // total number of disks - this.write(zipUtil.getLongBytes(1)); -}; + Events$1 = Events_1; + + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } -ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var fileOffset = ae._offsets.file; + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } - var size = ae.getSize(); - var compressedSize = ae.getCompressedSize(); + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) { - size = constants.ZIP64_MAGIC; - compressedSize = constants.ZIP64_MAGIC; - fileOffset = constants.ZIP64_MAGIC; + push(job) { + return this._lists[job.options.priority].push(job); + } - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } - var extraBuf = Buffer.concat([ - zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), - zipUtil.getShortBytes(24), - zipUtil.getEightBytes(ae.getSize()), - zipUtil.getEightBytes(ae.getCompressedSize()), - zipUtil.getEightBytes(ae._offsets.file) - ], 28); + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } - ae.setExtra(extraBuf); - } + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } - // signature - this.write(zipUtil.getLongBytes(constants.SIG_CFH)); + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - // version made by - this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); + }; - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); + var Queues_1 = Queues; - // compression method - this.write(zipUtil.getShortBytes(method)); + var BottleneckError; - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); + BottleneckError = class BottleneckError extends Error {}; - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); + var BottleneckError_1 = BottleneckError; - // sizes - this.write(zipUtil.getLongBytes(compressedSize)); - this.write(zipUtil.getLongBytes(size)); + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - var name = ae.getName(); - var comment = ae.getComment(); - var extra = ae.getCentralDirectoryExtra(); + NUM_PRIORITIES = 10; - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); - comment = Buffer.from(comment); - } + DEFAULT_PRIORITY = 5; - // name length - this.write(zipUtil.getShortBytes(name.length)); + parser$1 = parser; - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + BottleneckError$1 = BottleneckError_1; - // comments length - this.write(zipUtil.getShortBytes(comment.length)); + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } - // disk number start - this.write(constants.SHORT_ZERO); + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - // internal attributes - this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - // external attributes - this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } - // relative offset of LFH - this.write(zipUtil.getLongBytes(fileOffset)); + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } - // name - this.write(name); + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } - // extra - this.write(extra); + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } - // comment - this.write(comment); -}; + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } -ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_DD)); + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } - // sizes - if (ae.isZip64()) { - this.write(zipUtil.getEightBytes(ae.getCompressedSize())); - this.write(zipUtil.getEightBytes(ae.getSize())); - } else { - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); - } -}; + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } -ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var name = ae.getName(); - var extra = ae.getLocalFileDataExtra(); + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } - if (ae.isZip64()) { - gpb.useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); - } + }; - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); - } + var Job_1 = Job; - ae._offsets.file = this.offset; + var BottleneckError$2, LocalDatastore, parser$2; - // signature - this.write(zipUtil.getLongBytes(constants.SIG_LFH)); + parser$2 = parser; - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); + BottleneckError$2 = BottleneckError_1; - // compression method - this.write(zipUtil.getShortBytes(method)); + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } - ae._offsets.data = this.offset; + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } - // crc32 checksum and sizes - if (gpb.usesDataDescriptor()) { - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - } else { - this.write(zipUtil.getLongBytes(ae.getCrc())); - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); - } + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } - // name length - this.write(zipUtil.getShortBytes(name.length)); + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } - // name - this.write(name); + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } - // extra - this.write(extra); + async __running__() { + await this.yieldLoop(); + return this._running; + } - ae._offsets.contents = this.offset; -}; + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -ZipArchiveOutputStream.prototype.getComment = function(comment) { - return this._archive.comment !== null ? this._archive.comment : ''; -}; + async __done__() { + await this.yieldLoop(); + return this._done; + } -ZipArchiveOutputStream.prototype.isZip64 = function() { - return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; -}; + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } -ZipArchiveOutputStream.prototype.setComment = function(comment) { - this._archive.comment = comment; -}; + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -/***/ }), + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } -/***/ 25445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - ArchiveEntry: __nccwpck_require__(92240), - ZipArchiveEntry: __nccwpck_require__(3179), - ArchiveOutputStream: __nccwpck_require__(36728), - ZipArchiveOutputStream: __nccwpck_require__(44432) -}; + isBlocked(now) { + return this._unblockTime >= now; + } -/***/ }), + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } -/***/ 95208: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var Stream = (__nccwpck_require__(12781).Stream); -var PassThrough = (__nccwpck_require__(45193).PassThrough); -var isStream = __nccwpck_require__(41554); + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } -var util = module.exports = {}; + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } -util.normalizeInputSource = function(source) { - if (source === null) { - return Buffer.alloc(0); - } else if (typeof source === 'string') { - return Buffer.from(source); - } else if (isStream(source) && !source._readableState) { - var normalized = new PassThrough(); - source.pipe(normalized); + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } - return normalized; - } + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } - return source; -}; + }; -/***/ }), + var LocalDatastore_1 = LocalDatastore; -/***/ 84322: -/***/ ((__unused_webpack_module, exports) => { + var BottleneckError$3, States; -"use strict"; + BottleneckError$3 = BottleneckError_1; -exports.__esModule = true; -function binaryOperation(operator, left, right) { - switch (operator) { - case '+': - return left + right; - case '-': - return left - right; - case '/': - return left / right; - case '%': - return left % right; - case '*': - return left * right; - case '**': - return Math.pow(left, right); - case '&': - return left & right; - case '|': - return left | right; - case '>>': - return left >> right; - case '>>>': - return left >>> right; - case '<<': - return left << right; - case '^': - return left ^ right; - case '==': - return left == right; - case '===': - return left === right; - case '!=': - return left != right; - case '!==': - return left !== right; - case 'in': - return left in right; - case 'instanceof': - return left instanceof right; - case '>': - return left > right; - case '<': - return left < right; - case '>=': - return left >= right; - case '<=': - return left <= right; - } -} -exports["default"] = binaryOperation; + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } -/***/ }), + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } -/***/ 40953: -/***/ ((module, exports, __nccwpck_require__) => { + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } -"use strict"; + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } -exports.__esModule = true; -var parser_1 = __nccwpck_require__(85026); -var b = __nccwpck_require__(7912); -var binaryOperation_1 = __nccwpck_require__(84322); -function expressionToConstant(expression, options) { - if (options === void 0) { options = {}; } - var constant = true; - function toConstant(expression) { - if (!constant) - return; - if (b.isArrayExpression(expression)) { - var result_1 = []; - for (var i = 0; constant && i < expression.elements.length; i++) { - var element = expression.elements[i]; - if (b.isSpreadElement(element)) { - var spread = toConstant(element.argument); - if (!(isSpreadable(spread) && constant)) { - constant = false; - } - else { - result_1.push.apply(result_1, spread); - } - } - else if (b.isExpression(element)) { - result_1.push(toConstant(element)); - } - else { - constant = false; - } - } - return result_1; - } - if (b.isBinaryExpression(expression)) { - var left = toConstant(expression.left); - var right = toConstant(expression.right); - return constant && binaryOperation_1["default"](expression.operator, left, right); - } - if (b.isBooleanLiteral(expression)) { - return expression.value; - } - if (b.isCallExpression(expression)) { - var args = []; - for (var i = 0; constant && i < expression.arguments.length; i++) { - var arg = expression.arguments[i]; - if (b.isSpreadElement(arg)) { - var spread = toConstant(arg.argument); - if (!(isSpreadable(spread) && constant)) { - constant = false; - } - else { - args.push.apply(args, spread); - } - } - else if (b.isExpression(arg)) { - args.push(toConstant(arg)); - } - else { - constant = false; - } - } - if (!constant) - return; - if (b.isMemberExpression(expression.callee)) { - var object = toConstant(expression.callee.object); - if (!object || !constant) { - constant = false; - return; - } - var member = expression.callee.computed - ? toConstant(expression.callee.property) - : b.isIdentifier(expression.callee.property) - ? expression.callee.property.name - : undefined; - if (member === undefined && !expression.callee.computed) { - constant = false; - } - if (!constant) - return; - if (canCallMethod(object, '' + member)) { - return object[member].apply(object, args); - } - } - else { - if (!b.isExpression(expression.callee)) { - constant = false; - return; - } - var callee = toConstant(expression.callee); - if (!constant) - return; - return callee.apply(null, args); - } - } - if (b.isConditionalExpression(expression)) { - var test = toConstant(expression.test); - return test - ? toConstant(expression.consequent) - : toConstant(expression.alternate); - } - if (b.isIdentifier(expression)) { - if (options.constants && - {}.hasOwnProperty.call(options.constants, expression.name)) { - return options.constants[expression.name]; - } - } - if (b.isLogicalExpression(expression)) { - var left = toConstant(expression.left); - var right = toConstant(expression.right); - if (constant && expression.operator === '&&') { - return left && right; - } - if (constant && expression.operator === '||') { - return left || right; - } - } - if (b.isMemberExpression(expression)) { - var object = toConstant(expression.object); - if (!object || !constant) { - constant = false; - return; - } - var member = expression.computed - ? toConstant(expression.property) - : b.isIdentifier(expression.property) - ? expression.property.name - : undefined; - if (member === undefined && !expression.computed) { - constant = false; - } - if (!constant) - return; - if ({}.hasOwnProperty.call(object, '' + member) && member[0] !== '_') { - return object[member]; - } - } - if (b.isNullLiteral(expression)) { - return null; - } - if (b.isNumericLiteral(expression)) { - return expression.value; - } - if (b.isObjectExpression(expression)) { - var result_2 = {}; - for (var i = 0; constant && i < expression.properties.length; i++) { - var property = expression.properties[i]; - if (b.isObjectProperty(property)) { - if (property.shorthand) { - constant = false; - return; - } - var key = property.computed - ? toConstant(property.key) - : b.isIdentifier(property.key) - ? property.key.name - : b.isStringLiteral(property.key) - ? property.key.value - : undefined; - if (!key || key[0] === '_') { - constant = false; - } - if (!constant) - return; - if (b.isExpression(property.value)) { - var value = toConstant(property.value); - if (!constant) - return; - result_2[key] = value; - } - else { - constant = false; - } - } - else if (b.isObjectMethod(property)) { - constant = false; - } - else if (b.isSpreadProperty(property)) { - var argument = toConstant(property.argument); - if (!argument) - constant = false; - if (!constant) - return; - Object.assign(result_2, argument); - } - } - return result_2; - } - if (b.isParenthesizedExpression(expression)) { - return toConstant(expression.expression); - } - if (b.isRegExpLiteral(expression)) { - return new RegExp(expression.pattern, expression.flags); - } - if (b.isSequenceExpression(expression)) { - for (var i = 0; i < expression.expressions.length - 1 && constant; i++) { - toConstant(expression.expressions[i]); - } - return toConstant(expression.expressions[expression.expressions.length - 1]); - } - if (b.isStringLiteral(expression)) { - return expression.value; - } - // TODO: TaggedTemplateExpression - if (b.isTemplateLiteral(expression)) { - var result_3 = ''; - for (var i = 0; i < expression.quasis.length; i++) { - var quasi = expression.quasis[i]; - result_3 += quasi.value.cooked; - if (i < expression.expressions.length) { - result_3 += '' + toConstant(expression.expressions[i]); - } - } - return result_3; - } - if (b.isUnaryExpression(expression)) { - var argument = toConstant(expression.argument); - if (!constant) { - return; - } - switch (expression.operator) { - case '-': - return -argument; - case '+': - return +argument; - case '!': - return !argument; - case '~': - return ~argument; - case 'typeof': - return typeof argument; - case 'void': - return void argument; - } - } - constant = false; - } - var result = toConstant(expression); - return constant ? { constant: true, result: result } : { constant: false }; -} -exports.expressionToConstant = expressionToConstant; -function isSpreadable(value) { - return (typeof value === 'string' || - Array.isArray(value) || - (typeof Set !== 'undefined' && value instanceof Set) || - (typeof Map !== 'undefined' && value instanceof Map)); -} -function shallowEqual(a, b) { - if (a === b) - return true; - if (a && b && typeof a === 'object' && typeof b === 'object') { - for (var key in a) { - if (a[key] !== b[key]) { - return false; - } - } - for (var key in b) { - if (a[key] !== b[key]) { - return false; - } - } - return true; - } - return false; -} -function canCallMethod(object, member) { - switch (typeof object) { - case 'boolean': - switch (member) { - case 'toString': - return true; - default: - return false; - } - case 'number': - switch (member) { - case 'toExponential': - case 'toFixed': - case 'toPrecision': - case 'toString': - return true; - default: - return false; - } - case 'string': - switch (member) { - case 'charAt': - case 'charCodeAt': - case 'codePointAt': - case 'concat': - case 'endsWith': - case 'includes': - case 'indexOf': - case 'lastIndexOf': - case 'match': - case 'normalize': - case 'padEnd': - case 'padStart': - case 'repeat': - case 'replace': - case 'search': - case 'slice': - case 'split': - case 'startsWith': - case 'substr': - case 'substring': - case 'toLowerCase': - case 'toUpperCase': - case 'trim': - return true; - default: - return false; - } - default: - if (object instanceof RegExp) { - switch (member) { - case 'test': - case 'exec': - return true; - default: - return false; - } - } - return {}.hasOwnProperty.call(object, member) && member[0] !== '_'; - } -} -var EMPTY_OBJECT = {}; -var lastSrc = ''; -var lastConstants = EMPTY_OBJECT; -var lastOptions = EMPTY_OBJECT; -var lastResult = null; -var lastWasConstant = false; -function isConstant(src, constants, options) { - if (constants === void 0) { constants = EMPTY_OBJECT; } - if (options === void 0) { options = EMPTY_OBJECT; } - if (lastSrc === src && - shallowEqual(lastConstants, constants) && - shallowEqual(lastOptions, options)) { - return lastWasConstant; - } - lastSrc = src; - lastConstants = constants; - var ast; - try { - ast = parser_1.parseExpression(src, options); - } - catch (ex) { - return (lastWasConstant = false); - } - var _a = expressionToConstant(ast, { constants: constants }), result = _a.result, constant = _a.constant; - lastResult = result; - return (lastWasConstant = constant); -} -exports.isConstant = isConstant; -function toConstant(src, constants, options) { - if (constants === void 0) { constants = EMPTY_OBJECT; } - if (options === void 0) { options = EMPTY_OBJECT; } - if (!isConstant(src, constants, options)) { - throw new Error(JSON.stringify(src) + ' is not constant.'); - } - return lastResult; -} -exports.toConstant = toConstant; -exports["default"] = isConstant; -module.exports = isConstant; -module.exports["default"] = isConstant; -module.exports.expressionToConstant = expressionToConstant; -module.exports.isConstant = isConstant; -module.exports.toConstant = toConstant; + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -/***/ }), + }; -/***/ 95898: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var States_1 = States; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + var DLList$2, Sync; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + DLList$2 = DLList_1; -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + isEmpty() { + return this._queue.length === 0; + } -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + }; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + var Sync_1 = Sync; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + var version = "2.19.5"; + var version$1 = { + version: version + }; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + parser$3 = parser; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + Events$2 = Events_1; -exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; + RedisConnection$1 = require$$2; -function objectToString(o) { - return Object.prototype.toString.call(o); -} + IORedisConnection$1 = require$$3; + Scripts$1 = require$$4; -/***/ }), + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } -/***/ 83201: -/***/ ((__unused_webpack_module, exports) => { + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } -/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ -/* vim: set ts=2: */ -/*exported CRC32 */ -var CRC32; -(function (factory) { - /*jshint ignore:start */ - /*eslint-disable */ - if(typeof DO_NOT_EXPORT_CRC === 'undefined') { - if(true) { - factory(exports); - } else {} - } else { - factory(CRC32 = {}); - } - /*eslint-enable */ - /*jshint ignore:end */ -}(function(CRC32) { -CRC32.version = '1.2.2'; -/*global Int32Array */ -function signed_crc_table() { - var c = 0, table = new Array(256); + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } - for(var n =0; n != 256; ++n){ - c = n; - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - table[n] = c; - } + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } - return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; -} + keys() { + return Object.keys(this.instances); + } -var T0 = signed_crc_table(); -function slice_by_16_tables(T) { - var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } - for(n = 0; n != 256; ++n) table[n] = T[n]; - for(n = 0; n != 256; ++n) { - v = T[n]; - for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; - } - var out = []; - for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); - return out; -} -var TT = slice_by_16_tables(T0); -var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; -var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; -var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; -function crc32_bstr(bstr, seed) { - var C = seed ^ -1; - for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; - return ~C; -} + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } -function crc32_buf(B, seed) { - var C = seed ^ -1, L = B.length - 15, i = 0; - for(; i < L;) C = - Tf[B[i++] ^ (C & 255)] ^ - Te[B[i++] ^ ((C >> 8) & 255)] ^ - Td[B[i++] ^ ((C >> 16) & 255)] ^ - Tc[B[i++] ^ (C >>> 24)] ^ - Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ - T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ - T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; - L += 15; - while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; - return ~C; -} + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } -function crc32_str(str, seed) { - var C = seed ^ -1; - for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { - c = str.charCodeAt(i++); - if(c < 0x80) { - C = (C>>>8) ^ T0[(C^c)&0xFF]; - } else if(c < 0x800) { - C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } else if(c >= 0xD800 && c < 0xE000) { - c = (c&1023)+64; d = str.charCodeAt(i++)&1023; - C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; - } else { - C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } - } - return ~C; -} -CRC32.table = T0; -// $FlowIgnore -CRC32.bstr = crc32_bstr; -// $FlowIgnore -CRC32.buf = crc32_buf; -// $FlowIgnore -CRC32.str = crc32_str; -})); + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; -/***/ }), + return Group; -/***/ 94521: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + }).call(commonjsGlobal); -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ + var Group_1 = Group; - + var Batcher, Events$3, parser$4; -const {Transform} = __nccwpck_require__(45193); + parser$4 = parser; -const crc32 = __nccwpck_require__(83201); + Events$3 = Events_1; -class CRC32Stream extends Transform { - constructor(options) { - super(options); - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } - this.rawSize = 0; - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - callback(null, chunk); - } + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; - } + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - hex() { - return this.digest('hex').toUpperCase(); - } + return Batcher; - size() { - return this.rawSize; - } -} + }).call(commonjsGlobal); -module.exports = CRC32Stream; + var Batcher_1 = Batcher; + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/***/ }), + var require$$8 = getCjsExportFromNamespace(version$2); -/***/ 92563: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ + NUM_PRIORITIES$1 = 10; + DEFAULT_PRIORITY$1 = 5; + parser$5 = parser; -const {DeflateRaw} = __nccwpck_require__(59796); + Queues$1 = Queues_1; -const crc32 = __nccwpck_require__(83201); + Job$1 = Job_1; -class DeflateCRC32Stream extends DeflateRaw { - constructor(options) { - super(options); + LocalDatastore$1 = LocalDatastore_1; - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); + RedisDatastore$1 = require$$4$1; - this.rawSize = 0; - this.compressedSize = 0; - } + Events$4 = Events_1; - push(chunk, encoding) { - if (chunk) { - this.compressedSize += chunk.length; - } + States$1 = States_1; - return super.push(chunk, encoding); - } + Sync$1 = Sync_1; - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; - } + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } - super._transform(chunk, encoding, callback) - } + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; - } + ready() { + return this._store.ready; + } - hex() { - return this.digest('hex').toUpperCase(); - } + clients() { + return this._store.clients; + } - size(compressed = false) { - if (compressed) { - return this.compressedSize; - } else { - return this.rawSize; - } - } -} + channel() { + return `b_${this.id}`; + } -module.exports = DeflateCRC32Stream; + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } + publish(message) { + return this._store.__publish__(message); + } -/***/ }), + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -/***/ 5101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + chain(_limiter) { + this._limiter = _limiter; + return this; + } -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ + queued(priority) { + return this._queues.queued(priority); + } + clusterQueued() { + return this._store.__queued__(); + } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } -module.exports = { - CRC32Stream: __nccwpck_require__(94521), - DeflateCRC32Stream: __nccwpck_require__(92563) -} + running() { + return this._store.__running__(); + } + done() { + return this._store.__done__(); + } -/***/ }), + jobStatus(id) { + return this._states.jobStatus(id); + } -/***/ 72746: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + jobs(status) { + return this._states.statusJobs(status); + } -"use strict"; + counts() { + return this._states.statusCounts(); + } + _randomIndex() { + return Math.random().toString(36).slice(2); + } -const cp = __nccwpck_require__(32081); -const parse = __nccwpck_require__(66855); -const enoent = __nccwpck_require__(44101); + check(weight = 1) { + return this._store.__check__(weight); + } -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - return spawned; -} + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - return result; -} + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } -module.exports._parse = parse; -module.exports._enoent = enoent; + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } -/***/ }), + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } -/***/ 44101: -/***/ ((module) => { + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } -"use strict"; + currentReservoir() { + return this._store.__currentReservoir__(); + } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -const isWin = process.platform === 'win32'; + } + Bottleneck.default = Bottleneck; -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} + Bottleneck.Events = Events$4; -function hookChildProcess(cp, parsed) { - if (!isWin) { - return; - } + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; - const originalEmit = cp.emit; + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; + + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; + + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed, 'spawn'); + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; - if (err) { - return originalEmit.call(cp, 'error', err); - } - } + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} + return Bottleneck; -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } + }).call(commonjsGlobal); - return null; -} + var Bottleneck_1 = Bottleneck; -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } + var lib = Bottleneck_1; - return null; -} + return lib; -module.exports = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; +}))); /***/ }), -/***/ 66855: +/***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -const path = __nccwpck_require__(71017); -const resolveCommand = __nccwpck_require__(87274); -const escape = __nccwpck_require__(34274); -const readShebang = __nccwpck_require__(41252); - -const isWin = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; - -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); +var balanced = __nccwpck_require__(9417); - const shebang = parsed.file && readShebang(parsed.file); +module.exports = expandTop; - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - return resolveCommand(parsed); - } +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - return parsed.file; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); } -function parseNonShell(parsed) { - if (!isWin) { - return parsed; - } +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + var parts = []; + var m = balanced('{', '}', str); - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); + if (!m) + return str.split(','); - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - const shellCommand = [parsed.command].concat(parsed.args).join(' '); + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } + parts.push.apply(parts, p); - return parsed; + return parts; } -function parse(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original +function expandTop(str) { + if (!str) + return []; - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); + return expand(escapeBraces(str), true).map(unescapeBraces); } -module.exports = parse; - - -/***/ }), - -/***/ 34274: -/***/ ((module) => { - -"use strict"; +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; +function expand(str, isTop) { + var expansions = []; -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + var m = balanced('{', '}', str); + if (!m) return [str]; - return arg; -} + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } - // Algorithm below is based on https://qntm.org/cmd + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - // All other backslashes occur literally + N = []; - // Quote the whole thing: - arg = `"${arg}"`; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } } + } - return arg; + return expansions; } -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; /***/ }), -/***/ 41252: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51590: +/***/ ((module) => { -"use strict"; +module.exports = Buffers; +function Buffers (bufs) { + if (!(this instanceof Buffers)) return new Buffers(bufs); + this.buffers = bufs || []; + this.length = this.buffers.reduce(function (size, buf) { + return size + buf.length + }, 0); +} -const fs = __nccwpck_require__(57147); -const shebangCommand = __nccwpck_require__(67032); +Buffers.prototype.push = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to push a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.push(buf); + this.length += buf.length; + } + return this.length; +}; -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); +Buffers.prototype.unshift = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to unshift a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.unshift(buf); + this.length += buf.length; + } + return this.length; +}; - let fd; +Buffers.prototype.copy = function (dst, dStart, start, end) { + return this.slice(start, end).copy(dst, dStart, 0, end - start); +}; - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } +Buffers.prototype.splice = function (i, howMany) { + var buffers = this.buffers; + var index = i >= 0 ? i : this.length - i; + var reps = [].slice.call(arguments, 2); + + if (howMany === undefined) { + howMany = this.length - index; + } + else if (howMany > this.length - index) { + howMany = this.length - index; + } + + for (var i = 0; i < reps.length; i++) { + this.length += reps[i].length; + } + + var removed = new Buffers(); + var bytes = 0; + + var startBytes = 0; + for ( + var ii = 0; + ii < buffers.length && startBytes + buffers[ii].length < index; + ii ++ + ) { startBytes += buffers[ii].length } + + if (index - startBytes > 0) { + var start = index - startBytes; + + if (start + howMany < buffers[ii].length) { + removed.push(buffers[ii].slice(start, start + howMany)); + + var orig = buffers[ii]; + //var buf = new Buffer(orig.length - howMany); + var buf0 = new Buffer(start); + for (var i = 0; i < start; i++) { + buf0[i] = orig[i]; + } + + var buf1 = new Buffer(orig.length - start - howMany); + for (var i = start + howMany; i < orig.length; i++) { + buf1[ i - howMany - start ] = orig[i] + } + + if (reps.length > 0) { + var reps_ = reps.slice(); + reps_.unshift(buf0); + reps_.push(buf1); + buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); + ii += reps_.length; + reps = []; + } + else { + buffers.splice(ii, 1, buf0, buf1); + //buffers[ii] = buf; + ii += 2; + } + } + else { + removed.push(buffers[ii].slice(start)); + buffers[ii] = buffers[ii].slice(0, start); + ii ++; + } + } + + if (reps.length > 0) { + buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); + ii += reps.length; + } + + while (removed.length < howMany) { + var buf = buffers[ii]; + var len = buf.length; + var take = Math.min(len, howMany - removed.length); + + if (take === len) { + removed.push(buf); + buffers.splice(ii, 1); + } + else { + removed.push(buf.slice(0, take)); + buffers[ii] = buffers[ii].slice(take); + } + } + + this.length -= removed.length; + + return removed; +}; + +Buffers.prototype.slice = function (i, j) { + var buffers = this.buffers; + if (j === undefined) j = this.length; + if (i === undefined) i = 0; + + if (j > this.length) j = this.length; + + var startBytes = 0; + for ( + var si = 0; + si < buffers.length && startBytes + buffers[si].length <= i; + si ++ + ) { startBytes += buffers[si].length } + + var target = new Buffer(j - i); + + var ti = 0; + for (var ii = si; ti < j - i && ii < buffers.length; ii++) { + var len = buffers[ii].length; + + var start = ti === 0 ? i - startBytes : 0; + var end = ti + len >= j - i + ? Math.min(start + (j - i) - ti, len) + : len + ; + + buffers[ii].copy(target, ti, start, end); + ti += end - start; + } + + return target; +}; - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} +Buffers.prototype.pos = function (i) { + if (i < 0 || i >= this.length) throw new Error('oob'); + var l = i, bi = 0, bu = null; + for (;;) { + bu = this.buffers[bi]; + if (l < bu.length) { + return {buf: bi, offset: l}; + } else { + l -= bu.length; + } + bi++; + } +}; -module.exports = readShebang; +Buffers.prototype.get = function get (i) { + var pos = this.pos(i); + return this.buffers[pos.buf].get(pos.offset); +}; -/***/ }), +Buffers.prototype.set = function set (i, b) { + var pos = this.pos(i); -/***/ 87274: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this.buffers[pos.buf].set(pos.offset, b); +}; -"use strict"; +Buffers.prototype.indexOf = function (needle, offset) { + if ("string" === typeof needle) { + needle = new Buffer(needle); + } else if (needle instanceof Buffer) { + // already a buffer + } else { + throw new Error('Invalid type for a search string'); + } + if (!needle.length) { + return 0; + } -const path = __nccwpck_require__(71017); -const which = __nccwpck_require__(34207); -const getPathKey = __nccwpck_require__(20539); + if (!this.length) { + return -1; + } -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + var i = 0, j = 0, match = 0, mstart, pos = 0; - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } + // start search from a particular point in the virtual buffer + if (offset) { + var p = this.pos(offset); + i = p.buf; + j = p.offset; + pos = offset; } - let resolved; + // for each character in virtual buffer + for (;;) { + while (j >= this.buffers[i].length) { + j = 0; + i++; - try { - resolved = which.sync(parsed.command, { - path: env[getPathKey({ env })], - pathExt: withoutPathExt ? path.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); + if (i >= this.buffers.length) { + // search string not found + return -1; + } } - } - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + var char = this.buffers[i][j]; + + if (char == needle[match]) { + // keep track where match started + if (match == 0) { + mstart = { + i: i, + j: j, + pos: pos + }; + } + match++; + if (match == needle.length) { + // full match + return mstart.pos; + } + } else if (match != 0) { + // a partial match ended, go back to match starting position + // this will continue the search at the next character + i = mstart.i; + j = mstart.j; + pos = mstart.pos; + match = 0; + } + + j++; + pos++; } +}; - return resolved; +Buffers.prototype.toBuffer = function() { + return this.slice(); } -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +Buffers.prototype.toString = function(encoding, start, end) { + return this.slice(start, end).toString(encoding); } -module.exports = resolveCommand; - /***/ }), -/***/ 84697: +/***/ 86966: /***/ ((module) => { -/** - * Helpers. +"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; + /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Module exports. + * @public */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + * Module variables. + * @private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; /** - * Long format for `ms`. + * Convert the given value in bytes into a string or parse to string to an integer in bytes. * - * @param {Number} ms - * @return {String} - * @api private + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} */ -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); } - return ms + ' ms'; -} -/** - * Pluralization helper. - */ + if (typeof value === 'number') { + return format(value, options); + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + return null; } - -/***/ }), - -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Format the given value in bytes into a string. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public */ -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } - if (!this.useColors) { - return; - } + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } - args.splice(lastC, 0, c); + return str + unitSeparator + unit; } /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. + * Parse the string value into an integer in bytes. * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. + * If no unit is given, it is assumed the value is in bytes. * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. + * @param {number|string} val * - * @return {String} returns the previously persisted debug modes - * @api private + * @returns {number|null} + * @public */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } - return r; -} + if (typeof val !== 'string') { + return null; + } -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); } -module.exports = __nccwpck_require__(46243)(exports); -const {formatters} = module.exports; +/***/ }), -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +/***/ 28803: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; +"use strict"; + + +var GetIntrinsic = __nccwpck_require__(74538); + +var callBind = __nccwpck_require__(62977); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); } + return intrinsic; }; /***/ }), -/***/ 46243: +/***/ 62977: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(84697); - createDebug.destroy = destroy; +var bind = __nccwpck_require__(88334); +var GetIntrinsic = __nccwpck_require__(74538); - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - /** - * The currently active debug mode names, and names to skip. - */ +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); - createDebug.names = []; - createDebug.skips = []; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +/***/ }), - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } +/***/ 46533: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const self = debug; +var Traverse = __nccwpck_require__(8588); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +module.exports = Chainsaw; +function Chainsaw (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + saw.record(); + return saw.chain(); +}; - args[0] = createDebug.coerce(args[0]); +Chainsaw.light = function ChainsawLight (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + return saw.chain(); +}; - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +Chainsaw.saw = function (builder, handlers) { + var saw = new EventEmitter; + saw.handlers = handlers; + saw.actions = []; - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + saw.chain = function () { + var ch = Traverse(saw.handlers).map(function (node) { + if (this.isRoot) return node; + var ps = this.path; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + if (typeof node === 'function') { + this.update(function () { + saw.actions.push({ + path : ps, + args : [].slice.call(arguments) + }); + return ch; + }); + } + }); - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + process.nextTick(function () { + saw.emit('begin'); + saw.next(); + }); - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + return ch; + }; - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + saw.pop = function () { + return saw.actions.shift(); + }; - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } + saw.next = function () { + var action = saw.pop(); - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + if (!action) { + saw.emit('end'); + } + else if (!action.trap) { + var node = saw.handlers; + action.path.forEach(function (key) { node = node[key] }); + node.apply(saw.handlers, action.args); + } + }; - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + saw.nest = function (cb) { + var args = [].slice.call(arguments, 1); + var autonext = true; - return debug; - } + if (typeof cb === 'boolean') { + var autonext = cb; + cb = args.shift(); + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + var s = Chainsaw.saw(builder, {}); + var r = builder.call(s.handlers, s); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; + if (r !== undefined) s.handlers = r; - createDebug.names = []; - createDebug.skips = []; + // If we are recording... + if ("undefined" !== typeof saw.step) { + // ... our children should, too + s.record(); + } - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + cb.apply(s.chain(), args); + if (autonext !== false) s.on('end', saw.next); + }; - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + saw.record = function () { + upgradeChainsaw(saw); + }; - namespaces = split[i].replace(/\*/g, '.*?'); + ['trap', 'down', 'jump'].forEach(function (method) { + saw[method] = function () { + throw new Error("To use the trap, down and jump features, please "+ + "call record() first to start recording actions."); + }; + }); - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + return saw; +}; - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +function upgradeChainsaw(saw) { + saw.step = 0; - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + // override pop + saw.pop = function () { + return saw.actions[saw.step++]; + }; - let i; - let len; + saw.trap = function (name, cb) { + var ps = Array.isArray(name) ? name : [name]; + saw.actions.push({ + path : ps, + step : saw.step, + cb : cb, + trap : true + }); + }; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + saw.down = function (name) { + var ps = (Array.isArray(name) ? name : [name]).join('/'); + var i = saw.actions.slice(saw.step).map(function (x) { + if (x.trap && x.step <= saw.step) return false; + return x.path.join('/') == ps; + }).indexOf(true); - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + if (i >= 0) saw.step += i; + else saw.step = saw.actions.length; - return false; - } + var act = saw.actions[saw.step - 1]; + if (act && act.trap) { + // It's a trap! + saw.step = act.step; + act.cb(); + } + else saw.next(); + }; - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + saw.jump = function (step) { + saw.step = step; + saw.next(); + }; +}; - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } +/***/ }), - createDebug.enable(createDebug.load()); +/***/ 8937: +/***/ ((module, exports, __nccwpck_require__) => { - return createDebug; +"use strict"; + + +var objIsRegex = __nccwpck_require__(96403); + +exports = (module.exports = parse); + +var TOKEN_TYPES = exports.TOKEN_TYPES = { + LINE_COMMENT: '//', + BLOCK_COMMENT: '/**/', + SINGLE_QUOTE: '\'', + DOUBLE_QUOTE: '"', + TEMPLATE_QUOTE: '`', + REGEXP: '//g' } -module.exports = setup; +var BRACKETS = exports.BRACKETS = { + '(': ')', + '{': '}', + '[': ']' +}; +var BRACKETS_REVERSED = { + ')': '(', + '}': '{', + ']': '[' +}; +exports.parse = parse; +function parse(src, state, options) { + options = options || {}; + state = state || exports.defaultState(); + var start = options.start || 0; + var end = options.end || src.length; + var index = start; + while (index < end) { + try { + parseChar(src[index], state); + } catch (ex) { + ex.index = index; + throw ex; + } + index++; + } + return state; +} -/***/ }), +exports.parseUntil = parseUntil; +function parseUntil(src, delimiter, options) { + options = options || {}; + var start = options.start || 0; + var index = start; + var state = exports.defaultState(); + while (index < src.length) { + if ((options.ignoreNesting || !state.isNesting(options)) && matches(src, delimiter, index)) { + var end = index; + return { + start: start, + end: end, + src: src.substring(start, end) + }; + } + try { + parseChar(src[index], state); + } catch (ex) { + ex.index = index; + throw ex; + } + index++; + } + var err = new Error('The end of the string was reached with no closing bracket found.'); + err.code = 'CHARACTER_PARSER:END_OF_STRING_REACHED'; + err.index = index; + throw err; +} -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.parseChar = parseChar; +function parseChar(character, state) { + if (character.length !== 1) { + var err = new Error('Character must be a string of length 1'); + err.name = 'InvalidArgumentError'; + err.code = 'CHARACTER_PARSER:CHAR_LENGTH_NOT_ONE'; + throw err; + } + state = state || exports.defaultState(); + state.src += character; + var wasComment = state.isComment(); + var lastChar = state.history ? state.history[0] : ''; -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); + if (state.regexpStart) { + if (character === '/' || character == '*') { + state.stack.pop(); + } + state.regexpStart = false; + } + switch (state.current()) { + case TOKEN_TYPES.LINE_COMMENT: + if (character === '\n') { + state.stack.pop(); + } + break; + case TOKEN_TYPES.BLOCK_COMMENT: + if (state.lastChar === '*' && character === '/') { + state.stack.pop(); + } + break; + case TOKEN_TYPES.SINGLE_QUOTE: + if (character === '\'' && !state.escaped) { + state.stack.pop(); + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + break; + case TOKEN_TYPES.DOUBLE_QUOTE: + if (character === '"' && !state.escaped) { + state.stack.pop(); + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + break; + case TOKEN_TYPES.TEMPLATE_QUOTE: + if (character === '`' && !state.escaped) { + state.stack.pop(); + state.hasDollar = false; + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + state.hasDollar = false; + } else if (character === '$' && !state.escaped) { + state.hasDollar = true; + } else if (character === '{' && state.hasDollar) { + state.stack.push(BRACKETS[character]); + } else { + state.escaped = false; + state.hasDollar = false; + } + break; + case TOKEN_TYPES.REGEXP: + if (character === '/' && !state.escaped) { + state.stack.pop(); + } else if (character === '\\' && !state.escaped) { + state.escaped = true; + } else { + state.escaped = false; + } + break; + default: + if (character in BRACKETS) { + state.stack.push(BRACKETS[character]); + } else if (character in BRACKETS_REVERSED) { + if (state.current() !== character) { + var err = new SyntaxError('Mismatched Bracket: ' + character); + err.code = 'CHARACTER_PARSER:MISMATCHED_BRACKET'; + throw err; + }; + state.stack.pop(); + } else if (lastChar === '/' && character === '/') { + // Don't include comments in history + state.history = state.history.substr(1); + state.stack.push(TOKEN_TYPES.LINE_COMMENT); + } else if (lastChar === '/' && character === '*') { + // Don't include comment in history + state.history = state.history.substr(1); + state.stack.push(TOKEN_TYPES.BLOCK_COMMENT); + } else if (character === '/' && isRegexp(state.history)) { + state.stack.push(TOKEN_TYPES.REGEXP); + // N.B. if the next character turns out to be a `*` or a `/` + // then this isn't actually a regexp + state.regexpStart = true; + } else if (character === '\'') { + state.stack.push(TOKEN_TYPES.SINGLE_QUOTE); + } else if (character === '"') { + state.stack.push(TOKEN_TYPES.DOUBLE_QUOTE); + } else if (character === '`') { + state.stack.push(TOKEN_TYPES.TEMPLATE_QUOTE); + } + break; + } + if (!state.isComment() && !wasComment) { + state.history = character + state.history; + } + state.lastChar = character; // store last character for ending block comments + return state; } +exports.defaultState = function () { return new State() }; +function State() { + this.stack = []; -/***/ }), + this.regexpStart = false; + this.escaped = false; + this.hasDollar = false; -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { + this.src = ''; + this.history = '' + this.lastChar = '' +} +State.prototype.current = function () { + return this.stack[this.stack.length - 1]; +}; +State.prototype.isString = function () { + return ( + this.current() === TOKEN_TYPES.SINGLE_QUOTE || + this.current() === TOKEN_TYPES.DOUBLE_QUOTE || + this.current() === TOKEN_TYPES.TEMPLATE_QUOTE + ); +} +State.prototype.isComment = function () { + return this.current() === TOKEN_TYPES.LINE_COMMENT || this.current() === TOKEN_TYPES.BLOCK_COMMENT; +} +State.prototype.isNesting = function (opts) { + if ( + opts && opts.ignoreLineComment && + this.stack.length === 1 && this.stack[0] === TOKEN_TYPES.LINE_COMMENT + ) { + // if we are only inside a line comment, and line comments are ignored + // don't count it as nesting + return false; + } + return !!this.stack.length; +} -/** - * Module dependencies. - */ +function matches(str, matcher, i) { + if (objIsRegex(matcher)) { + return matcher.test(str.substr(i || 0)); + } else { + return str.substr(i || 0, matcher.length) === matcher; + } +} -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); +exports.isPunctuator = isPunctuator +function isPunctuator(c) { + if (!c) return true; // the start of a string is a punctuator + var code = c.charCodeAt(0) -/** - * This is the Node.js implementation of `debug()`. - */ + switch (code) { + case 46: // . dot + case 40: // ( open bracket + case 41: // ) close bracket + case 59: // ; semicolon + case 44: // , comma + case 123: // { open curly brace + case 125: // } close curly brace + case 91: // [ + case 93: // ] + case 58: // : + case 63: // ? + case 126: // ~ + case 37: // % + case 38: // & + case 42: // *: + case 43: // + + case 45: // - + case 47: // / + case 60: // < + case 62: // > + case 94: // ^ + case 124: // | + case 33: // ! + case 61: // = + return true; + default: + return false; + } +} -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +exports.isKeyword = isKeyword +function isKeyword(id) { + return (id === 'if') || (id === 'in') || (id === 'do') || (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let') || (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum') || (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super') || + (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || + (id === 'import') || (id === 'default') || (id === 'finally') || (id === 'extends') || (id === 'function') || + (id === 'continue') || (id === 'debugger') || (id === 'package') || (id === 'private') || (id === 'interface') || + (id === 'instanceof') || (id === 'implements') || (id === 'protected') || (id === 'public') || (id === 'static'); +} -/** - * Colors. - */ +function isRegexp(history) { + //could be start of regexp or divide sign -exports.colors = [6, 2, 3, 4, 5, 1]; + history = history.replace(/^\s*/, ''); -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); + //unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide + if (history[0] === ')') return false; + //unless it's a function expression, it's a regexp, so we assume it's a regexp + if (history[0] === '}') return true; + //any punctuation means it's a regexp + if (isPunctuator(history[0])) return true; + //if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`) + if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0].split('').reverse().join(''))) return true; - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + return false; } + +/***/ }), + +/***/ 92240: +/***/ ((module) => { + /** - * Build up the default `inspectOpts` object from the environment variables. + * node-compress-commons * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ +var ArchiveEntry = module.exports = function() {}; -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +ArchiveEntry.prototype.getName = function() {}; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } +ArchiveEntry.prototype.getSize = function() {}; - obj[prop] = val; - return obj; -}, {}); +ArchiveEntry.prototype.getLastModifiedDate = function() {}; -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +ArchiveEntry.prototype.isDirectory = function() {}; -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} +/***/ }), + +/***/ 36728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Adds ANSI color escape codes if enabled. + * node-compress-commons * - * @api public + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ +var inherits = (__nccwpck_require__(73837).inherits); +var isStream = __nccwpck_require__(41554); +var Transform = (__nccwpck_require__(45193).Transform); + +var ArchiveEntry = __nccwpck_require__(92240); +var util = __nccwpck_require__(95208); + +var ArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ArchiveOutputStream)) { + return new ArchiveOutputStream(options); + } + + Transform.call(this, options); + + this.offset = 0; + this._archive = { + finish: false, + finished: false, + processing: false + }; +}; -function formatArgs(args) { - const {namespace: name, useColors} = this; +inherits(ArchiveOutputStream, Transform); - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; +ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { + // scaffold only +}; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} +ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { + // scaffold only +}; -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} +ArchiveOutputStream.prototype._emitErrorCallback = function(err) { + if (err) { + this.emit('error', err); + } +}; -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +ArchiveOutputStream.prototype._finish = function(ae) { + // scaffold only +}; -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +ArchiveOutputStream.prototype._normalizeEntry = function(ae) { + // scaffold only +}; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +ArchiveOutputStream.prototype.entry = function(ae, source, callback) { + source = source || null; -function load() { - return process.env.DEBUG; -} + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); + } -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + if (!(ae instanceof ArchiveEntry)) { + callback(new Error('not a valid instance of ArchiveEntry')); + return; + } -function init(debug) { - debug.inspectOpts = {}; + if (this._archive.finish || this._archive.finished) { + callback(new Error('unacceptable entry after finish')); + return; + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + if (this._archive.processing) { + callback(new Error('already processing an entry')); + return; + } -module.exports = __nccwpck_require__(46243)(exports); + this._archive.processing = true; + this._normalizeEntry(ae); + this._entry = ae; -const {formatters} = module.exports; + source = util.normalizeInputSource(source); -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (Buffer.isBuffer(source)) { + this._appendBuffer(ae, source, callback); + } else if (isStream(source)) { + this._appendStream(ae, source, callback); + } else { + this._archive.processing = false; + callback(new Error('input source must be valid Stream or Buffer instance')); + return; + } -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); + return this; }; -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ +ArchiveOutputStream.prototype.finish = function() { + if (this._archive.processing) { + this._archive.finish = true; + return; + } -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); + this._finish(); }; +ArchiveOutputStream.prototype.getBytesWritten = function() { + return this.offset; +}; -/***/ }), +ArchiveOutputStream.prototype.write = function(chunk, cb) { + if (chunk) { + this.offset += chunk.length; + } -/***/ 56323: -/***/ ((module) => { + return Transform.prototype.write.call(this, chunk, cb); +}; -"use strict"; +/***/ }), +/***/ 11704: +/***/ ((module) => { -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { + WORD: 4, + DWORD: 8, + EMPTY: Buffer.alloc(0), -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} + SHORT: 2, + SHORT_MASK: 0xffff, + SHORT_SHIFT: 16, + SHORT_ZERO: Buffer.from(Array(2)), + LONG: 4, + LONG_ZERO: Buffer.from(Array(4)), -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + MIN_VERSION_INITIAL: 10, + MIN_VERSION_DATA_DESCRIPTOR: 20, + MIN_VERSION_ZIP64: 45, + VERSION_MADEBY: 45, - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} + METHOD_STORED: 0, + METHOD_DEFLATED: 8, -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; + PLATFORM_UNIX: 3, + PLATFORM_FAT: 0, -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} + SIG_LFH: 0x04034b50, + SIG_DD: 0x08074b50, + SIG_CFH: 0x02014b50, + SIG_EOCD: 0x06054b50, + SIG_ZIP64_EOCD: 0x06064B50, + SIG_ZIP64_EOCD_LOC: 0x07064B50, -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + ZIP64_MAGIC_SHORT: 0xffff, + ZIP64_MAGIC: 0xffffffff, + ZIP64_EXTRA_ID: 0x0001, -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} + ZLIB_NO_COMPRESSION: 0, + ZLIB_BEST_SPEED: 1, + ZLIB_BEST_COMPRESSION: 9, + ZLIB_DEFAULT_COMPRESSION: -1, -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} + MODE_MASK: 0xFFF, + DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH + DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) + EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] -} + // Unix file types + S_IFMT: 61440, // 0170000 type of file mask + S_IFIFO: 4096, // 010000 named pipe (fifo) + S_IFCHR: 8192, // 020000 character special + S_IFDIR: 16384, // 040000 directory + S_IFBLK: 24576, // 060000 block special + S_IFREG: 32768, // 0100000 regular + S_IFLNK: 40960, // 0120000 symbolic link + S_IFSOCK: 49152, // 0140000 socket -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} + // DOS file type flags + S_DOS_A: 32, // 040 Archive + S_DOS_D: 16, // 020 Directory + S_DOS_V: 8, // 010 Volume + S_DOS_S: 4, // 04 System + S_DOS_H: 2, // 02 Hidden + S_DOS_R: 1 // 01 Read Only +}; -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. -} +/***/ }), -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } +/***/ 63229: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination -} +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var zipUtil = __nccwpck_require__(68682); -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; +var DATA_DESCRIPTOR_FLAG = 1 << 3; +var ENCRYPTION_FLAG = 1 << 0; +var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; +var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; +var STRONG_ENCRYPTION_FLAG = 1 << 6; +var UFT8_NAMES_FLAG = 1 << 11; - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; +var GeneralPurposeBit = module.exports = function() { + if (!(this instanceof GeneralPurposeBit)) { + return new GeneralPurposeBit(); + } - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } -} + this.descriptor = false; + this.encryption = false; + this.utf8 = false; + this.numberOfShannonFanoTrees = 0; + this.strongEncryption = false; + this.slidingDictionarySize = 0; -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } + return this; +}; - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) +GeneralPurposeBit.prototype.encode = function() { + return zipUtil.getShortBytes( + (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | + (this.utf8 ? UFT8_NAMES_FLAG : 0) | + (this.encryption ? ENCRYPTION_FLAG : 0) | + (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) + ); }; -var deepmerge_1 = deepmerge; +GeneralPurposeBit.prototype.parse = function(buf, offset) { + var flag = zipUtil.getShortBytesValue(buf, offset); + var gbp = new GeneralPurposeBit(); -module.exports = deepmerge_1; + gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); + gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); + gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); + gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); + gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); + gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); + return gbp; +}; -/***/ }), +GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { + this.numberOfShannonFanoTrees = n; +}; -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { +GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { + return this.numberOfShannonFanoTrees; +}; -"use strict"; +GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { + this.slidingDictionarySize = n; +}; +GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { + return this.slidingDictionarySize; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); +GeneralPurposeBit.prototype.useDataDescriptor = function(b) { + this.descriptor = b; +}; -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +GeneralPurposeBit.prototype.usesDataDescriptor = function() { + return this.descriptor; +}; - /* istanbul ignore next */ +GeneralPurposeBit.prototype.useEncryption = function(b) { + this.encryption = b; +}; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } +GeneralPurposeBit.prototype.usesEncryption = function() { + return this.encryption; +}; - this.name = 'Deprecation'; - } +GeneralPurposeBit.prototype.useStrongEncryption = function(b) { + this.strongEncryption = b; +}; -} +GeneralPurposeBit.prototype.usesStrongEncryption = function() { + return this.strongEncryption; +}; -exports.Deprecation = Deprecation; +GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { + this.utf8 = b; +}; +GeneralPurposeBit.prototype.usesUTF8ForNames = function() { + return this.utf8; +}; /***/ }), -/***/ 3194: +/***/ 70713: /***/ ((module) => { -"use strict"; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { + /** + * Bits used for permissions (and sticky bit) + */ + PERM_MASK: 4095, // 07777 + /** + * Bits used to indicate the filesystem object type. + */ + FILE_TYPE_FLAG: 61440, // 0170000 -module.exports = { - 'html': '', - 'xml': '', - 'transitional': '', - 'strict': '', - 'frameset': '', - '1.1': '', - 'basic': '', - 'mobile': '', - 'plist': '' -}; + /** + * Indicates symbolic links. + */ + LINK_FLAG: 40960, // 0120000 + + /** + * Indicates plain files. + */ + FILE_FLAG: 32768, // 0100000 + + /** + * Indicates directories. + */ + DIR_FLAG: 16384, // 040000 + // ---------------------------------------------------------- + // somewhat arbitrary choices that are quite common for shared + // installations + // ----------------------------------------------------------- + + /** + * Default permissions for symbolic links. + */ + DEFAULT_LINK_PERM: 511, // 0777 + + /** + * Default permissions for directories. + */ + DEFAULT_DIR_PERM: 493, // 0755 + + /** + * Default permissions for plain files. + */ + DEFAULT_FILE_PERM: 420 // 0644 +}; /***/ }), -/***/ 13598: +/***/ 68682: /***/ ((module) => { -"use strict"; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var util = module.exports = {}; +util.dateToDos = function(d, forceLocalTime) { + forceLocalTime = forceLocalTime || false; -function _process (v, mod) { - var i - var r + var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); - if (typeof mod === 'function') { - r = mod(v) - if (r !== undefined) { - v = r - } - } else if (Array.isArray(mod)) { - for (i = 0; i < mod.length; i++) { - r = mod[i](v) - if (r !== undefined) { - v = r - } - } + if (year < 1980) { + return 2162688; // 1980-1-1 00:00:00 + } else if (year >= 2044) { + return 2141175677; // 2043-12-31 23:59:58 } - return v -} + var val = { + year: year, + month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), + date: forceLocalTime ? d.getDate() : d.getUTCDate(), + hours: forceLocalTime ? d.getHours() : d.getUTCHours(), + minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), + seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() + }; -function parseKey (key, val) { - // detect negative index notation - if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { - return val.length + parseInt(key, 10) - } - return key -} + return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | + (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); +}; -function isIndex (k) { - return /^\d+$/.test(k) -} +util.dosToDate = function(dos) { + return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); +}; -function isObject (val) { - return Object.prototype.toString.call(val) === '[object Object]' -} +util.fromDosTime = function(buf) { + return util.dosToDate(buf.readUInt32LE(0)); +}; -function isArrayOrObject (val) { - return Object(val) === val -} +util.getEightBytes = function(v) { + var buf = Buffer.alloc(8); + buf.writeUInt32LE(v % 0x0100000000, 0); + buf.writeUInt32LE((v / 0x0100000000) | 0, 4); -function isEmptyObject (val) { - return Object.keys(val).length === 0 -} + return buf; +}; -var blacklist = ['__proto__', 'prototype', 'constructor'] -var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } +util.getShortBytes = function(v) { + var buf = Buffer.alloc(2); + buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); -function parsePath (path, sep) { - if (path.indexOf('[') >= 0) { - path = path.replace(/\[/g, sep).replace(/]/g, '') - } + return buf; +}; - var parts = path.split(sep) +util.getShortBytesValue = function(buf, offset) { + return buf.readUInt16LE(offset); +}; - var check = parts.filter(blacklistFilter) +util.getLongBytes = function(v) { + var buf = Buffer.alloc(4); + buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); - if (check.length !== parts.length) { - throw Error('Refusing to update blacklisted property ' + path) - } + return buf; +}; - return parts -} +util.getLongBytesValue = function(buf, offset) { + return buf.readUInt32LE(offset); +}; -var hasOwnProperty = Object.prototype.hasOwnProperty +util.toDosTime = function(d) { + return util.getLongBytes(util.dateToDos(d)); +}; -function DotObject (separator, override, useArray, useBrackets) { - if (!(this instanceof DotObject)) { - return new DotObject(separator, override, useArray, useBrackets) - } +/***/ }), - if (typeof override === 'undefined') override = false - if (typeof useArray === 'undefined') useArray = true - if (typeof useBrackets === 'undefined') useBrackets = true - this.separator = separator || '.' - this.override = override - this.useArray = useArray - this.useBrackets = useBrackets - this.keepArray = false +/***/ 3179: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // contains touched arrays - this.cleanup = [] -} +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var normalizePath = __nccwpck_require__(55388); -var dotDefault = new DotObject('.', false, true, true) -function wrap (method) { - return function () { - return dotDefault[method].apply(dotDefault, arguments) - } -} +var ArchiveEntry = __nccwpck_require__(92240); +var GeneralPurposeBit = __nccwpck_require__(63229); +var UnixStat = __nccwpck_require__(70713); -DotObject.prototype._fill = function (a, obj, v, mod) { - var k = a.shift() +var constants = __nccwpck_require__(11704); +var zipUtil = __nccwpck_require__(68682); - if (a.length > 0) { - obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) +var ZipArchiveEntry = module.exports = function(name) { + if (!(this instanceof ZipArchiveEntry)) { + return new ZipArchiveEntry(name); + } - if (!isArrayOrObject(obj[k])) { - if (this.override) { - obj[k] = {} - } else { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error( - 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] - ) - } + ArchiveEntry.call(this); - return - } - } + this.platform = constants.PLATFORM_FAT; + this.method = -1; - this._fill(a, obj[k], v, mod) - } else { - if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error("Trying to redefine non-empty obj['" + k + "']") - } + this.name = null; + this.size = 0; + this.csize = 0; + this.gpb = new GeneralPurposeBit(); + this.crc = 0; + this.time = -1; - return - } + this.minver = constants.MIN_VERSION_INITIAL; + this.mode = -1; + this.extra = null; + this.exattr = 0; + this.inattr = 0; + this.comment = null; - obj[k] = _process(v, mod) + if (name) { + this.setName(name); } -} +}; + +inherits(ZipArchiveEntry, ArchiveEntry); /** + * Returns the extra fields related to the entry. * - * Converts an object with dotted-key/value pairs to it's expanded version + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { + return this.getExtra(); +}; + +/** + * Returns the comment set for the entry. * - * Optionally transformed by a set of modifiers. + * @returns {string} + */ +ZipArchiveEntry.prototype.getComment = function() { + return this.comment !== null ? this.comment : ''; +}; + +/** + * Returns the compressed size of the entry. * - * Usage: + * @returns {number} + */ +ZipArchiveEntry.prototype.getCompressedSize = function() { + return this.csize; +}; + +/** + * Returns the CRC32 digest for the entry. * - * var row = { - * 'nr': 200, - * 'doc.name': ' My Document ' - * } + * @returns {number} + */ +ZipArchiveEntry.prototype.getCrc = function() { + return this.crc; +}; + +/** + * Returns the external file attributes for the entry. * - * var mods = { - * 'doc.name': [_s.trim, _s.underscored] - * } + * @returns {number} + */ +ZipArchiveEntry.prototype.getExternalAttributes = function() { + return this.exattr; +}; + +/** + * Returns the extra fields related to the entry. * - * dot.object(row, mods) + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getExtra = function() { + return this.extra !== null ? this.extra : constants.EMPTY; +}; + +/** + * Returns the general purpose bits related to the entry. * - * @param {Object} obj - * @param {Object} mods + * @returns {GeneralPurposeBit} */ -DotObject.prototype.object = function (obj, mods) { - var self = this +ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { + return this.gpb; +}; - Object.keys(obj).forEach(function (k) { - var mod = mods === undefined ? null : mods[k] - // normalize array notation. - var ok = parsePath(k, self.separator).join(self.separator) +/** + * Returns the internal file attributes for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getInternalAttributes = function() { + return this.inattr; +}; - if (ok.indexOf(self.separator) !== -1) { - self._fill(ok.split(self.separator), obj, obj[k], mod) - delete obj[k] - } else { - obj[k] = _process(obj[k], mod) - } - }) +/** + * Returns the last modified date of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getLastModifiedDate = function() { + return this.getTime(); +}; - return obj -} +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { + return this.getExtra(); +}; /** - * @param {String} path dotted path - * @param {String} v value to be set - * @param {Object} obj object to be modified - * @param {Function|Array} mod optional modifier + * Returns the compression method used on the entry. + * + * @returns {number} */ -DotObject.prototype.str = function (path, v, obj, mod) { - var ok = parsePath(path, this.separator).join(this.separator) +ZipArchiveEntry.prototype.getMethod = function() { + return this.method; +}; - if (path.indexOf(this.separator) !== -1) { - this._fill(ok.split(this.separator), obj, v, mod) - } else { - obj[path] = _process(v, mod) - } +/** + * Returns the filename of the entry. + * + * @returns {string} + */ +ZipArchiveEntry.prototype.getName = function() { + return this.name; +}; - return obj -} +/** + * Returns the platform on which the entry was made. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getPlatform = function() { + return this.platform; +}; /** + * Returns the size of the entry. * - * Pick a value from an object using dot notation. + * @returns {number} + */ +ZipArchiveEntry.prototype.getSize = function() { + return this.size; +}; + +/** + * Returns a date object representing the last modified date of the entry. * - * Optionally remove the value + * @returns {number|Date} + */ +ZipArchiveEntry.prototype.getTime = function() { + return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; +}; + +/** + * Returns the DOS timestamp for the entry. * - * @param {String} path - * @param {Object} obj - * @param {Boolean} remove + * @returns {number} */ -DotObject.prototype.pick = function (path, obj, remove, reindexArray) { - var i - var keys - var val - var key - var cp +ZipArchiveEntry.prototype.getTimeDos = function() { + return this.time !== -1 ? this.time : 0; +}; - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = parseKey(keys[i], obj) - if (obj && typeof obj === 'object' && key in obj) { - if (i === keys.length - 1) { - if (remove) { - val = obj[key] - if (reindexArray && Array.isArray(obj)) { - obj.splice(key, 1) - } else { - delete obj[key] - } - if (Array.isArray(obj)) { - cp = keys.slice(0, -1).join('.') - if (this.cleanup.indexOf(cp) === -1) { - this.cleanup.push(cp) - } - } - return val - } else { - return obj[key] - } - } else { - obj = obj[key] - } - } else { - return undefined - } - } - if (remove && Array.isArray(obj)) { - obj = obj.filter(function (n) { - return n !== undefined - }) - } - return obj -} /** + * Returns the UNIX file permissions for the entry. * - * Delete value from an object using dot notation. + * @returns {number} + */ +ZipArchiveEntry.prototype.getUnixMode = function() { + return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); +}; + +/** + * Returns the version of ZIP needed to extract the entry. * - * @param {String} path - * @param {Object} obj - * @return {any} The removed value + * @returns {number} */ -DotObject.prototype.delete = function (path, obj) { - return this.remove(path, obj, true) -} +ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { + return this.minver; +}; /** + * Sets the comment of the entry. * - * Remove value from an object using dot notation. + * @param comment + */ +ZipArchiveEntry.prototype.setComment = function(comment) { + if (Buffer.byteLength(comment) !== comment.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } + + this.comment = comment; +}; + +/** + * Sets the compressed size of the entry. * - * Will remove multiple items if path is an array. - * In this case array indexes will be retained until all - * removals have been processed. + * @param size + */ +ZipArchiveEntry.prototype.setCompressedSize = function(size) { + if (size < 0) { + throw new Error('invalid entry compressed size'); + } + + this.csize = size; +}; + +/** + * Sets the checksum of the entry. * - * Use dot.delete() to automatically re-index arrays. + * @param crc + */ +ZipArchiveEntry.prototype.setCrc = function(crc) { + if (crc < 0) { + throw new Error('invalid entry crc32'); + } + + this.crc = crc; +}; + +/** + * Sets the external file attributes of the entry. * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value + * @param attr */ -DotObject.prototype.remove = function (path, obj, reindexArray) { - var i +ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { + this.exattr = attr >>> 0; +}; - this.cleanup = [] - if (Array.isArray(path)) { - for (i = 0; i < path.length; i++) { - this.pick(path[i], obj, true, reindexArray) - } - if (!reindexArray) { - this._cleanup(obj) - } - return obj - } else { - return this.pick(path, obj, true, reindexArray) - } -} +/** + * Sets the extra fields related to the entry. + * + * @param extra + */ +ZipArchiveEntry.prototype.setExtra = function(extra) { + this.extra = extra; +}; -DotObject.prototype._cleanup = function (obj) { - var ret - var i - var keys - var root - if (this.cleanup.length) { - for (i = 0; i < this.cleanup.length; i++) { - keys = this.cleanup[i].split('.') - root = keys.splice(0, -1).join('.') - ret = root ? this.pick(root, obj) : obj - ret = ret[keys[0]].filter(function (v) { - return v !== undefined - }) - this.set(this.cleanup[i], ret, obj) - } - this.cleanup = [] +/** + * Sets the general purpose bits related to the entry. + * + * @param gpb + */ +ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { + if (!(gpb instanceof GeneralPurposeBit)) { + throw new Error('invalid entry GeneralPurposeBit'); } -} + + this.gpb = gpb; +}; /** - * Alias method for `dot.remove` - * - * Note: this is not an alias for dot.delete() + * Sets the internal file attributes of the entry. * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value + * @param attr */ -DotObject.prototype.del = DotObject.prototype.remove +ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { + this.inattr = attr; +}; /** + * Sets the compression method of the entry. * - * Move a property from one place to the other. - * - * If the source path does not exist (undefined) - * the target property will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj - * @param {Function|Array} mods - * @param {Boolean} merge + * @param method */ -DotObject.prototype.move = function (source, target, obj, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) - } else { - merge = mods - this.set(target, this.pick(source, obj, true), obj, merge) +ZipArchiveEntry.prototype.setMethod = function(method) { + if (method < 0) { + throw new Error('invalid entry compression method'); } - return obj -} + this.method = method; +}; /** + * Sets the name of the entry. * - * Transfer a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge + * @param name + * @param prependSlash */ -DotObject.prototype.transfer = function ( - source, - target, - obj1, - obj2, - mods, - merge -) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process(this.pick(source, obj1, true), mods), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, true), obj2, merge) +ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { + name = normalizePath(name, false) + .replace(/^\w+:/, '') + .replace(/^(\.\.\/|\/)+/, ''); + + if (prependSlash) { + name = `/${name}`; } - return obj2 -} + if (Buffer.byteLength(name) !== name.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } + + this.name = name; +}; /** + * Sets the platform on which the entry was made. * - * Copy a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. + * @param platform + */ +ZipArchiveEntry.prototype.setPlatform = function(platform) { + this.platform = platform; +}; + +/** + * Sets the size of the entry. * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge + * @param size */ -DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process( - // clone what is picked - JSON.parse(JSON.stringify(this.pick(source, obj1, false))), - mods - ), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, false), obj2, merge) +ZipArchiveEntry.prototype.setSize = function(size) { + if (size < 0) { + throw new Error('invalid entry size'); } - return obj2 -} + this.size = size; +}; /** + * Sets the time of the entry. * - * Set a property on an object using dot notation. - * - * @param {String} path - * @param {any} val - * @param {Object} obj - * @param {Boolean} merge + * @param time + * @param forceLocalTime */ -DotObject.prototype.set = function (path, val, obj, merge) { - var i - var k - var keys - var key - - // Do not operate if the value is undefined. - if (typeof val === 'undefined') { - return obj +ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { + if (!(time instanceof Date)) { + throw new Error('invalid entry time'); } - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = keys[i] - if (i === keys.length - 1) { - if (merge && isObject(val) && isObject(obj[key])) { - for (k in val) { - if (hasOwnProperty.call(val, k)) { - obj[key][k] = val[k] - } - } - } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { - for (var j = 0; j < val.length; j++) { - obj[keys[i]].push(val[j]) - } - } else { - obj[key] = val - } - } else if ( - // force the value to be an object - !hasOwnProperty.call(obj, key) || - (!isObject(obj[key]) && !Array.isArray(obj[key])) - ) { - // initialize as array if next key is numeric - if (/^\d+$/.test(keys[i + 1])) { - obj[key] = [] - } else { - obj[key] = {} - } - } - obj = obj[key] - } - return obj -} + this.time = zipUtil.dateToDos(time, forceLocalTime); +}; /** + * Sets the UNIX file permissions for the entry. * - * Transform an object - * - * Usage: - * - * var obj = { - * "id": 1, - * "some": { - * "thing": "else" - * } - * } - * - * var transform = { - * "id": "nr", - * "some.thing": "name" - * } - * - * var tgt = dot.transform(transform, obj) - * - * @param {Object} recipe Transform recipe - * @param {Object} obj Object to be transformed - * @param {Array} mods modifiers for the target + * @param mode */ -DotObject.prototype.transform = function (recipe, obj, tgt) { - obj = obj || {} - tgt = tgt || {} - Object.keys(recipe).forEach( - function (key) { - this.set(recipe[key], this.pick(key, obj), tgt) - }.bind(this) - ) - return tgt -} +ZipArchiveEntry.prototype.setUnixMode = function(mode) { + mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; + + var extattr = 0; + extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); + + this.setExternalAttributes(extattr); + this.mode = mode & constants.MODE_MASK; + this.platform = constants.PLATFORM_UNIX; +}; /** + * Sets the version of ZIP needed to extract this entry. * - * Convert object to dotted-key/value pair - * - * Usage: + * @param minver + */ +ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { + this.minver = minver; +}; + +/** + * Returns true if this entry represents a directory. * - * var tgt = dot.dot(obj) + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isDirectory = function() { + return this.getName().slice(-1) === '/'; +}; + +/** + * Returns true if this entry represents a unix symlink, + * in which case the entry's content contains the target path + * for the symlink. * - * or + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isUnixSymlink = function() { + return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; +}; + +/** + * Returns true if this entry is using the ZIP64 extension of ZIP. * - * var tgt = {} - * dot.dot(obj, tgt) + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isZip64 = function() { + return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; +}; + + +/***/ }), + +/***/ 44432: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * node-compress-commons * - * @param {Object} obj source object - * @param {Object} tgt target object - * @param {Array} path path array (internal) + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -DotObject.prototype.dot = function (obj, tgt, path) { - tgt = tgt || {} - path = path || [] - var isArray = Array.isArray(obj) +var inherits = (__nccwpck_require__(73837).inherits); +var crc32 = __nccwpck_require__(83201); +var {CRC32Stream} = __nccwpck_require__(5101); +var {DeflateCRC32Stream} = __nccwpck_require__(5101); - Object.keys(obj).forEach( - function (key) { - var index = isArray && this.useBrackets ? '[' + key + ']' : key - if ( - isArrayOrObject(obj[key]) && - ((isObject(obj[key]) && !isEmptyObject(obj[key])) || - (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) - ) { - if (isArray && this.useBrackets) { - var previousKey = path[path.length - 1] || '' - return this.dot( - obj[key], - tgt, - path.slice(0, -1).concat(previousKey + index) - ) - } else { - return this.dot(obj[key], tgt, path.concat(index)) - } - } else { - if (isArray && this.useBrackets) { - tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] - } else { - tgt[path.concat(index).join(this.separator)] = obj[key] - } - } - }.bind(this) - ) - return tgt -} +var ArchiveOutputStream = __nccwpck_require__(36728); +var ZipArchiveEntry = __nccwpck_require__(3179); +var GeneralPurposeBit = __nccwpck_require__(63229); -DotObject.pick = wrap('pick') -DotObject.move = wrap('move') -DotObject.transfer = wrap('transfer') -DotObject.transform = wrap('transform') -DotObject.copy = wrap('copy') -DotObject.object = wrap('object') -DotObject.str = wrap('str') -DotObject.set = wrap('set') -DotObject.delete = wrap('delete') -DotObject.del = DotObject.remove = wrap('remove') -DotObject.dot = wrap('dot'); -['override', 'overwrite'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault.override - }, - set: function (val) { - dotDefault.override = !!val - } - }) -}); -['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault[prop] - }, - set: function (val) { - dotDefault[prop] = val - } - }) -}) +var constants = __nccwpck_require__(11704); +var util = __nccwpck_require__(95208); +var zipUtil = __nccwpck_require__(68682); -DotObject._process = _process +var ZipArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ZipArchiveOutputStream)) { + return new ZipArchiveOutputStream(options); + } -module.exports = DotObject + options = this.options = this._defaults(options); + ArchiveOutputStream.call(this, options); -/***/ }), + this._entry = null; + this._entries = []; + this._archive = { + centralLength: 0, + centralOffset: 0, + comment: '', + finish: false, + finished: false, + processing: false, + forceZip64: options.forceZip64, + forceLocalTime: options.forceLocalTime + }; +}; -/***/ 18212: -/***/ ((module) => { +inherits(ZipArchiveOutputStream, ArchiveOutputStream); -"use strict"; +ZipArchiveOutputStream.prototype._afterAppend = function(ae) { + this._entries.push(ae); + if (ae.getGeneralPurposeBit().usesDataDescriptor()) { + this._writeDataDescriptor(ae); + } -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; + this._archive.processing = false; + this._entry = null; + + if (this._archive.finish && !this._archive.finished) { + this._finish(); + } }; +ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { + if (source.length === 0) { + ae.setMethod(constants.METHOD_STORED); + } -/***/ }), + var method = ae.getMethod(); -/***/ 81205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (method === constants.METHOD_STORED) { + ae.setSize(source.length); + ae.setCompressedSize(source.length); + ae.setCrc(crc32.buf(source) >>> 0); + } -var once = __nccwpck_require__(1223); + this._writeLocalFileHeader(ae); -var noop = function() {}; + if (method === constants.METHOD_STORED) { + this.write(source); + this._afterAppend(ae); + callback(null, ae); + return; + } else if (method === constants.METHOD_DEFLATED) { + this._smartStream(ae, callback).end(source); + return; + } else { + callback(new Error('compression method ' + method + ' not implemented')); + return; + } +}; -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; +ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + + this._writeLocalFileHeader(ae); + + var smart = this._smartStream(ae, callback); + source.once('error', function(err) { + smart.emit('error', err); + smart.end(); + }) + source.pipe(smart); }; -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +ZipArchiveOutputStream.prototype._defaults = function(o) { + if (typeof o !== 'object') { + o = {}; + } + + if (typeof o.zlib !== 'object') { + o.zlib = {}; + } + + if (typeof o.zlib.level !== 'number') { + o.zlib.level = constants.ZLIB_BEST_SPEED; + } + + o.forceZip64 = !!o.forceZip64; + o.forceLocalTime = !!o.forceLocalTime; + + return o; }; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; +ZipArchiveOutputStream.prototype._finish = function() { + this._archive.centralOffset = this.offset; - callback = once(callback || noop); + this._entries.forEach(function(ae) { + this._writeCentralFileHeader(ae); + }.bind(this)); - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; + this._archive.centralLength = this.offset - this._archive.centralOffset; - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; + if (this.isZip64()) { + this._writeCentralDirectoryZip64(); + } - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; + this._writeCentralDirectoryEnd(); - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + this._archive.processing = false; + this._archive.finish = true; + this._archive.finished = true; + this.end(); +}; - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; +ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { + if (ae.getMethod() === -1) { + ae.setMethod(constants.METHOD_DEFLATED); + } - var onerror = function(err) { - callback.call(stream, err); - }; + if (ae.getMethod() === constants.METHOD_DEFLATED) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + } - var onclose = function() { - process.nextTick(onclosenexttick); - }; + if (ae.getTime() === -1) { + ae.setTime(new Date(), this._archive.forceLocalTime); + } - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; + ae._offsets = { + file: 0, + data: 0, + contents: 0, + }; +}; - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { + var deflate = ae.getMethod() === constants.METHOD_DEFLATED; + var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); + var error = null; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } + function handleStuff() { + var digest = process.digest().readUInt32BE(0); + ae.setCrc(digest); + ae.setSize(process.size()); + ae.setCompressedSize(process.size(true)); + this._afterAppend(ae); + callback(error, ae); + } - if (isChildProcess(stream)) stream.on('exit', onexit); + process.once('end', handleStuff.bind(this)); + process.once('error', function(err) { + error = err; + }); - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); + process.pipe(this, { end: false }); - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + return process; }; -module.exports = eos; +ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { + var records = this._entries.length; + var size = this._archive.centralLength; + var offset = this._archive.centralOffset; + if (this.isZip64()) { + records = constants.ZIP64_MAGIC_SHORT; + size = constants.ZIP64_MAGIC; + offset = constants.ZIP64_MAGIC; + } -/***/ }), + // signature + this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); -/***/ 34852: -/***/ ((module, exports) => { + // disk numbers + this.write(constants.SHORT_ZERO); + this.write(constants.SHORT_ZERO); -"use strict"; -/** - * @author Toru Nagashima - * @copyright 2015 Toru Nagashima. All rights reserved. - * See LICENSE file in root directory for full license. - */ + // number of entries + this.write(zipUtil.getShortBytes(records)); + this.write(zipUtil.getShortBytes(records)); + // length and location of CD + this.write(zipUtil.getLongBytes(size)); + this.write(zipUtil.getLongBytes(offset)); -Object.defineProperty(exports, "__esModule", ({ value: true })); + // archive comment + var comment = this.getComment(); + var commentLength = Buffer.byteLength(comment); + this.write(zipUtil.getShortBytes(commentLength)); + this.write(comment); +}; -/** - * @typedef {object} PrivateData - * @property {EventTarget} eventTarget The event target. - * @property {{type:string}} event The original event object. - * @property {number} eventPhase The current event phase. - * @property {EventTarget|null} currentTarget The current event target. - * @property {boolean} canceled The flag to prevent default. - * @property {boolean} stopped The flag to stop propagation. - * @property {boolean} immediateStopped The flag to stop propagation immediately. - * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. - * @property {number} timeStamp The unix time. - * @private - */ +ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); -/** - * Private data for event wrappers. - * @type {WeakMap} - * @private - */ -const privateData = new WeakMap(); + // size of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(44)); -/** - * Cache for wrapper classes. - * @type {WeakMap} - * @private - */ -const wrappers = new WeakMap(); + // version made by + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); -/** - * Get private data. - * @param {Event} event The event object to get private data. - * @returns {PrivateData} The private data of the event. - * @private - */ -function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv -} + // version to extract + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); -/** - * https://dom.spec.whatwg.org/#set-the-canceled-flag - * @param data {PrivateData} private data. - */ -function setCancelFlag(data) { - if (data.passiveListener != null) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return - } - if (!data.event.cancelable) { - return - } + // disk numbers + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); - } -} + // number of entries + this.write(zipUtil.getEightBytes(this._entries.length)); + this.write(zipUtil.getEightBytes(this._entries.length)); -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -function Event(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now(), - }); + // length and location of CD + this.write(zipUtil.getEightBytes(this._archive.centralLength)); + this.write(zipUtil.getEightBytes(this._archive.centralOffset)); - // https://heycam.github.io/webidl/#Unforgeable - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + // extensible data sector + // not implemented at this time - // Define accessors - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); - } - } -} + // end of central directory locator + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); -// Should be enumerable, but class methods are not enumerable. -Event.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type - }, + // disk number holding the ZIP64 EOCD record + this.write(constants.LONG_ZERO); - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget - }, + // relative offset of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget - }, + // total number of disks + this.write(zipUtil.getLongBytes(1)); +}; - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return [] - } - return [currentTarget] - }, +ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var fileOffset = ae._offsets.file; - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0 - }, + var size = ae.getSize(); + var compressedSize = ae.getCompressedSize(); - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1 - }, + if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) { + size = constants.ZIP64_MAGIC; + compressedSize = constants.ZIP64_MAGIC; + fileOffset = constants.ZIP64_MAGIC; - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2 - }, + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3 - }, + var extraBuf = Buffer.concat([ + zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), + zipUtil.getShortBytes(24), + zipUtil.getEightBytes(ae.getSize()), + zipUtil.getEightBytes(ae.getCompressedSize()), + zipUtil.getEightBytes(ae._offsets.file) + ], 28); - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase - }, + ae.setExtra(extraBuf); + } - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); + // signature + this.write(zipUtil.getLongBytes(constants.SIG_CFH)); - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); - } - }, + // version made by + this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); - } - }, + // compression method + this.write(zipUtil.getShortBytes(method)); - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles) - }, + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable) - }, + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, + // sizes + this.write(zipUtil.getLongBytes(compressedSize)); + this.write(zipUtil.getLongBytes(size)); - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled - }, + var name = ae.getName(); + var comment = ae.getComment(); + var extra = ae.getCentralDirectoryExtra(); - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed) - }, + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); + comment = Buffer.from(comment); + } - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp - }, + // name length + this.write(zipUtil.getShortBytes(name.length)); - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget - }, + // extra length + this.write(zipUtil.getShortBytes(extra.length)); - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped - }, - set cancelBubble(value) { - if (!value) { - return - } - const data = pd(this); + // comments length + this.write(zipUtil.getShortBytes(comment.length)); - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; - } - }, + // disk number start + this.write(constants.SHORT_ZERO); - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); - } - }, + // internal attributes + this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - // Do nothing. - }, + // external attributes + this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); + + // relative offset of LFH + this.write(zipUtil.getLongBytes(fileOffset)); + + // name + this.write(name); + + // extra + this.write(extra); + + // comment + this.write(comment); +}; + +ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_DD)); + + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); + + // sizes + if (ae.isZip64()) { + this.write(zipUtil.getEightBytes(ae.getCompressedSize())); + this.write(zipUtil.getEightBytes(ae.getSize())); + } else { + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); + } }; -// `constructor` is not enumerable. -Object.defineProperty(Event.prototype, "constructor", { - value: Event, - configurable: true, - writable: true, -}); +ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var name = ae.getName(); + var extra = ae.getLocalFileDataExtra(); + + if (ae.isZip64()) { + gpb.useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + } + + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); + } + + ae._offsets.file = this.offset; + + // signature + this.write(zipUtil.getLongBytes(constants.SIG_LFH)); + + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); + + // compression method + this.write(zipUtil.getShortBytes(method)); + + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); + + ae._offsets.data = this.offset; + + // crc32 checksum and sizes + if (gpb.usesDataDescriptor()) { + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + } else { + this.write(zipUtil.getLongBytes(ae.getCrc())); + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); + } + + // name length + this.write(zipUtil.getShortBytes(name.length)); -// Ensure `event instanceof window.Event` is `true`. -if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event.prototype, window.Event.prototype); + // extra length + this.write(zipUtil.getShortBytes(extra.length)); - // Make association for wrappers. - wrappers.set(window.Event.prototype, Event); -} + // name + this.write(name); -/** - * Get the property descriptor to redirect a given property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to redirect the property. - * @private - */ -function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key] - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true, - } -} + // extra + this.write(extra); -/** - * Get the property descriptor to call a given method property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to call the method property. - * @private - */ -function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments) - }, - configurable: true, - enumerable: true, - } -} + ae._offsets.contents = this.offset; +}; -/** - * Define new wrapper class. - * @param {Function} BaseEvent The base wrapper class. - * @param {Object} proto The prototype of the original event. - * @returns {Function} The defined wrapper class. - * @private - */ -function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent - } +ZipArchiveOutputStream.prototype.getComment = function(comment) { + return this._archive.comment !== null ? this._archive.comment : ''; +}; - /** CustomEvent */ - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); - } +ZipArchiveOutputStream.prototype.isZip64 = function() { + return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; +}; - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true }, - }); +ZipArchiveOutputStream.prototype.setComment = function(comment) { + this._archive.comment = comment; +}; - // Define accessors. - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc - ? defineCallDescriptor(key) - : defineRedirectDescriptor(key) - ); - } - } - return CustomEvent -} +/***/ }), + +/***/ 25445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Get the wrapper class of a given prototype. - * @param {Object} proto The prototype of the original event to get its wrapper. - * @returns {Function} The wrapper class. - * @private + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event - } +module.exports = { + ArchiveEntry: __nccwpck_require__(92240), + ZipArchiveEntry: __nccwpck_require__(3179), + ArchiveOutputStream: __nccwpck_require__(36728), + ZipArchiveOutputStream: __nccwpck_require__(44432) +}; - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); - } - return wrapper -} +/***/ }), -/** - * Wrap a given event to management a dispatching. - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Object} event The event to wrap. - * @returns {Event} The wrapper instance. - * @private - */ -function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event) -} +/***/ 95208: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Get the immediateStopped flag of a given event. - * @param {Event} event The event to get. - * @returns {boolean} The flag to stop propagation immediately. - * @private + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -function isStopped(event) { - return pd(event).immediateStopped -} +var Stream = (__nccwpck_require__(12781).Stream); +var PassThrough = (__nccwpck_require__(45193).PassThrough); +var isStream = __nccwpck_require__(41554); -/** - * Set the current event phase of a given event. - * @param {Event} event The event to set current target. - * @param {number} eventPhase New event phase. - * @returns {void} - * @private - */ -function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; -} +var util = module.exports = {}; -/** - * Set the current target of a given event. - * @param {Event} event The event to set current target. - * @param {EventTarget|null} currentTarget New current target. - * @returns {void} - * @private - */ -function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; -} +util.normalizeInputSource = function(source) { + if (source === null) { + return Buffer.alloc(0); + } else if (typeof source === 'string') { + return Buffer.from(source); + } else if (isStream(source) && !source._readableState) { + var normalized = new PassThrough(); + source.pipe(normalized); -/** - * Set a passive listener of a given event. - * @param {Event} event The event to set current target. - * @param {Function|null} passiveListener New passive listener. - * @returns {void} - * @private - */ -function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; -} + return normalized; + } -/** - * @typedef {object} ListenerNode - * @property {Function} listener - * @property {1|2|3} listenerType - * @property {boolean} passive - * @property {boolean} once - * @property {ListenerNode|null} next - * @private - */ + return source; +}; -/** - * @type {WeakMap>} - * @private - */ -const listenersMap = new WeakMap(); +/***/ }), -// Listener types -const CAPTURE = 1; -const BUBBLE = 2; -const ATTRIBUTE = 3; +/***/ 84322: +/***/ ((__unused_webpack_module, exports) => { -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax -} +"use strict"; -/** - * Get listeners. - * @param {EventTarget} eventTarget The event target to get. - * @returns {Map} The listeners. - * @private - */ -function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." - ) +exports.__esModule = true; +function binaryOperation(operator, left, right) { + switch (operator) { + case '+': + return left + right; + case '-': + return left - right; + case '/': + return left / right; + case '%': + return left % right; + case '*': + return left * right; + case '**': + return Math.pow(left, right); + case '&': + return left & right; + case '|': + return left | right; + case '>>': + return left >> right; + case '>>>': + return left >>> right; + case '<<': + return left << right; + case '^': + return left ^ right; + case '==': + return left == right; + case '===': + return left === right; + case '!=': + return left != right; + case '!==': + return left !== right; + case 'in': + return left in right; + case 'instanceof': + return left instanceof right; + case '>': + return left > right; + case '<': + return left < right; + case '>=': + return left >= right; + case '<=': + return left <= right; } - return listeners } +exports["default"] = binaryOperation; -/** - * Get the property descriptor for the event attribute of a given event. - * @param {string} eventName The event name to get property descriptor. - * @returns {PropertyDescriptor} The property descriptor. - * @private - */ -function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener + +/***/ }), + +/***/ 40953: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + +exports.__esModule = true; +var parser_1 = __nccwpck_require__(85026); +var b = __nccwpck_require__(7912); +var binaryOperation_1 = __nccwpck_require__(84322); +function expressionToConstant(expression, options) { + if (options === void 0) { options = {}; } + var constant = true; + function toConstant(expression) { + if (!constant) + return; + if (b.isArrayExpression(expression)) { + var result_1 = []; + for (var i = 0; constant && i < expression.elements.length; i++) { + var element = expression.elements[i]; + if (b.isSpreadElement(element)) { + var spread = toConstant(element.argument); + if (!(isSpreadable(spread) && constant)) { + constant = false; + } + else { + result_1.push.apply(result_1, spread); + } + } + else if (b.isExpression(element)) { + result_1.push(toConstant(element)); + } + else { + constant = false; } - node = node.next; } - return null - }, - - set(listener) { - if (typeof listener !== "function" && !isObject(listener)) { - listener = null; // eslint-disable-line no-param-reassign + return result_1; + } + if (b.isBinaryExpression(expression)) { + var left = toConstant(expression.left); + var right = toConstant(expression.right); + return constant && binaryOperation_1["default"](expression.operator, left, right); + } + if (b.isBooleanLiteral(expression)) { + return expression.value; + } + if (b.isCallExpression(expression)) { + var args = []; + for (var i = 0; constant && i < expression.arguments.length; i++) { + var arg = expression.arguments[i]; + if (b.isSpreadElement(arg)) { + var spread = toConstant(arg.argument); + if (!(isSpreadable(spread) && constant)) { + constant = false; + } + else { + args.push.apply(args, spread); + } + } + else if (b.isExpression(arg)) { + args.push(toConstant(arg)); + } + else { + constant = false; + } } - const listeners = getListeners(this); - - // Traverse to the tail while removing old value. - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - // Remove old value. - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); + if (!constant) + return; + if (b.isMemberExpression(expression.callee)) { + var object = toConstant(expression.callee.object); + if (!object || !constant) { + constant = false; + return; + } + var member = expression.callee.computed + ? toConstant(expression.callee.property) + : b.isIdentifier(expression.callee.property) + ? expression.callee.property.name + : undefined; + if (member === undefined && !expression.callee.computed) { + constant = false; + } + if (!constant) + return; + if (canCallMethod(object, '' + member)) { + return object[member].apply(object, args); + } + } + else { + if (!b.isExpression(expression.callee)) { + constant = false; + return; + } + var callee = toConstant(expression.callee); + if (!constant) + return; + return callee.apply(null, args); + } + } + if (b.isConditionalExpression(expression)) { + var test = toConstant(expression.test); + return test + ? toConstant(expression.consequent) + : toConstant(expression.alternate); + } + if (b.isIdentifier(expression)) { + if (options.constants && + {}.hasOwnProperty.call(options.constants, expression.name)) { + return options.constants[expression.name]; + } + } + if (b.isLogicalExpression(expression)) { + var left = toConstant(expression.left); + var right = toConstant(expression.right); + if (constant && expression.operator === '&&') { + return left && right; + } + if (constant && expression.operator === '||') { + return left || right; + } + } + if (b.isMemberExpression(expression)) { + var object = toConstant(expression.object); + if (!object || !constant) { + constant = false; + return; + } + var member = expression.computed + ? toConstant(expression.property) + : b.isIdentifier(expression.property) + ? expression.property.name + : undefined; + if (member === undefined && !expression.computed) { + constant = false; + } + if (!constant) + return; + if ({}.hasOwnProperty.call(object, '' + member) && member[0] !== '_') { + return object[member]; + } + } + if (b.isNullLiteral(expression)) { + return null; + } + if (b.isNumericLiteral(expression)) { + return expression.value; + } + if (b.isObjectExpression(expression)) { + var result_2 = {}; + for (var i = 0; constant && i < expression.properties.length; i++) { + var property = expression.properties[i]; + if (b.isObjectProperty(property)) { + if (property.shorthand) { + constant = false; + return; + } + var key = property.computed + ? toConstant(property.key) + : b.isIdentifier(property.key) + ? property.key.name + : b.isStringLiteral(property.key) + ? property.key.value + : undefined; + if (!key || key[0] === '_') { + constant = false; + } + if (!constant) + return; + if (b.isExpression(property.value)) { + var value = toConstant(property.value); + if (!constant) + return; + result_2[key] = value; + } + else { + constant = false; } - } else { - prev = node; } - - node = node.next; + else if (b.isObjectMethod(property)) { + constant = false; + } + else if (b.isSpreadProperty(property)) { + var argument = toConstant(property.argument); + if (!argument) + constant = false; + if (!constant) + return; + Object.assign(result_2, argument); + } } - - // Add new value. - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null, - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; + return result_2; + } + if (b.isParenthesizedExpression(expression)) { + return toConstant(expression.expression); + } + if (b.isRegExpLiteral(expression)) { + return new RegExp(expression.pattern, expression.flags); + } + if (b.isSequenceExpression(expression)) { + for (var i = 0; i < expression.expressions.length - 1 && constant; i++) { + toConstant(expression.expressions[i]); + } + return toConstant(expression.expressions[expression.expressions.length - 1]); + } + if (b.isStringLiteral(expression)) { + return expression.value; + } + // TODO: TaggedTemplateExpression + if (b.isTemplateLiteral(expression)) { + var result_3 = ''; + for (var i = 0; i < expression.quasis.length; i++) { + var quasi = expression.quasis[i]; + result_3 += quasi.value.cooked; + if (i < expression.expressions.length) { + result_3 += '' + toConstant(expression.expressions[i]); } } - }, - configurable: true, - enumerable: true, + return result_3; + } + if (b.isUnaryExpression(expression)) { + var argument = toConstant(expression.argument); + if (!constant) { + return; + } + switch (expression.operator) { + case '-': + return -argument; + case '+': + return +argument; + case '!': + return !argument; + case '~': + return ~argument; + case 'typeof': + return typeof argument; + case 'void': + return void argument; + } + } + constant = false; } + var result = toConstant(expression); + return constant ? { constant: true, result: result } : { constant: false }; } - -/** - * Define an event attribute (e.g. `eventTarget.onclick`). - * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. - * @param {string} eventName The event name to define. - * @returns {void} - */ -function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); +exports.expressionToConstant = expressionToConstant; +function isSpreadable(value) { + return (typeof value === 'string' || + Array.isArray(value) || + (typeof Set !== 'undefined' && value instanceof Set) || + (typeof Map !== 'undefined' && value instanceof Map)); } - -/** - * Define a custom EventTarget with event attributes. - * @param {string[]} eventNames Event names for event attributes. - * @returns {EventTarget} The custom EventTarget. - * @private - */ -function defineCustomEventTarget(eventNames) { - /** CustomEventTarget */ - function CustomEventTarget() { - EventTarget.call(this); +function shallowEqual(a, b) { + if (a === b) + return true; + if (a && b && typeof a === 'object' && typeof b === 'object') { + for (var key in a) { + if (a[key] !== b[key]) { + return false; + } + } + for (var key in b) { + if (a[key] !== b[key]) { + return false; + } + } + return true; } - - CustomEventTarget.prototype = Object.create(EventTarget.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true, - }, - }); - - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + return false; +} +function canCallMethod(object, member) { + switch (typeof object) { + case 'boolean': + switch (member) { + case 'toString': + return true; + default: + return false; + } + case 'number': + switch (member) { + case 'toExponential': + case 'toFixed': + case 'toPrecision': + case 'toString': + return true; + default: + return false; + } + case 'string': + switch (member) { + case 'charAt': + case 'charCodeAt': + case 'codePointAt': + case 'concat': + case 'endsWith': + case 'includes': + case 'indexOf': + case 'lastIndexOf': + case 'match': + case 'normalize': + case 'padEnd': + case 'padStart': + case 'repeat': + case 'replace': + case 'search': + case 'slice': + case 'split': + case 'startsWith': + case 'substr': + case 'substring': + case 'toLowerCase': + case 'toUpperCase': + case 'trim': + return true; + default: + return false; + } + default: + if (object instanceof RegExp) { + switch (member) { + case 'test': + case 'exec': + return true; + default: + return false; + } + } + return {}.hasOwnProperty.call(object, member) && member[0] !== '_'; } - - return CustomEventTarget } - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - * class B extends EventTarget("message") {} - * class C extends EventTarget("message", "error") {} - * class D extends EventTarget(["message", "error"]) {} - */ -function EventTarget() { - /*eslint-disable consistent-return */ - if (this instanceof EventTarget) { - listenersMap.set(this, new Map()); - return +var EMPTY_OBJECT = {}; +var lastSrc = ''; +var lastConstants = EMPTY_OBJECT; +var lastOptions = EMPTY_OBJECT; +var lastResult = null; +var lastWasConstant = false; +function isConstant(src, constants, options) { + if (constants === void 0) { constants = EMPTY_OBJECT; } + if (options === void 0) { options = EMPTY_OBJECT; } + if (lastSrc === src && + shallowEqual(lastConstants, constants) && + shallowEqual(lastOptions, options)) { + return lastWasConstant; } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]) + lastSrc = src; + lastConstants = constants; + var ast; + try { + ast = parser_1.parseExpression(src, options); } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types) + catch (ex) { + return (lastWasConstant = false); } - throw new TypeError("Cannot call a class as a function") - /*eslint-enable consistent-return */ + var _a = expressionToConstant(ast, { constants: constants }), result = _a.result, constant = _a.constant; + lastResult = result; + return (lastWasConstant = constant); } +exports.isConstant = isConstant; +function toConstant(src, constants, options) { + if (constants === void 0) { constants = EMPTY_OBJECT; } + if (options === void 0) { options = EMPTY_OBJECT; } + if (!isConstant(src, constants, options)) { + throw new Error(JSON.stringify(src) + ' is not constant.'); + } + return lastResult; +} +exports.toConstant = toConstant; +exports["default"] = isConstant; +module.exports = isConstant; +module.exports["default"] = isConstant; +module.exports.expressionToConstant = expressionToConstant; +module.exports.isConstant = isConstant; +module.exports.toConstant = toConstant; -// Should be enumerable, but class methods are not enumerable. -EventTarget.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = getListeners(this); - const optionsIsObj = isObject(options); - const capture = optionsIsObj - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - }; - // Set it as the first node if the first node is null. - let node = listeners.get(eventName); - if (node === undefined) { - listeners.set(eventName, newNode); - return - } +/***/ }), - // Traverse to the tail while checking duplication.. - let prev = null; - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - // Should ignore duplication. - return - } - prev = node; - node = node.next; - } +/***/ 95898: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Add it. - prev.next = newNode; - }, +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return - } +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. - const listeners = getListeners(this); - const capture = isObject(options) - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return - } +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - prev = node; - node = node.next; - } - }, +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.') - } +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - // If listeners aren't registered, terminate. - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true - } +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - // Since we cannot rewrite several properties, so wrap object. - const wrappedEvent = wrapEvent(this, event); +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null; - while (node != null) { - // Remove this listener if it's once - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - // Call this listener - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error(err); - } - } - } else if ( - node.listenerType !== ATTRIBUTE && - typeof node.listener.handleEvent === "function" - ) { - node.listener.handleEvent(wrappedEvent); - } +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; - // Break if `event.stopImmediatePropagation` was called. - if (isStopped(wrappedEvent)) { - break - } +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - node = node.next; - } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; - return !wrappedEvent.defaultPrevented - }, -}; +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -// `constructor` is not enumerable. -Object.defineProperty(EventTarget.prototype, "constructor", { - value: EventTarget, - configurable: true, - writable: true, -}); +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -// Ensure `eventTarget instanceof window.EventTarget` is `true`. -if ( - typeof window !== "undefined" && - typeof window.EventTarget !== "undefined" -) { - Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } +exports.isPrimitive = isPrimitive; -exports.defineEventAttribute = defineEventAttribute; -exports.EventTarget = EventTarget; -exports["default"] = EventTarget; +exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; -module.exports = EventTarget -module.exports.EventTarget = module.exports["default"] = EventTarget -module.exports.defineEventAttribute = defineEventAttribute -//# sourceMappingURL=event-target-shim.js.map +function objectToString(o) { + return Object.prototype.toString.call(o); +} /***/ }), -/***/ 11848: -/***/ ((module) => { +/***/ 83201: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* vim: set ts=2: */ +/*exported CRC32 */ +var CRC32; +(function (factory) { + /*jshint ignore:start */ + /*eslint-disable */ + if(typeof DO_NOT_EXPORT_CRC === 'undefined') { + if(true) { + factory(exports); + } else {} + } else { + factory(CRC32 = {}); + } + /*eslint-enable */ + /*jshint ignore:end */ +}(function(CRC32) { +CRC32.version = '1.2.2'; +/*global Int32Array */ +function signed_crc_table() { + var c = 0, table = new Array(256); + for(var n =0; n != 256; ++n){ + c = n; + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + table[n] = c; + } -var has = Object.prototype.hasOwnProperty - , prefix = '~'; + return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; +} -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} +var T0 = signed_crc_table(); +function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); + for(n = 0; n != 256; ++n) table[n] = T[n]; + for(n = 0; n != 256; ++n) { + v = T[n]; + for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; + } + var out = []; + for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; +} +var TT = slice_by_16_tables(T0); +var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; +var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; +var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; +function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; + return ~C; +} - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; +function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for(; i < L;) C = + Tf[B[i++] ^ (C & 255)] ^ + Te[B[i++] ^ ((C >> 8) & 255)] ^ + Td[B[i++] ^ ((C >> 16) & 255)] ^ + Tc[B[i++] ^ (C >>> 24)] ^ + Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ + T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ + T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; + return ~C; } -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; +function crc32_str(str, seed) { + var C = seed ^ -1; + for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { + c = str.charCodeAt(i++); + if(c < 0x80) { + C = (C>>>8) ^ T0[(C^c)&0xFF]; + } else if(c < 0x800) { + C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } else if(c >= 0xD800 && c < 0xE000) { + c = (c&1023)+64; d = str.charCodeAt(i++)&1023; + C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; + } else { + C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } + } + return ~C; } +CRC32.table = T0; +// $FlowIgnore +CRC32.bstr = crc32_bstr; +// $FlowIgnore +CRC32.buf = crc32_buf; +// $FlowIgnore +CRC32.str = crc32_str; +})); + + +/***/ }), + +/***/ 94521: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /** - * Add a listener for a given event. + * node-crc32-stream * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; + - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; +const {Transform} = __nccwpck_require__(45193); - return emitter; -} +const crc32 = __nccwpck_require__(83201); -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} +class CRC32Stream extends Transform { + constructor(options) { + super(options); + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} + this.rawSize = 0; + } -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; + } - if (this._eventsCount === 0) return names; + callback(null, chunk); + } - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + hex() { + return this.digest('hex').toUpperCase(); } - return names; -}; + size() { + return this.rawSize; + } +} -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; +module.exports = CRC32Stream; - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } +/***/ }), - return ee; -}; +/***/ 92563: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; /** - * Return the number of listeners listening to a given event. + * node-crc32-stream * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return false; +const {DeflateRaw} = __nccwpck_require__(59796); - var listeners = this._events[evt] - , len = arguments.length - , args - , i; +const crc32 = __nccwpck_require__(83201); - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); +class DeflateCRC32Stream extends DeflateRaw { + constructor(options) { + super(options); - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); + + this.rawSize = 0; + this.compressedSize = 0; + } + + push(chunk, encoding) { + if (chunk) { + this.compressedSize += chunk.length; } - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; + return super.push(chunk, encoding); + } + + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; + super._transform(chunk, encoding, callback) + } - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; + } - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + hex() { + return this.digest('hex').toUpperCase(); + } - listeners[i].fn.apply(listeners[i].context, args); - } + size(compressed = false) { + if (compressed) { + return this.compressedSize; + } else { + return this.rawSize; } } +} - return true; -}; +module.exports = DeflateCRC32Stream; -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; +/***/ }), +/***/ 5101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; /** - * Remove the listeners of a given event. + * node-crc32-stream * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - var listeners = this._events[evt]; - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } +module.exports = { + CRC32Stream: __nccwpck_require__(94521), + DeflateCRC32Stream: __nccwpck_require__(92563) +} - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - return this; -}; +/***/ }), -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; +/***/ 72746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } +"use strict"; - return this; -}; -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; +const cp = __nccwpck_require__(32081); +const parse = __nccwpck_require__(66855); +const enoent = __nccwpck_require__(44101); -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; } +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); -/***/ }), + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); -/***/ 27030: -/***/ ((module) => { + return result; +} -module.exports = class FixedFIFO { - constructor (hwm) { - if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') - this.buffer = new Array(hwm) - this.mask = hwm - 1 - this.top = 0 - this.btm = 0 - this.next = null - } +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; - clear () { - this.top = this.btm = 0 - this.next = null - this.buffer.fill(undefined) - } +module.exports._parse = parse; +module.exports._enoent = enoent; - push (data) { - if (this.buffer[this.top] !== undefined) return false - this.buffer[this.top] = data - this.top = (this.top + 1) & this.mask - return true - } - shift () { - const last = this.buffer[this.btm] - if (last === undefined) return undefined - this.buffer[this.btm] = undefined - this.btm = (this.btm + 1) & this.mask - return last - } +/***/ }), - peek () { - return this.buffer[this.btm] - } +/***/ 44101: +/***/ ((module) => { - isEmpty () { - return this.buffer[this.btm] === undefined - } -} +"use strict"; -/***/ }), +const isWin = process.platform === 'win32'; -/***/ 92958: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} -const FixedFIFO = __nccwpck_require__(27030) +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } -module.exports = class FastFIFO { - constructor (hwm) { - this.hwm = hwm || 16 - this.head = new FixedFIFO(this.hwm) - this.tail = this.head - this.length = 0 - } + const originalEmit = cp.emit; - clear () { - this.head = this.tail - this.head.clear() - this.length = 0 - } + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed, 'spawn'); - push (val) { - this.length++ - if (!this.head.push(val)) { - const prev = this.head - this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length) - this.head.push(val) - } - } + if (err) { + return originalEmit.call(cp, 'error', err); + } + } - shift () { - if (this.length !== 0) this.length-- - const val = this.tail.shift() - if (val === undefined && this.tail.next) { - const next = this.tail.next - this.tail.next = null - this.tail = next - return this.tail.shift() + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); } - return val - } + return null; +} - peek () { - const val = this.tail.peek() - if (val === undefined && this.tail.next) return this.tail.next.peek() - return val - } +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } - isEmpty () { - return this.length === 0 - } + return null; } +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + /***/ }), -/***/ 43664: +/***/ 66855: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const taskManager = __nccwpck_require__(42708); -const async_1 = __nccwpck_require__(95679); -const stream_1 = __nccwpck_require__(94630); -const sync_1 = __nccwpck_require__(42405); -const settings_1 = __nccwpck_require__(10952); -const utils = __nccwpck_require__(45444); -async function FastGlob(source, options) { - assertPatternsInput(source); - const works = getWorks(source, async_1.default, options); - const result = await Promise.all(works); - return utils.array.flatten(result); -} -// https://github.com/typescript-eslint/typescript-eslint/issues/60 -// eslint-disable-next-line no-redeclare -(function (FastGlob) { - FastGlob.glob = FastGlob; - FastGlob.globSync = sync; - FastGlob.globStream = stream; - FastGlob.async = FastGlob; - function sync(source, options) { - assertPatternsInput(source); - const works = getWorks(source, sync_1.default, options); - return utils.array.flatten(works); - } - FastGlob.sync = sync; - function stream(source, options) { - assertPatternsInput(source); - const works = getWorks(source, stream_1.default, options); - /** - * The stream returned by the provider cannot work with an asynchronous iterator. - * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. - * This affects performance (+25%). I don't see best solution right now. - */ - return utils.stream.merge(works); - } - FastGlob.stream = stream; - function generateTasks(source, options) { - assertPatternsInput(source); - const patterns = [].concat(source); - const settings = new settings_1.default(options); - return taskManager.generate(patterns, settings); - } - FastGlob.generateTasks = generateTasks; - function isDynamicPattern(source, options) { - assertPatternsInput(source); - const settings = new settings_1.default(options); - return utils.pattern.isDynamicPattern(source, settings); - } - FastGlob.isDynamicPattern = isDynamicPattern; - function escapePath(source) { - assertPatternsInput(source); - return utils.path.escape(source); - } - FastGlob.escapePath = escapePath; - function convertPathToPattern(source) { - assertPatternsInput(source); - return utils.path.convertPathToPattern(source); - } - FastGlob.convertPathToPattern = convertPathToPattern; - let posix; - (function (posix) { - function escapePath(source) { - assertPatternsInput(source); - return utils.path.escapePosixPath(source); - } - posix.escapePath = escapePath; - function convertPathToPattern(source) { - assertPatternsInput(source); - return utils.path.convertPosixPathToPattern(source); - } - posix.convertPathToPattern = convertPathToPattern; - })(posix = FastGlob.posix || (FastGlob.posix = {})); - let win32; - (function (win32) { - function escapePath(source) { - assertPatternsInput(source); - return utils.path.escapeWindowsPath(source); - } - win32.escapePath = escapePath; - function convertPathToPattern(source) { - assertPatternsInput(source); - return utils.path.convertWindowsPathToPattern(source); - } - win32.convertPathToPattern = convertPathToPattern; - })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); -})(FastGlob || (FastGlob = {})); -function getWorks(source, _Provider, options) { - const patterns = [].concat(source); - const settings = new settings_1.default(options); - const tasks = taskManager.generate(patterns, settings); - const provider = new _Provider(settings); - return tasks.map(provider.read, provider); -} -function assertPatternsInput(input) { - const source = [].concat(input); - const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); - if (!isValidSource) { - throw new TypeError('Patterns must be a string (non empty) or an array of strings'); - } -} -module.exports = FastGlob; +const path = __nccwpck_require__(71017); +const resolveCommand = __nccwpck_require__(87274); +const escape = __nccwpck_require__(34274); +const readShebang = __nccwpck_require__(41252); -/***/ }), +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; -/***/ 42708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); -"use strict"; + const shebang = parsed.file && readShebang(parsed.file); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; -const utils = __nccwpck_require__(45444); -function generate(input, settings) { - const patterns = processPatterns(input, settings); - const ignore = processPatterns(settings.ignore, settings); - const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); - const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); - const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); - const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); - const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); - return staticTasks.concat(dynamicTasks); -} -exports.generate = generate; -function processPatterns(input, settings) { - let patterns = input; - /** - * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry - * and some problems with the micromatch package (see fast-glob issues: #365, #394). - * - * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown - * in matching in the case of a large set of patterns after expansion. - */ - if (settings.braceExpansion) { - patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); - } - /** - * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used - * at any nesting level. - * - * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change - * the pattern in the filter before creating a regular expression. There is no need to change the patterns - * in the application. Only on the input. - */ - if (settings.baseNameMatch) { - patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); } - /** - * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. - */ - return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); + + return parsed.file; } -/** - * Returns tasks grouped by basic pattern directories. - * - * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. - * This is necessary because directory traversal starts at the base directory and goes deeper. - */ -function convertPatternsToTasks(positive, negative, dynamic) { - const tasks = []; - const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); - const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); - const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); - const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); - tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); - /* - * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory - * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. - */ - if ('.' in insideCurrentDirectoryGroup) { - tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); - } - else { - tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; } - return tasks; -} -exports.convertPatternsToTasks = convertPatternsToTasks; -function getPositivePatterns(patterns) { - return utils.pattern.getPositivePatterns(patterns); -} -exports.getPositivePatterns = getPositivePatterns; -function getNegativePatternsAsPositive(patterns, ignore) { - const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); - const positive = negative.map(utils.pattern.convertToPositivePattern); - return positive; -} -exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; -function groupPatternsByBaseDirectory(patterns) { - const group = {}; - return patterns.reduce((collection, pattern) => { - const base = utils.pattern.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } - else { - collection[base] = [pattern]; - } - return collection; - }, group); -} -exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; -function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map((base) => { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); -} -exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; -function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - dynamic, - positive, - negative, - base, - patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) - }; -} -exports.convertPatternGroupToTask = convertPatternGroupToTask; + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); -/***/ }), + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); -/***/ 95679: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); -"use strict"; + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const async_1 = __nccwpck_require__(97747); -const provider_1 = __nccwpck_require__(60257); -class ProviderAsync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new async_1.default(this._settings); - } - async read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = await this.api(root, task, options); - return entries.map((entry) => options.transform(entry)); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } -} -exports["default"] = ProviderAsync; + return parsed; +} -/***/ }), +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } -/***/ 36983: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original -"use strict"; + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(45444); -const partial_1 = __nccwpck_require__(35295); -class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const matcher = this._getMatcher(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, matcher, negativeRe); - } - _getMatcher(patterns) { - return new partial_1.default(patterns, this._settings, this._micromatchOptions); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); - return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, matcher, negativeRe) { - if (this._isSkippedByDeep(basePath, entry.path)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - const filepath = utils.path.removeLeadingDotSegment(entry.path); - if (this._isSkippedByPositivePatterns(filepath, matcher)) { - return false; - } - return this._isSkippedByNegativePatterns(filepath, negativeRe); - } - _isSkippedByDeep(basePath, entryPath) { - /** - * Avoid unnecessary depth calculations when it doesn't matter. - */ - if (this._settings.deep === Infinity) { - return false; - } - return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; - } - _getEntryLevel(basePath, entryPath) { - const entryPathDepth = entryPath.split('/').length; - if (basePath === '') { - return entryPathDepth; - } - const basePathDepth = basePath.split('/').length; - return entryPathDepth - basePathDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); - } - _isSkippedByPositivePatterns(entryPath, matcher) { - return !this._settings.baseNameMatch && !matcher.match(entryPath); - } - _isSkippedByNegativePatterns(entryPath, patternsRe) { - return !utils.pattern.matchAny(entryPath, patternsRe); - } + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); } -exports["default"] = DeepFilter; + +module.exports = parse; /***/ }), -/***/ 71343: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 34274: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(45444); -class EntryFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this.index = new Map(); - } - getFilter(positive, negative) { - const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); - return (entry) => this._filter(entry, positiveRe, negativeRe); - } - _filter(entry, positiveRe, negativeRe) { - const filepath = utils.path.removeLeadingDotSegment(entry.path); - if (this._settings.unique && this._isDuplicateEntry(filepath)) { - return false; - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { - return false; - } - const isDirectory = entry.dirent.isDirectory(); - const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); - if (this._settings.unique && isMatched) { - this._createIndexRecord(filepath); - } - return isMatched; - } - _isDuplicateEntry(filepath) { - return this.index.has(filepath); - } - _createIndexRecord(filepath) { - this.index.set(filepath, undefined); - } - _onlyFileFilter(entry) { - return this._settings.onlyFiles && !entry.dirent.isFile(); - } - _onlyDirectoryFilter(entry) { - return this._settings.onlyDirectories && !entry.dirent.isDirectory(); - } - _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { - if (!this._settings.absolute) { - return false; - } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); - return utils.pattern.matchAny(fullpath, patternsRe); - } - _isMatchToPatterns(filepath, patternsRe, isDirectory) { - // Trying to match files and directories by patterns. - const isMatched = utils.pattern.matchAny(filepath, patternsRe); - // A pattern with a trailling slash can be used for directory matching. - // To apply such pattern, we need to add a tralling slash to the path. - if (!isMatched && isDirectory) { - return utils.pattern.matchAny(filepath + '/', patternsRe); - } - return isMatched; - } + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; } -exports["default"] = EntryFilter; +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; -/***/ }), + // Algorithm below is based on https://qntm.org/cmd -/***/ 36654: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); -"use strict"; + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(45444); -class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error) => this._isNonFatalError(error); - } - _isNonFatalError(error) { - return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); } + + return arg; } -exports["default"] = ErrorFilter; + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; /***/ }), -/***/ 32576: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41252: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(45444); -class Matcher { - constructor(_patterns, _settings, _micromatchOptions) { - this._patterns = _patterns; - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this._storage = []; - this._fillStorage(); - } - _fillStorage() { - for (const pattern of this._patterns) { - const segments = this._getPatternSegments(pattern); - const sections = this._splitSegmentsIntoSections(segments); - this._storage.push({ - complete: sections.length <= 1, - pattern, - segments, - sections - }); - } - } - _getPatternSegments(pattern) { - const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); - return parts.map((part) => { - const dynamic = utils.pattern.isDynamicPattern(part, this._settings); - if (!dynamic) { - return { - dynamic: false, - pattern: part - }; - } - return { - dynamic: true, - pattern: part, - patternRe: utils.pattern.makeRe(part, this._micromatchOptions) - }; - }); - } - _splitSegmentsIntoSections(segments) { - return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); - } -} -exports["default"] = Matcher; +const fs = __nccwpck_require__(57147); +const shebangCommand = __nccwpck_require__(67032); -/***/ }), +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); -/***/ 35295: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + let fd; -"use strict"; + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const matcher_1 = __nccwpck_require__(32576); -class PartialMatcher extends matcher_1.default { - match(filepath) { - const parts = filepath.split('/'); - const levels = parts.length; - const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); - for (const pattern of patterns) { - const section = pattern.sections[0]; - /** - * In this case, the pattern has a globstar and we must read all directories unconditionally, - * but only if the level has reached the end of the first group. - * - * fixtures/{a,b}/** - * ^ true/false ^ always true - */ - if (!pattern.complete && levels > section.length) { - return true; - } - const match = parts.every((part, index) => { - const segment = pattern.segments[index]; - if (segment.dynamic && segment.patternRe.test(part)) { - return true; - } - if (!segment.dynamic && segment.pattern === part) { - return true; - } - return false; - }); - if (match) { - return true; - } - } - return false; - } + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); } -exports["default"] = PartialMatcher; + +module.exports = readShebang; /***/ }), -/***/ 60257: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87274: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); + const path = __nccwpck_require__(71017); -const deep_1 = __nccwpck_require__(36983); -const entry_1 = __nccwpck_require__(71343); -const error_1 = __nccwpck_require__(36654); -const entry_2 = __nccwpck_require__(94029); -class Provider { - constructor(_settings) { - this._settings = _settings; - this.errorFilter = new error_1.default(this._settings); - this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); - this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); - this.entryTransformer = new entry_2.default(this._settings); - } - _getRootDirectory(task) { - return path.resolve(this._settings.cwd, task.base); +const which = __nccwpck_require__(34207); +const getPathKey = __nccwpck_require__(20539); + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } } - _getReaderOptions(task) { - const basePath = task.base === '.' ? '' : task.base; - return { - basePath, - pathSegmentSeparator: '/', - concurrency: this._settings.concurrency, - deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), - entryFilter: this.entryFilter.getFilter(task.positive, task.negative), - errorFilter: this.errorFilter.getFilter(), - followSymbolicLinks: this._settings.followSymbolicLinks, - fs: this._settings.fs, - stats: this._settings.stats, - throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, - transform: this.entryTransformer.getTransformer() - }; + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } } - _getMicromatchOptions() { - return { - dot: this._settings.dot, - matchBase: this._settings.baseNameMatch, - nobrace: !this._settings.braceExpansion, - nocase: !this._settings.caseSensitiveMatch, - noext: !this._settings.extglob, - noglobstar: !this._settings.globstar, - posix: true, - strictSlashes: false - }; + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } + + return resolved; } -exports["default"] = Provider; + +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +module.exports = resolveCommand; /***/ }), -/***/ 94630: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 84697: +/***/ ((module) => { -"use strict"; +/** + * Helpers. + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(12781); -const stream_2 = __nccwpck_require__(12083); -const provider_1 = __nccwpck_require__(60257); -class ProviderStream extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new stream_2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const source = this.api(root, task, options); - const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); - source - .once('error', (error) => destination.emit('error', error)) - .on('data', (entry) => destination.emit('data', options.transform(entry))) - .once('end', () => destination.emit('end')); - destination - .once('close', () => source.destroy()); - return destination; - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } -exports["default"] = ProviderStream; +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -/***/ }), +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} -/***/ 42405: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -"use strict"; +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -const sync_1 = __nccwpck_require__(76234); -const provider_1 = __nccwpck_require__(60257); -class ProviderSync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new sync_1.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = this.api(root, task, options); - return entries.map(options.transform); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -exports["default"] = ProviderSync; /***/ }), -/***/ 94029: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/* eslint-env browser */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(45444); -class EntryTransformer { - constructor(_settings) { - this._settings = _settings; - } - getTransformer() { - return (entry) => this._transform(entry); - } - _transform(entry) { - let filepath = entry.path; - if (this._settings.absolute) { - filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); - filepath = utils.path.unixify(filepath); - } - if (this._settings.markDirectories && entry.dirent.isDirectory()) { - filepath += '/'; - } - if (!this._settings.objectMode) { - return filepath; - } - return Object.assign(Object.assign({}, entry), { path: filepath }); - } +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -exports["default"] = EntryTransformer; +/** + * Colorize log arguments if enabled. + * + * @api public + */ -/***/ }), +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -/***/ 97747: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!this.useColors) { + return; + } -"use strict"; + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fsWalk = __nccwpck_require__(26026); -const reader_1 = __nccwpck_require__(65582); -const stream_1 = __nccwpck_require__(12083); -class ReaderAsync extends reader_1.default { - constructor() { - super(...arguments); - this._walkAsync = fsWalk.walk; - this._readerStream = new stream_1.default(this._settings); - } - dynamic(root, options) { - return new Promise((resolve, reject) => { - this._walkAsync(root, options, (error, entries) => { - if (error === null) { - resolve(entries); - } - else { - reject(error); - } - }); - }); - } - async static(patterns, options) { - const entries = []; - const stream = this._readerStream.static(patterns, options); - // After #235, replace it with an asynchronous iterator. - return new Promise((resolve, reject) => { - stream.once('error', reject); - stream.on('data', (entry) => entries.push(entry)); - stream.once('end', () => resolve(entries)); - }); - } + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } -exports["default"] = ReaderAsync; +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); -/***/ }), +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} -/***/ 65582: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -"use strict"; + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const path = __nccwpck_require__(71017); -const fsStat = __nccwpck_require__(70109); -const utils = __nccwpck_require__(45444); -class Reader { - constructor(_settings) { - this._settings = _settings; - this._fsStatSettings = new fsStat.Settings({ - followSymbolicLink: this._settings.followSymbolicLinks, - fs: this._settings.fs, - throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks - }); - } - _getFullEntryPath(filepath) { - return path.resolve(this._settings.cwd, filepath); - } - _makeEntry(stats, pattern) { - const entry = { - name: pattern, - path: pattern, - dirent: utils.fs.createDirentFromStats(pattern, stats) - }; - if (this._settings.stats) { - entry.stats = stats; - } - return entry; - } - _isFatalError(error) { - return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; - } + return r; } -exports["default"] = Reader; + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = __nccwpck_require__(46243)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; /***/ }), -/***/ 12083: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(12781); -const fsStat = __nccwpck_require__(70109); -const fsWalk = __nccwpck_require__(26026); -const reader_1 = __nccwpck_require__(65582); -class ReaderStream extends reader_1.default { - constructor() { - super(...arguments); - this._walkStream = fsWalk.walkStream; - this._stat = fsStat.stat; - } - dynamic(root, options) { - return this._walkStream(root, options); - } - static(patterns, options) { - const filepaths = patterns.map(this._getFullEntryPath, this); - const stream = new stream_1.PassThrough({ objectMode: true }); - stream._write = (index, _enc, done) => { - return this._getEntry(filepaths[index], patterns[index], options) - .then((entry) => { - if (entry !== null && options.entryFilter(entry)) { - stream.push(entry); - } - if (index === filepaths.length - 1) { - stream.end(); - } - done(); - }) - .catch(done); - }; - for (let i = 0; i < filepaths.length; i++) { - stream.write(i); - } - return stream; - } - _getEntry(filepath, pattern, options) { - return this._getStat(filepath) - .then((stats) => this._makeEntry(stats, pattern)) - .catch((error) => { - if (options.errorFilter(error)) { - return null; - } - throw error; - }); - } - _getStat(filepath) { - return new Promise((resolve, reject) => { - this._stat(filepath, this._fsStatSettings, (error, stats) => { - return error === null ? resolve(stats) : reject(error); - }); - }); - } -} -exports["default"] = ReaderStream; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(84697); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/***/ }), + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -/***/ 76234: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -"use strict"; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fsStat = __nccwpck_require__(70109); -const fsWalk = __nccwpck_require__(26026); -const reader_1 = __nccwpck_require__(65582); -class ReaderSync extends reader_1.default { - constructor() { - super(...arguments); - this._walkSync = fsWalk.walkSync; - this._statSync = fsStat.statSync; - } - dynamic(root, options) { - return this._walkSync(root, options); - } - static(patterns, options) { - const entries = []; - for (const pattern of patterns) { - const filepath = this._getFullEntryPath(pattern); - const entry = this._getEntry(filepath, pattern, options); - if (entry === null || !options.entryFilter(entry)) { - continue; - } - entries.push(entry); - } - return entries; - } - _getEntry(filepath, pattern, options) { - try { - const stats = this._getStat(filepath); - return this._makeEntry(stats, pattern); - } - catch (error) { - if (options.errorFilter(error)) { - return null; - } - throw error; - } - } - _getStat(filepath) { - return this._statSync(filepath, this._fsStatSettings); - } -} -exports["default"] = ReaderSync; + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -/***/ }), + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -/***/ 10952: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return debug; + } -"use strict"; + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; -const fs = __nccwpck_require__(57147); -const os = __nccwpck_require__(22037); -/** - * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. - * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 - */ -const CPU_COUNT = Math.max(os.cpus().length, 1); -exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - lstatSync: fs.lstatSync, - stat: fs.stat, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync -}; -class Settings { - constructor(_options = {}) { - this._options = _options; - this.absolute = this._getValue(this._options.absolute, false); - this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); - this.braceExpansion = this._getValue(this._options.braceExpansion, true); - this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); - this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); - this.cwd = this._getValue(this._options.cwd, process.cwd()); - this.deep = this._getValue(this._options.deep, Infinity); - this.dot = this._getValue(this._options.dot, false); - this.extglob = this._getValue(this._options.extglob, true); - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); - this.fs = this._getFileSystemMethods(this._options.fs); - this.globstar = this._getValue(this._options.globstar, true); - this.ignore = this._getValue(this._options.ignore, []); - this.markDirectories = this._getValue(this._options.markDirectories, false); - this.objectMode = this._getValue(this._options.objectMode, false); - this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); - this.onlyFiles = this._getValue(this._options.onlyFiles, true); - this.stats = this._getValue(this._options.stats, false); - this.suppressErrors = this._getValue(this._options.suppressErrors, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); - this.unique = this._getValue(this._options.unique, true); - if (this.onlyDirectories) { - this.onlyFiles = false; - } - if (this.stats) { - this.objectMode = true; - } - // Remove the cast to the array in the next major (#404). - this.ignore = [].concat(this.ignore); - } - _getValue(option, value) { - return option === undefined ? value : option; - } - _getFileSystemMethods(methods = {}) { - return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); - } -} -exports["default"] = Settings; + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; -/***/ }), + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -/***/ 85325: -/***/ ((__unused_webpack_module, exports) => { + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -"use strict"; + namespaces = split[i].replace(/\*/g, '.*?'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitWhen = exports.flatten = void 0; -function flatten(items) { - return items.reduce((collection, item) => [].concat(collection, item), []); -} -exports.flatten = flatten; -function splitWhen(items, predicate) { - const result = [[]]; - let groupIndex = 0; - for (const item of items) { - if (predicate(item)) { - groupIndex++; - result[groupIndex] = []; - } - else { - result[groupIndex].push(item); - } - } - return result; -} -exports.splitWhen = splitWhen; + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -/***/ }), + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -/***/ 41230: -/***/ ((__unused_webpack_module, exports) => { + let i; + let len; -"use strict"; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isEnoentCodeError = void 0; -function isEnoentCodeError(error) { - return error.code === 'ENOENT'; -} -exports.isEnoentCodeError = isEnoentCodeError; + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + return false; + } -/***/ }), + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } -/***/ 17543: -/***/ ((__unused_webpack_module, exports) => { + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -"use strict"; + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createDirentFromStats = void 0; -class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); + createDebug.enable(createDebug.load()); + + return createDebug; } -exports.createDirentFromStats = createDirentFromStats; + +module.exports = setup; /***/ }), -/***/ 45444: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; -const array = __nccwpck_require__(85325); -exports.array = array; -const errno = __nccwpck_require__(41230); -exports.errno = errno; -const fs = __nccwpck_require__(17543); -exports.fs = fs; -const path = __nccwpck_require__(63873); -exports.path = path; -const pattern = __nccwpck_require__(81221); -exports.pattern = pattern; -const stream = __nccwpck_require__(18382); -exports.stream = stream; -const string = __nccwpck_require__(52203); -exports.string = string; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); +} /***/ }), -/***/ 63873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; -const os = __nccwpck_require__(22037); -const path = __nccwpck_require__(71017); -const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; -const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ -/** - * All non-escaped special characters. - * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. - * Windows: (){}, !+@ before (, ! at the beginning. - */ -const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; -const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g; /** - * The device path (\\.\ or \\?\). - * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + * Module dependencies. */ -const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; + +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); + /** - * All backslashes except those escaping special characters. - * Windows: !()+@{} - * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + * This is the Node.js implementation of `debug()`. */ -const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g; + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + /** - * Designed to work only with simple paths: `dir\\file`. + * Colors. */ -function unixify(filepath) { - return filepath.replace(/\\/g, '/'); -} -exports.unixify = unixify; -function makeAbsolute(cwd, filepath) { - return path.resolve(cwd, filepath); -} -exports.makeAbsolute = makeAbsolute; -function removeLeadingDotSegment(entry) { - // We do not use `startsWith` because this is 10x slower than current implementation for some cases. - // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with - if (entry.charAt(0) === '.') { - const secondCharactery = entry.charAt(1); - if (secondCharactery === '/' || secondCharactery === '\\') { - return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); - } - } - return entry; -} -exports.removeLeadingDotSegment = removeLeadingDotSegment; -exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; -function escapeWindowsPath(pattern) { - return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); -} -exports.escapeWindowsPath = escapeWindowsPath; -function escapePosixPath(pattern) { - return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); -} -exports.escapePosixPath = escapePosixPath; -exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; -function convertWindowsPathToPattern(filepath) { - return escapeWindowsPath(filepath) - .replace(DOS_DEVICE_PATH_RE, '//$1') - .replace(WINDOWS_BACKSLASHES_RE, '/'); -} -exports.convertWindowsPathToPattern = convertWindowsPathToPattern; -function convertPosixPathToPattern(filepath) { - return escapePosixPath(filepath); + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } -exports.convertPosixPathToPattern = convertPosixPathToPattern; +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -/***/ }), +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); -/***/ 81221: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } -"use strict"; + obj[prop] = val; + return obj; +}, {}); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; -const path = __nccwpck_require__(71017); -const globParent = __nccwpck_require__(54655); -const micromatch = __nccwpck_require__(76228); -const GLOBSTAR = '**'; -const ESCAPE_SYMBOL = '\\'; -const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; -const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; -const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; -const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; -const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; /** - * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. - * The latter is due to the presence of the device path at the beginning of the UNC path. + * Is stdout a TTY? Colored output is enabled when `true`. */ -const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; -function isStaticPattern(pattern, options = {}) { - return !isDynamicPattern(pattern, options); -} -exports.isStaticPattern = isStaticPattern; -function isDynamicPattern(pattern, options = {}) { - /** - * A special case with an empty string is necessary for matching patterns that start with a forward slash. - * An empty string cannot be a dynamic pattern. - * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. - */ - if (pattern === '') { - return false; - } - /** - * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check - * filepath directly (without read directory). - */ - if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { - return true; - } - if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { - return true; - } - return false; -} -exports.isDynamicPattern = isDynamicPattern; -function hasBraceExpansion(pattern) { - const openingBraceIndex = pattern.indexOf('{'); - if (openingBraceIndex === -1) { - return false; - } - const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); - if (closingBraceIndex === -1) { - return false; - } - const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); - return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); -} -function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; -} -exports.convertToPositivePattern = convertToPositivePattern; -function convertToNegativePattern(pattern) { - return '!' + pattern; -} -exports.convertToNegativePattern = convertToNegativePattern; -function isNegativePattern(pattern) { - return pattern.startsWith('!') && pattern[1] !== '('; + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } -exports.isNegativePattern = isNegativePattern; -function isPositivePattern(pattern) { - return !isNegativePattern(pattern); + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } } -exports.isPositivePattern = isPositivePattern; -function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; } -exports.getNegativePatterns = getNegativePatterns; -function getPositivePatterns(patterns) { - return patterns.filter(isPositivePattern); + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } -exports.getPositivePatterns = getPositivePatterns; + /** - * Returns patterns that can be applied inside the current directory. + * Save `namespaces`. * - * @example - * // ['./*', '*', 'a/*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + * @param {String} namespaces + * @api private */ -function getPatternsInsideCurrentDirectory(patterns) { - return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } -exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; + /** - * Returns patterns to be expanded relative to (outside) the current directory. + * Load `namespaces`. * - * @example - * // ['../*', './../*'] - * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + * @return {String} returns the previously persisted debug modes + * @api private */ -function getPatternsOutsideCurrentDirectory(patterns) { - return patterns.filter(isPatternRelatedToParentDirectory); -} -exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; -function isPatternRelatedToParentDirectory(pattern) { - return pattern.startsWith('..') || pattern.startsWith('./..'); -} -exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; -function getBaseDirectory(pattern) { - return globParent(pattern, { flipBackslashes: false }); -} -exports.getBaseDirectory = getBaseDirectory; -function hasGlobStar(pattern) { - return pattern.includes(GLOBSTAR); -} -exports.hasGlobStar = hasGlobStar; -function endsWithSlashGlobStar(pattern) { - return pattern.endsWith('/' + GLOBSTAR); -} -exports.endsWithSlashGlobStar = endsWithSlashGlobStar; -function isAffectDepthOfReadingPattern(pattern) { - const basename = path.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); -} -exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; -function expandPatternsWithBraceExpansion(patterns) { - return patterns.reduce((collection, pattern) => { - return collection.concat(expandBraceExpansion(pattern)); - }, []); -} -exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; -function expandBraceExpansion(pattern) { - const patterns = micromatch.braces(pattern, { expand: true, nodupes: true }); - /** - * Sort the patterns by length so that the same depth patterns are processed side by side. - * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` - */ - patterns.sort((a, b) => a.length - b.length); - /** - * Micromatch can return an empty string in the case of patterns like `{a,}`. - */ - return patterns.filter((pattern) => pattern !== ''); -} -exports.expandBraceExpansion = expandBraceExpansion; -function getPatternParts(pattern, options) { - let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); - /** - * The scan method returns an empty array in some cases. - * See micromatch/picomatch#58 for more details. - */ - if (parts.length === 0) { - parts = [pattern]; - } - /** - * The scan method does not return an empty part for the pattern with a forward slash. - * This is another part of micromatch/picomatch#58. - */ - if (parts[0].startsWith('/')) { - parts[0] = parts[0].slice(1); - parts.unshift(''); - } - return parts; -} -exports.getPatternParts = getPatternParts; -function makeRe(pattern, options) { - return micromatch.makeRe(pattern, options); -} -exports.makeRe = makeRe; -function convertPatternsToRe(patterns, options) { - return patterns.map((pattern) => makeRe(pattern, options)); -} -exports.convertPatternsToRe = convertPatternsToRe; -function matchAny(entry, patternsRe) { - return patternsRe.some((patternRe) => patternRe.test(entry)); + +function load() { + return process.env.DEBUG; } -exports.matchAny = matchAny; + /** - * This package only works with forward slashes as a path separator. - * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function removeDuplicateSlashes(pattern) { - return pattern.replace(DOUBLE_SLASH_RE, '/'); + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } -exports.removeDuplicateSlashes = removeDuplicateSlashes; +module.exports = __nccwpck_require__(46243)(exports); -/***/ }), +const {formatters} = module.exports; -/***/ 18382: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Map %o to `util.inspect()`, all on a single line. + */ -"use strict"; +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.merge = void 0; -const merge2 = __nccwpck_require__(82578); -function merge(streams) { - const mergedStream = merge2(streams); - streams.forEach((stream) => { - stream.once('error', (error) => mergedStream.emit('error', error)); - }); - mergedStream.once('close', () => propagateCloseEventToSources(streams)); - mergedStream.once('end', () => propagateCloseEventToSources(streams)); - return mergedStream; -} -exports.merge = merge; -function propagateCloseEventToSources(streams) { - streams.forEach((stream) => stream.emit('close')); -} +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /***/ }), -/***/ 52203: -/***/ ((__unused_webpack_module, exports) => { +/***/ 56323: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isEmpty = exports.isString = void 0; -function isString(input) { - return typeof input === 'string'; -} -exports.isString = isString; -function isEmpty(input) { - return input === ''; -} -exports.isEmpty = isEmpty; - -/***/ }), +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; -/***/ 12603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} -"use strict"; +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} -const validator = __nccwpck_require__(61739); -const XMLParser = __nccwpck_require__(42380); -const XMLBuilder = __nccwpck_require__(80660); +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; -module.exports = { - XMLParser: XMLParser, - XMLValidator: validator, - XMLBuilder: XMLBuilder +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE } -/***/ }), - -/***/ 4958: -/***/ ((module) => { +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} -function getIgnoreAttributesFn(ignoreAttributes) { - if (typeof ignoreAttributes === 'function') { - return ignoreAttributes - } - if (Array.isArray(ignoreAttributes)) { - return (attrName) => { - for (const pattern of ignoreAttributes) { - if (typeof pattern === 'string' && attrName === pattern) { - return true - } - if (pattern instanceof RegExp && pattern.test(attrName)) { - return true - } - } - } - } - return () => false +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value } -module.exports = getIgnoreAttributesFn +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} -/***/ }), +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} -/***/ 38280: -/***/ ((__unused_webpack_module, exports) => { +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return Object.propertyIsEnumerable.call(target, symbol) + }) + : [] +} -"use strict"; +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} -const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; -const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; -const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' -const regexName = new RegExp('^' + nameRegexp + '$'); +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} -const getAllMatches = function(string, regex) { - const matches = []; - let match = regex.exec(string); - while (match) { - const allmatches = []; - allmatches.startIndex = regex.lastIndex - match[0].length; - const len = match.length; - for (let index = 0; index < len; index++) { - allmatches.push(match[index]); - } - matches.push(allmatches); - match = regex.exec(string); - } - return matches; -}; +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } -const isName = function(string) { - const match = regexName.exec(string); - return !(match === null || typeof match === 'undefined'); -}; + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} -exports.isExist = function(v) { - return typeof v !== 'undefined'; -}; +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; -exports.isEmptyObject = function(obj) { - return Object.keys(obj).length === 0; -}; + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; -/** - * Copy all the properties of a into b. - * @param {*} target - * @param {*} a - */ -exports.merge = function(target, a, arrayMode) { - if (a) { - const keys = Object.keys(a); // will return an array of own properties - const len = keys.length; //don't make it inline - for (let i = 0; i < len; i++) { - if (arrayMode === 'strict') { - target[keys[i]] = [ a[keys[i]] ]; - } else { - target[keys[i]] = a[keys[i]]; - } - } - } -}; -/* exports.merge =function (b,a){ - return Object.assign(b,a); -} */ + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} -exports.getValue = function(v) { - if (exports.isExist(v)) { - return v; - } else { - return ''; - } +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } + + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) }; -// const fakeCall = function(a) {return a;}; -// const fakeCallNoReturn = function() {}; +var deepmerge_1 = deepmerge; -exports.isName = isName; -exports.getAllMatches = getAllMatches; -exports.nameRegexp = nameRegexp; +module.exports = deepmerge_1; /***/ }), -/***/ 61739: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const util = __nccwpck_require__(38280); - -const defaultOptions = { - allowBooleanAttributes: false, //A tag can have attributes without any value - unpairedTags: [] -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); -//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); -exports.validate = function (xmlData, options) { - options = Object.assign({}, defaultOptions, options); +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line - //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag - //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE - const tags = []; - let tagFound = false; + /* istanbul ignore next */ - //indicates that the root tag has been closed (aka. depth 0 has been reached) - let reachedRoot = false; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - if (xmlData[0] === '\ufeff') { - // check for byte order mark (BOM) - xmlData = xmlData.substr(1); + this.name = 'Deprecation'; } - - for (let i = 0; i < xmlData.length; i++) { - - if (xmlData[i] === '<' && xmlData[i+1] === '?') { - i+=2; - i = readPI(xmlData,i); - if (i.err) return i; - }else if (xmlData[i] === '<') { - //starting of tag - //read until you reach to '>' avoiding any '>' in attribute value - let tagStartPos = i; - i++; - - if (xmlData[i] === '!') { - i = readCommentAndCDATA(xmlData, i); - continue; - } else { - let closingTag = false; - if (xmlData[i] === '/') { - //closing tag - closingTag = true; - i++; - } - //read tagname - let tagName = ''; - for (; i < xmlData.length && - xmlData[i] !== '>' && - xmlData[i] !== ' ' && - xmlData[i] !== '\t' && - xmlData[i] !== '\n' && - xmlData[i] !== '\r'; i++ - ) { - tagName += xmlData[i]; - } - tagName = tagName.trim(); - //console.log(tagName); - if (tagName[tagName.length - 1] === '/') { - //self closing tag without attributes - tagName = tagName.substring(0, tagName.length - 1); - //continue; - i--; - } - if (!validateTagName(tagName)) { - let msg; - if (tagName.trim().length === 0) { - msg = "Invalid space after '<'."; - } else { - msg = "Tag '"+tagName+"' is an invalid name."; - } - return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); - } +} - const result = readAttributeStr(xmlData, i); - if (result === false) { - return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); - } - let attrStr = result.value; - i = result.index; +exports.Deprecation = Deprecation; - if (attrStr[attrStr.length - 1] === '/') { - //self closing tag - const attrStrStart = i - attrStr.length; - attrStr = attrStr.substring(0, attrStr.length - 1); - const isValid = validateAttributeString(attrStr, options); - if (isValid === true) { - tagFound = true; - //continue; //text may presents after self closing tag - } else { - //the result from the nested function returns the position of the error within the attribute - //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute - //this gives us the absolute index in the entire xml, which we can use to find the line at last - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); - } - } else if (closingTag) { - if (!result.tagClosed) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); - } else if (attrStr.trim().length > 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); - } else if (tags.length === 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); - } else { - const otg = tags.pop(); - if (tagName !== otg.tagName) { - let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); - return getErrorObject('InvalidTag', - "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", - getLineNumberForPosition(xmlData, tagStartPos)); - } - //when there are no more tags, we reached the root level. - if (tags.length == 0) { - reachedRoot = true; - } - } - } else { - const isValid = validateAttributeString(attrStr, options); - if (isValid !== true) { - //the result from the nested function returns the position of the error within the attribute - //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute - //this gives us the absolute index in the entire xml, which we can use to find the line at last - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); - } +/***/ }), - //if the root level has been reached before ... - if (reachedRoot === true) { - return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); - } else if(options.unpairedTags.indexOf(tagName) !== -1){ - //don't push into stack - } else { - tags.push({tagName, tagStartPos}); - } - tagFound = true; - } +/***/ 3194: +/***/ ((module) => { - //skip tag text value - //It may include comments and CDATA value - for (i++; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - if (xmlData[i + 1] === '!') { - //comment or CADATA - i++; - i = readCommentAndCDATA(xmlData, i); - continue; - } else if (xmlData[i+1] === '?') { - i = readPI(xmlData, ++i); - if (i.err) return i; - } else{ - break; - } - } else if (xmlData[i] === '&') { - const afterAmp = validateAmpersand(xmlData, i); - if (afterAmp == -1) - return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); - i = afterAmp; - }else{ - if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { - return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); - } - } - } //end of reading tag text value - if (xmlData[i] === '<') { - i--; - } - } - } else { - if ( isWhiteSpace(xmlData[i])) { - continue; - } - return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); - } - } +"use strict"; - if (!tagFound) { - return getErrorObject('InvalidXml', 'Start tag expected.', 1); - }else if (tags.length == 1) { - return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); - }else if (tags.length > 0) { - return getErrorObject('InvalidXml', "Invalid '"+ - JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ - "' found.", {line: 1, col: 1}); - } - return true; +module.exports = { + 'html': '', + 'xml': '', + 'transitional': '', + 'strict': '', + 'frameset': '', + '1.1': '', + 'basic': '', + 'mobile': '', + 'plist': '' }; -function isWhiteSpace(char){ - return char === ' ' || char === '\t' || char === '\n' || char === '\r'; -} -/** - * Read Processing insstructions and skip - * @param {*} xmlData - * @param {*} i - */ -function readPI(xmlData, i) { - const start = i; - for (; i < xmlData.length; i++) { - if (xmlData[i] == '?' || xmlData[i] == ' ') { - //tagname - const tagname = xmlData.substr(start, i - start); - if (i > 5 && tagname === 'xml') { - return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); - } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { - //check if valid attribut string - i++; - break; - } else { - continue; - } - } - } - return i; -} -function readCommentAndCDATA(xmlData, i) { - if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { - //comment - for (i += 3; i < xmlData.length; i++) { - if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { - i += 2; - break; - } - } - } else if ( - xmlData.length > i + 8 && - xmlData[i + 1] === 'D' && - xmlData[i + 2] === 'O' && - xmlData[i + 3] === 'C' && - xmlData[i + 4] === 'T' && - xmlData[i + 5] === 'Y' && - xmlData[i + 6] === 'P' && - xmlData[i + 7] === 'E' - ) { - let angleBracketsCount = 1; - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - angleBracketsCount++; - } else if (xmlData[i] === '>') { - angleBracketsCount--; - if (angleBracketsCount === 0) { - break; - } - } +/***/ }), + +/***/ 13598: +/***/ ((module) => { + +"use strict"; + + +function _process (v, mod) { + var i + var r + + if (typeof mod === 'function') { + r = mod(v) + if (r !== undefined) { + v = r } - } else if ( - xmlData.length > i + 9 && - xmlData[i + 1] === '[' && - xmlData[i + 2] === 'C' && - xmlData[i + 3] === 'D' && - xmlData[i + 4] === 'A' && - xmlData[i + 5] === 'T' && - xmlData[i + 6] === 'A' && - xmlData[i + 7] === '[' - ) { - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { - i += 2; - break; + } else if (Array.isArray(mod)) { + for (i = 0; i < mod.length; i++) { + r = mod[i](v) + if (r !== undefined) { + v = r } } } - return i; + return v } -const doubleQuote = '"'; -const singleQuote = "'"; - -/** - * Keep reading xmlData until '<' is found outside the attribute value. - * @param {string} xmlData - * @param {number} i - */ -function readAttributeStr(xmlData, i) { - let attrStr = ''; - let startChar = ''; - let tagClosed = false; - for (; i < xmlData.length; i++) { - if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { - if (startChar === '') { - startChar = xmlData[i]; - } else if (startChar !== xmlData[i]) { - //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa - } else { - startChar = ''; - } - } else if (xmlData[i] === '>') { - if (startChar === '') { - tagClosed = true; - break; - } - } - attrStr += xmlData[i]; - } - if (startChar !== '') { - return false; +function parseKey (key, val) { + // detect negative index notation + if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { + return val.length + parseInt(key, 10) } + return key +} - return { - value: attrStr, - index: i, - tagClosed: tagClosed - }; +function isIndex (k) { + return /^\d+$/.test(k) } -/** - * Select all the attributes whether valid or invalid. - */ -const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); +function isObject (val) { + return Object.prototype.toString.call(val) === '[object Object]' +} -//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" +function isArrayOrObject (val) { + return Object(val) === val +} -function validateAttributeString(attrStr, options) { - //console.log("start:"+attrStr+":end"); +function isEmptyObject (val) { + return Object.keys(val).length === 0 +} - //if(attrStr.trim().length === 0) return true; //empty string +var blacklist = ['__proto__', 'prototype', 'constructor'] +var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } - const matches = util.getAllMatches(attrStr, validAttrStrRegxp); - const attrNames = {}; +function parsePath (path, sep) { + if (path.indexOf('[') >= 0) { + path = path.replace(/\[/g, sep).replace(/]/g, '') + } - for (let i = 0; i < matches.length; i++) { - if (matches[i][1].length === 0) { - //nospace before attribute name: a="sd"b="saf" - return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) - } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { - return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); - } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { - //independent attribute: ab - return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); - } - /* else if(matches[i][6] === undefined){//attribute without value: ab= - return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; - } */ - const attrName = matches[i][2]; - if (!validateAttrName(attrName)) { - return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); - } - if (!attrNames.hasOwnProperty(attrName)) { - //check for duplicate attribute. - attrNames[attrName] = 1; - } else { - return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); - } + var parts = path.split(sep) + + var check = parts.filter(blacklistFilter) + + if (check.length !== parts.length) { + throw Error('Refusing to update blacklisted property ' + path) } - return true; + return parts } -function validateNumberAmpersand(xmlData, i) { - let re = /\d/; - if (xmlData[i] === 'x') { - i++; - re = /[\da-fA-F]/; - } - for (; i < xmlData.length; i++) { - if (xmlData[i] === ';') - return i; - if (!xmlData[i].match(re)) - break; +var hasOwnProperty = Object.prototype.hasOwnProperty + +function DotObject (separator, override, useArray, useBrackets) { + if (!(this instanceof DotObject)) { + return new DotObject(separator, override, useArray, useBrackets) } - return -1; + + if (typeof override === 'undefined') override = false + if (typeof useArray === 'undefined') useArray = true + if (typeof useBrackets === 'undefined') useBrackets = true + this.separator = separator || '.' + this.override = override + this.useArray = useArray + this.useBrackets = useBrackets + this.keepArray = false + + // contains touched arrays + this.cleanup = [] } -function validateAmpersand(xmlData, i) { - // https://www.w3.org/TR/xml/#dt-charref - i++; - if (xmlData[i] === ';') - return -1; - if (xmlData[i] === '#') { - i++; - return validateNumberAmpersand(xmlData, i); - } - let count = 0; - for (; i < xmlData.length; i++, count++) { - if (xmlData[i].match(/\w/) && count < 20) - continue; - if (xmlData[i] === ';') - break; - return -1; +var dotDefault = new DotObject('.', false, true, true) +function wrap (method) { + return function () { + return dotDefault[method].apply(dotDefault, arguments) } - return i; } -function getErrorObject(code, message, lineNumber) { - return { - err: { - code: code, - msg: message, - line: lineNumber.line || lineNumber, - col: lineNumber.col, - }, - }; -} +DotObject.prototype._fill = function (a, obj, v, mod) { + var k = a.shift() -function validateAttrName(attrName) { - return util.isName(attrName); -} + if (a.length > 0) { + obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) -// const startsWithXML = /^xml/i; + if (!isArrayOrObject(obj[k])) { + if (this.override) { + obj[k] = {} + } else { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error( + 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] + ) + } -function validateTagName(tagname) { - return util.isName(tagname) /* && !tagname.match(startsWithXML) */; -} + return + } + } -//this function returns the line number for the character at the given index -function getLineNumberForPosition(xmlData, index) { - const lines = xmlData.substring(0, index).split(/\r?\n/); - return { - line: lines.length, + this._fill(a, obj[k], v, mod) + } else { + if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error("Trying to redefine non-empty obj['" + k + "']") + } - // column number is last line's length + 1, because column numbering starts at 1: - col: lines[lines.length - 1].length + 1 - }; -} + return + } -//this function returns the position of the first character of match within attrStr -function getPositionFromMatch(match) { - return match.startIndex + match[1].length; + obj[k] = _process(v, mod) + } } +/** + * + * Converts an object with dotted-key/value pairs to it's expanded version + * + * Optionally transformed by a set of modifiers. + * + * Usage: + * + * var row = { + * 'nr': 200, + * 'doc.name': ' My Document ' + * } + * + * var mods = { + * 'doc.name': [_s.trim, _s.underscored] + * } + * + * dot.object(row, mods) + * + * @param {Object} obj + * @param {Object} mods + */ +DotObject.prototype.object = function (obj, mods) { + var self = this -/***/ }), - -/***/ 80660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Object.keys(obj).forEach(function (k) { + var mod = mods === undefined ? null : mods[k] + // normalize array notation. + var ok = parsePath(k, self.separator).join(self.separator) -"use strict"; + if (ok.indexOf(self.separator) !== -1) { + self._fill(ok.split(self.separator), obj, obj[k], mod) + delete obj[k] + } else { + obj[k] = _process(obj[k], mod) + } + }) -//parse Empty Node as self closing node -const buildFromOrderedJs = __nccwpck_require__(72462); -const getIgnoreAttributesFn = __nccwpck_require__(4958) + return obj +} -const defaultOptions = { - attributeNamePrefix: '@_', - attributesGroupName: false, - textNodeName: '#text', - ignoreAttributes: true, - cdataPropName: false, - format: false, - indentBy: ' ', - suppressEmptyNode: false, - suppressUnpairedNode: true, - suppressBooleanAttributes: true, - tagValueProcessor: function(key, a) { - return a; - }, - attributeValueProcessor: function(attrName, a) { - return a; - }, - preserveOrder: false, - commentPropName: false, - unpairedTags: [], - entities: [ - { regex: new RegExp("&", "g"), val: "&" },//it must be on top - { regex: new RegExp(">", "g"), val: ">" }, - { regex: new RegExp("<", "g"), val: "<" }, - { regex: new RegExp("\'", "g"), val: "'" }, - { regex: new RegExp("\"", "g"), val: """ } - ], - processEntities: true, - stopNodes: [], - // transformTagName: false, - // transformAttributeName: false, - oneListGroup: false -}; +/** + * @param {String} path dotted path + * @param {String} v value to be set + * @param {Object} obj object to be modified + * @param {Function|Array} mod optional modifier + */ +DotObject.prototype.str = function (path, v, obj, mod) { + var ok = parsePath(path, this.separator).join(this.separator) -function Builder(options) { - this.options = Object.assign({}, defaultOptions, options); - if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { - this.isAttribute = function(/*a*/) { - return false; - }; + if (path.indexOf(this.separator) !== -1) { + this._fill(ok.split(this.separator), obj, v, mod) } else { - this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) - this.attrPrefixLen = this.options.attributeNamePrefix.length; - this.isAttribute = isAttribute; + obj[path] = _process(v, mod) } - this.processTextOrObjNode = processTextOrObjNode - - if (this.options.format) { - this.indentate = indentate; - this.tagEndChar = '>\n'; - this.newLine = '\n'; - } else { - this.indentate = function() { - return ''; - }; - this.tagEndChar = '>'; - this.newLine = ''; - } + return obj } -Builder.prototype.build = function(jObj) { - if(this.options.preserveOrder){ - return buildFromOrderedJs(jObj, this.options); - }else { - if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ - jObj = { - [this.options.arrayNodeName] : jObj - } - } - return this.j2x(jObj, 0, []).val; - } -}; +/** + * + * Pick a value from an object using dot notation. + * + * Optionally remove the value + * + * @param {String} path + * @param {Object} obj + * @param {Boolean} remove + */ +DotObject.prototype.pick = function (path, obj, remove, reindexArray) { + var i + var keys + var val + var key + var cp -Builder.prototype.j2x = function(jObj, level, ajPath) { - let attrStr = ''; - let val = ''; - const jPath = ajPath.join('.') - for (let key in jObj) { - if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; - if (typeof jObj[key] === 'undefined') { - // supress undefined node only if it is not an attribute - if (this.isAttribute(key)) { - val += ''; - } - } else if (jObj[key] === null) { - // null attribute should be ignored by the attribute list, but should not cause the tag closing - if (this.isAttribute(key)) { - val += ''; - } else if (key[0] === '?') { - val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; - } else { - val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } - // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } else if (jObj[key] instanceof Date) { - val += this.buildTextValNode(jObj[key], key, '', level); - } else if (typeof jObj[key] !== 'object') { - //premitive type - const attr = this.isAttribute(key); - if (attr && !this.ignoreAttributesFn(attr, jPath)) { - attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); - } else if (!attr) { - //tag value - if (key === this.options.textNodeName) { - let newval = this.options.tagValueProcessor(key, '' + jObj[key]); - val += this.replaceEntitiesValue(newval); - } else { - val += this.buildTextValNode(jObj[key], key, '', level); - } - } - } else if (Array.isArray(jObj[key])) { - //repeated nodes - const arrLen = jObj[key].length; - let listTagVal = ""; - let listTagAttr = ""; - for (let j = 0; j < arrLen; j++) { - const item = jObj[key][j]; - if (typeof item === 'undefined') { - // supress undefined node - } else if (item === null) { - if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; - else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } else if (typeof item === 'object') { - if(this.options.oneListGroup){ - const result = this.j2x(item, level + 1, ajPath.concat(key)); - listTagVal += result.val; - if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { - listTagAttr += result.attrStr + keys = parsePath(path, this.separator) + for (i = 0; i < keys.length; i++) { + key = parseKey(keys[i], obj) + if (obj && typeof obj === 'object' && key in obj) { + if (i === keys.length - 1) { + if (remove) { + val = obj[key] + if (reindexArray && Array.isArray(obj)) { + obj.splice(key, 1) + } else { + delete obj[key] + } + if (Array.isArray(obj)) { + cp = keys.slice(0, -1).join('.') + if (this.cleanup.indexOf(cp) === -1) { + this.cleanup.push(cp) } - }else{ - listTagVal += this.processTextOrObjNode(item, key, level, ajPath) } + return val } else { - if (this.options.oneListGroup) { - let textValue = this.options.tagValueProcessor(key, item); - textValue = this.replaceEntitiesValue(textValue); - listTagVal += textValue; - } else { - listTagVal += this.buildTextValNode(item, key, '', level); - } - } - } - if(this.options.oneListGroup){ - listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); - } - val += listTagVal; - } else { - //nested node - if (this.options.attributesGroupName && key === this.options.attributesGroupName) { - const Ks = Object.keys(jObj[key]); - const L = Ks.length; - for (let j = 0; j < L; j++) { - attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); + return obj[key] } } else { - val += this.processTextOrObjNode(jObj[key], key, level, ajPath) + obj = obj[key] } + } else { + return undefined } } - return {attrStr: attrStr, val: val}; -}; - -Builder.prototype.buildAttrPairStr = function(attrName, val){ - val = this.options.attributeValueProcessor(attrName, '' + val); - val = this.replaceEntitiesValue(val); - if (this.options.suppressBooleanAttributes && val === "true") { - return ' ' + attrName; - } else return ' ' + attrName + '="' + val + '"'; -} - -function processTextOrObjNode (object, key, level, ajPath) { - const result = this.j2x(object, level + 1, ajPath.concat(key)); - if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { - return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); - } else { - return this.buildObjectNode(result.val, key, result.attrStr, level); + if (remove && Array.isArray(obj)) { + obj = obj.filter(function (n) { + return n !== undefined + }) } + return obj +} +/** + * + * Delete value from an object using dot notation. + * + * @param {String} path + * @param {Object} obj + * @return {any} The removed value + */ +DotObject.prototype.delete = function (path, obj) { + return this.remove(path, obj, true) } -Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { - if(val === ""){ - if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; - else { - return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; - } - }else{ +/** + * + * Remove value from an object using dot notation. + * + * Will remove multiple items if path is an array. + * In this case array indexes will be retained until all + * removals have been processed. + * + * Use dot.delete() to automatically re-index arrays. + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.remove = function (path, obj, reindexArray) { + var i - let tagEndExp = '' + val + tagEndExp ); - } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { - return this.indentate(level) + `` + this.newLine; - }else { - return ( - this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + - val + - this.indentate(level) + tagEndExp ); + if (!reindexArray) { + this._cleanup(obj) } + return obj + } else { + return this.pick(path, obj, true, reindexArray) } } -Builder.prototype.closeTag = function(key){ - let closeTag = ""; - if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired - if(!this.options.suppressUnpairedNode) closeTag = "/" - }else if(this.options.suppressEmptyNode){ //empty - closeTag = "/"; - }else{ - closeTag = `>} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.del = DotObject.prototype.remove + +/** + * + * Move a property from one place to the other. + * + * If the source path does not exist (undefined) + * the target property will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.move = function (source, target, obj, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) } else { - if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; - else { - return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar; - // return this.buildTagStr(level,key, attrStr); - } + merge = mods + this.set(target, this.pick(source, obj, true), obj, merge) } + + return obj } -Builder.prototype.buildTextValNode = function(val, key, attrStr, level) { - if (this.options.cdataPropName !== false && key === this.options.cdataPropName) { - return this.indentate(level) + `` + this.newLine; - }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { - return this.indentate(level) + `` + this.newLine; - }else if(key[0] === "?") {//PI tag - return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; - }else{ - let textValue = this.options.tagValueProcessor(key, val); - textValue = this.replaceEntitiesValue(textValue); - - if( textValue === ''){ - return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; - }else{ - return this.indentate(level) + '<' + key + attrStr + '>' + - textValue + - ' 0 && this.options.processEntities){ - for (let i=0; i { + keys = parsePath(path, this.separator) -const EOL = "\n"; + for (i = 0; i < keys.length; i++) { + key = keys[i] + if (i === keys.length - 1) { + if (merge && isObject(val) && isObject(obj[key])) { + for (k in val) { + if (hasOwnProperty.call(val, k)) { + obj[key][k] = val[k] + } + } + } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { + for (var j = 0; j < val.length; j++) { + obj[keys[i]].push(val[j]) + } + } else { + obj[key] = val + } + } else if ( + // force the value to be an object + !hasOwnProperty.call(obj, key) || + (!isObject(obj[key]) && !Array.isArray(obj[key])) + ) { + // initialize as array if next key is numeric + if (/^\d+$/.test(keys[i + 1])) { + obj[key] = [] + } else { + obj[key] = {} + } + } + obj = obj[key] + } + return obj +} /** - * - * @param {array} jArray - * @param {any} options - * @returns + * + * Transform an object + * + * Usage: + * + * var obj = { + * "id": 1, + * "some": { + * "thing": "else" + * } + * } + * + * var transform = { + * "id": "nr", + * "some.thing": "name" + * } + * + * var tgt = dot.transform(transform, obj) + * + * @param {Object} recipe Transform recipe + * @param {Object} obj Object to be transformed + * @param {Array} mods modifiers for the target */ -function toXml(jArray, options) { - let indentation = ""; - if (options.format && options.indentBy.length > 0) { - indentation = EOL; - } - return arrToStr(jArray, options, "", indentation); +DotObject.prototype.transform = function (recipe, obj, tgt) { + obj = obj || {} + tgt = tgt || {} + Object.keys(recipe).forEach( + function (key) { + this.set(recipe[key], this.pick(key, obj), tgt) + }.bind(this) + ) + return tgt } -function arrToStr(arr, options, jPath, indentation) { - let xmlStr = ""; - let isPreviousElementTag = false; - - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const tagName = propName(tagObj); - if(tagName === undefined) continue; - - let newJPath = ""; - if (jPath.length === 0) newJPath = tagName - else newJPath = `${jPath}.${tagName}`; +/** + * + * Convert object to dotted-key/value pair + * + * Usage: + * + * var tgt = dot.dot(obj) + * + * or + * + * var tgt = {} + * dot.dot(obj, tgt) + * + * @param {Object} obj source object + * @param {Object} tgt target object + * @param {Array} path path array (internal) + */ +DotObject.prototype.dot = function (obj, tgt, path) { + tgt = tgt || {} + path = path || [] + var isArray = Array.isArray(obj) - if (tagName === options.textNodeName) { - let tagText = tagObj[tagName]; - if (!isStopNode(newJPath, options)) { - tagText = options.tagValueProcessor(tagName, tagText); - tagText = replaceEntitiesValue(tagText, options); - } - if (isPreviousElementTag) { - xmlStr += indentation; - } - xmlStr += tagText; - isPreviousElementTag = false; - continue; - } else if (tagName === options.cdataPropName) { - if (isPreviousElementTag) { - xmlStr += indentation; - } - xmlStr += ``; - isPreviousElementTag = false; - continue; - } else if (tagName === options.commentPropName) { - xmlStr += indentation + ``; - isPreviousElementTag = true; - continue; - } else if (tagName[0] === "?") { - const attStr = attr_to_str(tagObj[":@"], options); - const tempInd = tagName === "?xml" ? "" : indentation; - let piTextNodeName = tagObj[tagName][0][options.textNodeName]; - piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing - xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; - isPreviousElementTag = true; - continue; - } - let newIdentation = indentation; - if (newIdentation !== "") { - newIdentation += options.indentBy; + Object.keys(obj).forEach( + function (key) { + var index = isArray && this.useBrackets ? '[' + key + ']' : key + if ( + isArrayOrObject(obj[key]) && + ((isObject(obj[key]) && !isEmptyObject(obj[key])) || + (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) + ) { + if (isArray && this.useBrackets) { + var previousKey = path[path.length - 1] || '' + return this.dot( + obj[key], + tgt, + path.slice(0, -1).concat(previousKey + index) + ) + } else { + return this.dot(obj[key], tgt, path.concat(index)) } - const attStr = attr_to_str(tagObj[":@"], options); - const tagStart = indentation + `<${tagName}${attStr}`; - const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); - if (options.unpairedTags.indexOf(tagName) !== -1) { - if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; - else xmlStr += tagStart + "/>"; - } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { - xmlStr += tagStart + "/>"; - } else if (tagValue && tagValue.endsWith(">")) { - xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + if (isArray && this.useBrackets) { + tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] } else { - xmlStr += tagStart + ">"; - if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + tgt[path.concat(index).join(this.separator)] = obj[key] } - isPreviousElementTag = true; - } - - return xmlStr; + } + }.bind(this) + ) + return tgt } -function propName(obj) { - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(!obj.hasOwnProperty(key)) continue; - if (key !== ":@") return key; +DotObject.pick = wrap('pick') +DotObject.move = wrap('move') +DotObject.transfer = wrap('transfer') +DotObject.transform = wrap('transform') +DotObject.copy = wrap('copy') +DotObject.object = wrap('object') +DotObject.str = wrap('str') +DotObject.set = wrap('set') +DotObject.delete = wrap('delete') +DotObject.del = DotObject.remove = wrap('remove') +DotObject.dot = wrap('dot'); +['override', 'overwrite'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault.override + }, + set: function (val) { + dotDefault.override = !!val } -} - -function attr_to_str(attrMap, options) { - let attrStr = ""; - if (attrMap && !options.ignoreAttributes) { - for (let attr in attrMap) { - if(!attrMap.hasOwnProperty(attr)) continue; - let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); - attrVal = replaceEntitiesValue(attrVal, options); - if (attrVal === true && options.suppressBooleanAttributes) { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; - } else { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; - } - } + }) +}); +['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault[prop] + }, + set: function (val) { + dotDefault[prop] = val } - return attrStr; -} + }) +}) -function isStopNode(jPath, options) { - jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); - let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); - for (let index in options.stopNodes) { - if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; - } - return false; -} +DotObject._process = _process -function replaceEntitiesValue(textValue, options) { - if (textValue && textValue.length > 0 && options.processEntities) { - for (let i = 0; i < options.entities.length; i++) { - const entity = options.entities[i]; - textValue = textValue.replace(entity.regex, entity.val); - } - } - return textValue; -} -module.exports = toXml; +module.exports = DotObject /***/ }), -/***/ 6072: +/***/ 81205: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const util = __nccwpck_require__(38280); +var once = __nccwpck_require__(1223); -//TODO: handle comments -function readDocType(xmlData, i){ - - const entities = {}; - if( xmlData[i + 3] === 'O' && - xmlData[i + 4] === 'C' && - xmlData[i + 5] === 'T' && - xmlData[i + 6] === 'Y' && - xmlData[i + 7] === 'P' && - xmlData[i + 8] === 'E') - { - i = i+9; - let angleBracketsCount = 1; - let hasBody = false, comment = false; - let exp = ""; - for(;i') { //Read tag content - if(comment){ - if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ - comment = false; - angleBracketsCount--; - } - }else{ - angleBracketsCount--; - } - if (angleBracketsCount === 0) { - break; - } - }else if( xmlData[i] === '['){ - hasBody = true; - }else{ - exp += xmlData[i]; - } - } - if(angleBracketsCount !== 0){ - throw new Error(`Unclosed DOCTYPE`); - } - }else{ - throw new Error(`Invalid Tag instead of DOCTYPE`); - } - return {entities, i}; -} +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; -function readEntityExp(xmlData,i){ - //External entities are not supported - // +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - //Parameter entities are not supported - // +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - //Internal entities are supported - // - - //read EntityName - let entityName = ""; - for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { - // if(xmlData[i] === " ") continue; - // else - entityName += xmlData[i]; - } - entityName = entityName.trim(); - if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); + callback = once(callback || noop); - //read Entity Value - const startChar = xmlData[i++]; - let val = "" - for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { - val += xmlData[i]; - } - return [entityName, val, i]; -} + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; -function isComment(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === '-' && - xmlData[i+3] === '-') return true - return false -} -function isEntity(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'E' && - xmlData[i+3] === 'N' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'I' && - xmlData[i+6] === 'T' && - xmlData[i+7] === 'Y') return true - return false -} -function isElement(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'E' && - xmlData[i+3] === 'L' && - xmlData[i+4] === 'E' && - xmlData[i+5] === 'M' && - xmlData[i+6] === 'E' && - xmlData[i+7] === 'N' && - xmlData[i+8] === 'T') return true - return false -} + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; -function isAttlist(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'A' && - xmlData[i+3] === 'T' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'L' && - xmlData[i+6] === 'I' && - xmlData[i+7] === 'S' && - xmlData[i+8] === 'T') return true - return false -} -function isNotation(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'N' && - xmlData[i+3] === 'O' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'A' && - xmlData[i+6] === 'T' && - xmlData[i+7] === 'I' && - xmlData[i+8] === 'O' && - xmlData[i+9] === 'N') return true - return false -} + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; -function validateEntityName(name){ - if (util.isName(name)) - return name; - else - throw new Error(`Invalid entity name ${name}`); -} + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; -module.exports = readDocType; + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + var onerror = function(err) { + callback.call(stream, err); + }; -/***/ }), + var onclose = function() { + process.nextTick(onclosenexttick); + }; -/***/ 86993: -/***/ ((__unused_webpack_module, exports) => { + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; + var onrequest = function() { + stream.req.on('finish', onfinish); + }; -const defaultOptions = { - preserveOrder: false, - attributeNamePrefix: '@_', - attributesGroupName: false, - textNodeName: '#text', - ignoreAttributes: true, - removeNSPrefix: false, // remove NS from tag name or attribute name if true - allowBooleanAttributes: false, //a tag can have attributes without any value - //ignoreRootElement : false, - parseTagValue: true, - parseAttributeValue: false, - trimValues: true, //Trim string values of tag and attributes - cdataPropName: false, - numberParseOptions: { - hex: true, - leadingZeros: true, - eNotation: true - }, - tagValueProcessor: function(tagName, val) { - return val; - }, - attributeValueProcessor: function(attrName, val) { - return val; - }, - stopNodes: [], //nested tags will not be parsed even for errors - alwaysCreateTextNode: false, - isArray: () => false, - commentPropName: false, - unpairedTags: [], - processEntities: true, - htmlEntities: false, - ignoreDeclaration: false, - ignorePiTags: false, - transformTagName: false, - transformAttributeName: false, - updateTag: function(tagName, jPath, attrs){ - return tagName - }, - // skipEmptyListItem: false -}; - -const buildOptions = function(options) { - return Object.assign({}, defaultOptions, options); + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; }; -exports.buildOptions = buildOptions; -exports.defaultOptions = defaultOptions; +module.exports = eos; + /***/ }), -/***/ 25832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 34852: +/***/ ((module, exports) => { "use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ -///@ts-check - -const util = __nccwpck_require__(38280); -const xmlNode = __nccwpck_require__(7462); -const readDocType = __nccwpck_require__(6072); -const toNumber = __nccwpck_require__(14526); -const getIgnoreAttributesFn = __nccwpck_require__(4958) -// const regx = -// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' -// .replace(/NAME/g, util.nameRegexp); +Object.defineProperty(exports, "__esModule", ({ value: true })); -//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); -//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ -class OrderedObjParser{ - constructor(options){ - this.options = options; - this.currentNode = null; - this.tagsNodeStack = []; - this.docTypeEntities = {}; - this.lastEntities = { - "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, - "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, - "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, - "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, - }; - this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; - this.htmlEntities = { - "space": { regex: /&(nbsp|#160);/g, val: " " }, - // "lt" : { regex: /&(lt|#60);/g, val: "<" }, - // "gt" : { regex: /&(gt|#62);/g, val: ">" }, - // "amp" : { regex: /&(amp|#38);/g, val: "&" }, - // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, - // "apos" : { regex: /&(apos|#39);/g, val: "'" }, - "cent" : { regex: /&(cent|#162);/g, val: "¢" }, - "pound" : { regex: /&(pound|#163);/g, val: "£" }, - "yen" : { regex: /&(yen|#165);/g, val: "¥" }, - "euro" : { regex: /&(euro|#8364);/g, val: "€" }, - "copyright" : { regex: /&(copy|#169);/g, val: "©" }, - "reg" : { regex: /&(reg|#174);/g, val: "®" }, - "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, - "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, - "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, - }; - this.addExternalEntities = addExternalEntities; - this.parseXml = parseXml; - this.parseTextData = parseTextData; - this.resolveNameSpace = resolveNameSpace; - this.buildAttributesMap = buildAttributesMap; - this.isItStopNode = isItStopNode; - this.replaceEntitiesValue = replaceEntitiesValue; - this.readStopNodeData = readStopNodeData; - this.saveTextToParentTag = saveTextToParentTag; - this.addChild = addChild; - this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) - } +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); -} +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); -function addExternalEntities(externalEntities){ - const entKeys = Object.keys(externalEntities); - for (let i = 0; i < entKeys.length; i++) { - const ent = entKeys[i]; - this.lastEntities[ent] = { - regex: new RegExp("&"+ent+";","g"), - val : externalEntities[ent] - } - } +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv } /** - * @param {string} val - * @param {string} tagName - * @param {string} jPath - * @param {boolean} dontTrim - * @param {boolean} hasAttributes - * @param {boolean} isLeafNode - * @param {boolean} escapeEntities + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. */ -function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { - if (val !== undefined) { - if (this.options.trimValues && !dontTrim) { - val = val.trim(); - } - if(val.length > 0){ - if(!escapeEntities) val = this.replaceEntitiesValue(val); - - const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); - if(newval === null || newval === undefined){ - //don't parse - return val; - }else if(typeof newval !== typeof val || newval !== val){ - //overwrite - return newval; - }else if(this.options.trimValues){ - return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); - }else{ - const trimmedVal = val.trim(); - if(trimmedVal === val){ - return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); - }else{ - return val; +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); } - } + return } - } -} - -function resolveNameSpace(tagname) { - if (this.options.removeNSPrefix) { - const tags = tagname.split(':'); - const prefix = tagname.charAt(0) === '/' ? '/' : ''; - if (tags[0] === 'xmlns') { - return ''; + if (!data.event.cancelable) { + return } - if (tags.length === 2) { - tagname = prefix + tags[1]; + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); } - } - return tagname; } -//TODO: change regex to capture NS -//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); -const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); -function buildAttributesMap(attrStr, jPath, tagName) { - if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') { - // attrStr = attrStr.replace(/\r?\n/g, ' '); - //attrStr = attrStr || attrStr.trim(); + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); - const matches = util.getAllMatches(attrStr, attrsRegx); - const len = matches.length; //don't make it inline - const attrs = {}; - for (let i = 0; i < len; i++) { - const attrName = this.resolveNameSpace(matches[i][1]); - if (this.ignoreAttributesFn(attrName, jPath)) { - continue - } - let oldVal = matches[i][4]; - let aName = this.options.attributeNamePrefix + attrName; - if (attrName.length) { - if (this.options.transformAttributeName) { - aName = this.options.transformAttributeName(aName); - } - if(aName === "__proto__") aName = "#__proto__"; - if (oldVal !== undefined) { - if (this.options.trimValues) { - oldVal = oldVal.trim(); - } - oldVal = this.replaceEntitiesValue(oldVal); - const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); - if(newVal === null || newVal === undefined){ - //don't parse - attrs[aName] = oldVal; - }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ - //overwrite - attrs[aName] = newVal; - }else{ - //parse - attrs[aName] = parseValue( - oldVal, - this.options.parseAttributeValue, - this.options.numberParseOptions - ); - } - } else if (this.options.allowBooleanAttributes) { - attrs[aName] = true; + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); } - } } - if (!Object.keys(attrs).length) { - return; - } - if (this.options.attributesGroupName) { - const attrCollection = {}; - attrCollection[this.options.attributesGroupName] = attrs; - return attrCollection; - } - return attrs - } } -const parseXml = function(xmlData) { - xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line - const xmlObj = new xmlNode('!xml'); - let currentNode = xmlObj; - let textData = ""; - let jPath = ""; - for(let i=0; i< xmlData.length; i++){//for each char in XML data - const ch = xmlData[i]; - if(ch === '<'){ - // const nextIndex = i+1; - // const _2ndChar = xmlData[nextIndex]; - if( xmlData[i+1] === '/') {//Closing Tag - const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") - let tagName = xmlData.substring(i+2,closeIndex).trim(); +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, - if(this.options.removeNSPrefix){ - const colonIndex = tagName.indexOf(":"); - if(colonIndex !== -1){ - tagName = tagName.substr(colonIndex+1); - } - } + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, - if(this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, - if(currentNode){ - textData = this.saveTextToParentTag(textData, currentNode, jPath); + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] } + return [currentTarget] + }, - //check if last tag of nested tag was unpaired tag - const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); - if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ - throw new Error(`Unpaired tag can not be used as closing tag: `); + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); } - let propIndex = 0 - if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ - propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) - this.tagsNodeStack.pop(); - }else{ - propIndex = jPath.lastIndexOf("."); + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); } - jPath = jPath.substring(0, propIndex); + }, - currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope - textData = ""; - i = closeIndex; - } else if( xmlData[i+1] === '?') { + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, - let tagData = readTagExp(xmlData,i, false, "?>"); - if(!tagData) throw new Error("Pi Tag is not closed."); + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, - textData = this.saveTextToParentTag(textData, currentNode, jPath); - if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, - }else{ - - const childNode = new xmlNode(tagData.tagName); - childNode.add(this.options.textNodeName, ""); - - if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); - } - this.addChild(currentNode, childNode, jPath) + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; } + }, + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, - i = tagData.closeIndex + 1; - } else if(xmlData.substr(i + 1, 3) === '!--') { - const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") - if(this.options.commentPropName){ - const comment = xmlData.substring(i + 4, endIndex - 2); + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; - textData = this.saveTextToParentTag(textData, currentNode, jPath); +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); - currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); - } - i = endIndex; - } else if( xmlData.substr(i + 1, 2) === '!D') { - const result = readDocType(xmlData, i); - this.docTypeEntities = result.entities; - i = result.i; - }else if(xmlData.substr(i + 1, 2) === '![') { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; - const tagExp = xmlData.substring(i + 9,closeIndex); +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); - textData = this.saveTextToParentTag(textData, currentNode, jPath); + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} - let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); - if(val == undefined) val = ""; +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} - //cdata should be set even if it is 0 length string - if(this.options.cdataPropName){ - currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); - }else{ - currentNode.add(this.options.textNodeName, val); - } - - i = closeIndex + 2; - }else {//Opening tag - let result = readTagExp(xmlData,i, this.options.removeNSPrefix); - let tagName= result.tagName; - const rawTagName = result.rawTagName; - let tagExp = result.tagExp; - let attrExpPresent = result.attrExpPresent; - let closeIndex = result.closeIndex; +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } - - //save text as child node - if (currentNode && textData) { - if(currentNode.tagname !== '!xml'){ - //when nested tag is found - textData = this.saveTextToParentTag(textData, currentNode, jPath, false); - } - } +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } - //check if last tag was unpaired tag - const lastTag = currentNode; - if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ - currentNode = this.tagsNodeStack.pop(); - jPath = jPath.substring(0, jPath.lastIndexOf(".")); - } - if(tagName !== xmlObj.tagname){ - jPath += jPath ? "." + tagName : tagName; - } - if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { - let tagContent = ""; - //self-closing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); - } - i = result.closeIndex; - } - //unpaired tag - else if(this.options.unpairedTags.indexOf(tagName) !== -1){ - - i = result.closeIndex; - } - //normal tag - else{ - //read until closing tag is found - const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); - if(!result) throw new Error(`Unexpected end of ${rawTagName}`); - i = result.i; - tagContent = result.tagContent; - } + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } - const childNode = new xmlNode(tagName); - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - if(tagContent) { - tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); - } - - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - childNode.add(this.options.textNodeName, tagContent); - - this.addChild(currentNode, childNode, jPath) - }else{ - //selfClosing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); - } - - if(this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); - const childNode = new xmlNode(tagName); - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - this.addChild(currentNode, childNode, jPath) - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - } - //opening tag - else{ - const childNode = new xmlNode( tagName); - this.tagsNodeStack.push(currentNode); - - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - this.addChild(currentNode, childNode, jPath) - currentNode = childNode; - } - textData = ""; - i = closeIndex; + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); } - } - }else{ - textData += xmlData[i]; } - } - return xmlObj.child; -} -function addChild(currentNode, childNode, jPath){ - const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) - if(result === false){ - }else if(typeof result === "string"){ - childNode.tagname = result - currentNode.addChild(childNode); - }else{ - currentNode.addChild(childNode); - } + return CustomEvent } -const replaceEntitiesValue = function(val){ - - if(this.options.processEntities){ - for(let entityName in this.docTypeEntities){ - const entity = this.docTypeEntities[entityName]; - val = val.replace( entity.regx, entity.val); - } - for(let entityName in this.lastEntities){ - const entity = this.lastEntities[entityName]; - val = val.replace( entity.regex, entity.val); +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event } - if(this.options.htmlEntities){ - for(let entityName in this.htmlEntities){ - const entity = this.htmlEntities[entityName]; - val = val.replace( entity.regex, entity.val); - } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); } - val = val.replace( this.ampEntity.regex, this.ampEntity.val); - } - return val; + return wrapper } -function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { - if (textData) { //store previously collected data as textNode - if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0 - - textData = this.parseTextData(textData, - currentNode.tagname, - jPath, - false, - currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, - isLeafNode); - if (textData !== undefined && textData !== "") - currentNode.add(this.options.textNodeName, textData); - textData = ""; - } - return textData; +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) } -//TODO: use jPath to simplify the logic /** - * - * @param {string[]} stopNodes - * @param {string} jPath - * @param {string} currentTagName + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private */ -function isItStopNode(stopNodes, jPath, currentTagName){ - const allNodesExp = "*." + currentTagName; - for (const stopNodePath in stopNodes) { - const stopNodeExp = stopNodes[stopNodePath]; - if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; - } - return false; +function isStopped(event) { + return pd(event).immediateStopped } /** - * Returns the tag Expression and where it is ending handling single-double quotes situation - * @param {string} xmlData - * @param {number} i starting index - * @returns + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private */ -function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ - let attrBoundary; - let tagExp = ""; - for (let index = i; index < xmlData.length; index++) { - let ch = xmlData[index]; - if (attrBoundary) { - if (ch === attrBoundary) attrBoundary = "";//reset - } else if (ch === '"' || ch === "'") { - attrBoundary = ch; - } else if (ch === closingChar[0]) { - if(closingChar[1]){ - if(xmlData[index + 1] === closingChar[1]){ - return { - data: tagExp, - index: index - } - } - }else{ - return { - data: tagExp, - index: index - } - } - } else if (ch === '\t') { - ch = " " - } - tagExp += ch; - } +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; } -function findClosingIndex(xmlData, str, i, errMsg){ - const closingIndex = xmlData.indexOf(str, i); - if(closingIndex === -1){ - throw new Error(errMsg) - }else{ - return closingIndex + str.length - 1; - } +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; } -function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ - const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); - if(!result) return; - let tagExp = result.data; - const closeIndex = result.index; - const separatorIndex = tagExp.search(/\s/); - let tagName = tagExp; - let attrExpPresent = true; - if(separatorIndex !== -1){//separate tag name and attributes expression - tagName = tagExp.substring(0, separatorIndex); - tagExp = tagExp.substring(separatorIndex + 1).trimStart(); - } +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} - const rawTagName = tagName; - if(removeNSPrefix){ - const colonIndex = tagName.indexOf(":"); - if(colonIndex !== -1){ - tagName = tagName.substr(colonIndex+1); - attrExpPresent = tagName !== result.data.substr(colonIndex + 1); - } - } +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ - return { - tagName: tagName, - tagExp: tagExp, - closeIndex: closeIndex, - attrExpPresent: attrExpPresent, - rawTagName: rawTagName, - } -} /** - * find paired tag for a stop node - * @param {string} xmlData - * @param {string} tagName - * @param {number} i + * @type {WeakMap>} + * @private */ -function readStopNodeData(xmlData, tagName, i){ - const startIndex = i; - // Starting at 1 since we already have an open tag - let openTagCount = 1; +const listenersMap = new WeakMap(); - for (; i < xmlData.length; i++) { - if( xmlData[i] === "<"){ - if (xmlData[i+1] === "/") {//close tag - const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); - let closeTagName = xmlData.substring(i+2,closeIndex).trim(); - if(closeTagName === tagName){ - openTagCount--; - if (openTagCount === 0) { - return { - tagContent: xmlData.substring(startIndex, i), - i : closeIndex - } - } - } - i=closeIndex; - } else if(xmlData[i+1] === '?') { - const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") - i=closeIndex; - } else if(xmlData.substr(i + 1, 3) === '!--') { - const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") - i=closeIndex; - } else if(xmlData.substr(i + 1, 2) === '![') { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; - i=closeIndex; - } else { - const tagData = readTagExp(xmlData, i, '>') +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; - if (tagData) { - const openTagName = tagData && tagData.tagName; - if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { - openTagCount++; - } - i=tagData.closeIndex; - } - } - } - }//end for loop +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax } -function parseValue(val, shouldParse, options) { - if (shouldParse && typeof val === 'string') { - //console.log(options) - const newval = val.trim(); - if(newval === 'true' ) return true; - else if(newval === 'false' ) return false; - else return toNumber(val, options); - } else { - if (util.isExist(val)) { - return val; - } else { - return ''; +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) } - } + return listeners } +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, -module.exports = OrderedObjParser; - - -/***/ }), - -/***/ 42380: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); -const { buildOptions} = __nccwpck_require__(86993); -const OrderedObjParser = __nccwpck_require__(25832); -const { prettify} = __nccwpck_require__(42882); -const validator = __nccwpck_require__(61739); + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } -class XMLParser{ - - constructor(options){ - this.externalEntities = {}; - this.options = buildOptions(options); - - } - /** - * Parse XML dats to JS object - * @param {string|Buffer} xmlData - * @param {boolean|Object} validationOption - */ - parse(xmlData,validationOption){ - if(typeof xmlData === "string"){ - }else if( xmlData.toString){ - xmlData = xmlData.toString(); - }else{ - throw new Error("XML data is accepted in String or Bytes[] form.") - } - if( validationOption){ - if(validationOption === true) validationOption = {}; //validate with default options - - const result = validator.validate(xmlData, validationOption); - if (result !== true) { - throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + node = node.next; } - } - const orderedObjParser = new OrderedObjParser(this.options); - orderedObjParser.addExternalEntities(this.externalEntities); - const orderedResult = orderedObjParser.parseXml(xmlData); - if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; - else return prettify(orderedResult, this.options); - } - /** - * Add Entity which is not by default supported by this library - * @param {string} key - * @param {string} value - */ - addEntity(key, value){ - if(value.indexOf("&") !== -1){ - throw new Error("Entity value can't have '&'") - }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ - throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") - }else if(value === "&"){ - throw new Error("An entity with value '&' is not permitted"); - }else{ - this.externalEntities[key] = value; - } + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, } } -module.exports = XMLParser; - -/***/ }), - -/***/ 42882: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - /** - * - * @param {array} node - * @param {any} options - * @returns + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} */ -function prettify(node, options){ - return compress( node, options); +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); } /** - * - * @param {array} arr - * @param {object} options - * @param {string} jPath - * @returns object + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private */ -function compress(arr, options, jPath){ - let text; - const compressedObj = {}; - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const property = propName(tagObj); - let newJpath = ""; - if(jPath === undefined) newJpath = property; - else newJpath = jPath + "." + property; - - if(property === options.textNodeName){ - if(text === undefined) text = tagObj[property]; - else text += "" + tagObj[property]; - }else if(property === undefined){ - continue; - }else if(tagObj[property]){ - - let val = compress(tagObj[property], options, newJpath); - const isLeaf = isLeafTag(val, options); - - if(tagObj[":@"]){ - assignAttributes( val, tagObj[":@"], newJpath, options); - }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ - val = val[options.textNodeName]; - }else if(Object.keys(val).length === 0){ - if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; - else val = ""; - } - - if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { - if(!Array.isArray(compressedObj[property])) { - compressedObj[property] = [ compressedObj[property] ]; - } - compressedObj[property].push(val); - }else{ - //TODO: if a node is not an array, then check if it should be an array - //also determine if it is a leaf node - if (options.isArray(property, newJpath, isLeaf )) { - compressedObj[property] = [val]; - }else{ - compressedObj[property] = val; - } - } +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); } - - } - // if(text && text.length > 0) compressedObj[options.textNodeName] = text; - if(typeof text === "string"){ - if(text.length > 0) compressedObj[options.textNodeName] = text; - }else if(text !== undefined) compressedObj[options.textNodeName] = text; - return compressedObj; -} -function propName(obj){ - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(key !== ":@") return key; - } -} + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); -function assignAttributes(obj, attrMap, jpath, options){ - if (attrMap) { - const keys = Object.keys(attrMap); - const len = keys.length; //don't make it inline - for (let i = 0; i < len; i++) { - const atrrName = keys[i]; - if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { - obj[atrrName] = [ attrMap[atrrName] ]; - } else { - obj[atrrName] = attrMap[atrrName]; - } + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } - } -} - -function isLeafTag(obj, options){ - const { textNodeName } = options; - const propCount = Object.keys(obj).length; - - if (propCount === 0) { - return true; - } - - if ( - propCount === 1 && - (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) - ) { - return true; - } - return false; + return CustomEventTarget } -exports.prettify = prettify; - - -/***/ }), - -/***/ 7462: -/***/ ((module) => { -"use strict"; - - -class XmlNode{ - constructor(tagname) { - this.tagname = tagname; - this.child = []; //nested tags, text, cdata, comments in order - this[":@"] = {}; //attributes map - } - add(key,val){ - // this.child.push( {name : key, val: val, isCdata: isCdata }); - if(key === "__proto__") key = "#__proto__"; - this.child.push( {[key]: val }); - } - addChild(node) { - if(node.tagname === "__proto__") node.tagname = "#__proto__"; - if(node[":@"] && Object.keys(node[":@"]).length > 0){ - this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); - }else{ - this.child.push( { [node.tagname]: node.child }); +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return } - }; -}; - - -module.exports = XmlNode; - -/***/ }), + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} -/***/ 7340: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } -"use strict"; + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } -/* eslint-disable no-var */ + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } -var reusify = __nccwpck_require__(32113) + // Add it. + prev.next = newNode; + }, -function fastqueue (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker - worker = context - context = null - } + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } - if (concurrency < 1) { - throw new Error('fastqueue concurrency must be greater than 1') - } + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; - var cache = reusify(Task) - var queueHead = null - var queueTail = null - var _running = 0 - var errorHandler = null + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } - var self = { - push: push, - drain: noop, - saturated: noop, - pause: pause, - paused: false, - concurrency: concurrency, - running: running, - resume: resume, - idle: idle, - length: length, - getQueue: getQueue, - unshift: unshift, - empty: noop, - kill: kill, - killAndDrain: killAndDrain, - error: error - } + prev = node; + node = node.next; + } + }, - return self + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } - function running () { - return _running - } + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } - function pause () { - self.paused = true - } + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); - function length () { - var current = queueHead - var counter = 0 + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } - while (current) { - current = current.next - counter++ - } + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } - return counter - } + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } - function getQueue () { - var current = queueHead - var tasks = [] + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); - while (current) { - tasks.push(current.value) - current = current.next - } + return !wrappedEvent.defaultPrevented + }, +}; - return tasks - } +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); - function resume () { - if (!self.paused) return - self.paused = false - for (var i = 0; i < self.concurrency; i++) { - _running++ - release() - } - } +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} - function idle () { - return _running === 0 && self.length() === 0 - } +exports.defineEventAttribute = defineEventAttribute; +exports.EventTarget = EventTarget; +exports["default"] = EventTarget; - function push (value, done) { - var current = cache.get() +module.exports = EventTarget +module.exports.EventTarget = module.exports["default"] = EventTarget +module.exports.defineEventAttribute = defineEventAttribute +//# sourceMappingURL=event-target-shim.js.map - current.context = context - current.release = release - current.value = value - current.callback = done || noop - current.errorHandler = errorHandler - if (_running === self.concurrency || self.paused) { - if (queueTail) { - queueTail.next = current - queueTail = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } +/***/ }), - function unshift (value, done) { - var current = cache.get() +/***/ 11848: +/***/ ((module) => { - current.context = context - current.release = release - current.value = value - current.callback = done || noop +"use strict"; - if (_running === self.concurrency || self.paused) { - if (queueHead) { - current.next = queueHead - queueHead = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } - function release (holder) { - if (holder) { - cache.release(holder) - } - var next = queueHead - if (next) { - if (!self.paused) { - if (queueTail === queueHead) { - queueTail = null - } - queueHead = next.next - next.next = null - worker.call(context, next.value, next.worked) - if (queueTail === null) { - self.empty() - } - } else { - _running-- - } - } else if (--_running === 0) { - self.drain() - } - } +var has = Object.prototype.hasOwnProperty + , prefix = '~'; - function kill () { - queueHead = null - queueTail = null - self.drain = noop - } +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} - function killAndDrain () { - queueHead = null - queueTail = null - self.drain() - self.drain = noop - } +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); - function error (handler) { - errorHandler = handler - } + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; } -function noop () {} - -function Task () { - this.value = null - this.callback = noop - this.next = null - this.release = noop - this.context = null - this.errorHandler = null - - var self = this - - this.worked = function worked (err, result) { - var callback = self.callback - var errorHandler = self.errorHandler - var val = self.value - self.value = null - self.callback = noop - if (self.errorHandler) { - errorHandler(err, val) - } - callback.call(self.context, err, result) - self.release(self) - } +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; } -function queueAsPromised (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker - worker = context - context = null +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); } - function asyncWrapper (arg, cb) { - worker.call(this, arg) - .then(function (res) { - cb(null, res) - }, cb) - } + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; - var queue = fastqueue(context, asyncWrapper, concurrency) + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; - var pushCb = queue.push - var unshiftCb = queue.unshift + return emitter; +} - queue.push = push - queue.unshift = unshift - queue.drained = drained +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} - return queue +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} - function push (value) { - var p = new Promise(function (resolve, reject) { - pushCb(value, function (err, result) { - if (err) { - reject(err) - return - } - resolve(result) - }) - }) +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop) + if (this._eventsCount === 0) return names; - return p + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } - function unshift (value) { - var p = new Promise(function (resolve, reject) { - unshiftCb(value, function (err, result) { - if (err) { - reject(err) - return - } - resolve(result) - }) - }) - - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop) - - return p + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); } - function drained () { - var previousDrain = queue.drain + return names; +}; - var p = new Promise(function (resolve) { - queue.drain = function () { - previousDrain() - resolve() - } - }) +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - return p - } -} + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; -module.exports = fastqueue -module.exports.promise = queueAsPromised + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + return ee; +}; -/***/ }), +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; -/***/ 6330: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; -"use strict"; -/*! - * fill-range +/** + * Calls each of the listeners registered for a given event. * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt] + , len = arguments.length + , args + , i; -const util = __nccwpck_require__(73837); -const toRegexRange = __nccwpck_require__(1861); + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); -const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } -const transform = toNumber => { - return value => toNumber === true ? Number(value) : String(value); -}; + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } -const isValidValue = value => { - return typeof value === 'number' || (typeof value === 'string' && value !== ''); -}; + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; -const isNumber = num => Number.isInteger(+num); + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); -const zeros = input => { - let value = `${input}`; - let index = -1; - if (value[0] === '-') value = value.slice(1); - if (value === '0') return false; - while (value[++index] === '0'); - return index > 0; -}; + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } -const stringify = (start, end, options) => { - if (typeof start === 'string' || typeof end === 'string') { - return true; + listeners[i].fn.apply(listeners[i].context, args); + } + } } - return options.stringify === true; -}; -const pad = (input, maxLength, toNumber) => { - if (maxLength > 0) { - let dash = input[0] === '-' ? '-' : ''; - if (dash) input = input.slice(1); - input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); - } - if (toNumber === false) { - return String(input); - } - return input; + return true; }; -const toMaxLen = (input, maxLength) => { - let negative = input[0] === '-' ? '-' : ''; - if (negative) { - input = input.slice(1); - maxLength--; - } - while (input.length < maxLength) input = '0' + input; - return negative ? ('-' + input) : input; +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); }; -const toSequence = (parts, options) => { - parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; - let prefix = options.capture ? '' : '?:'; - let positives = ''; - let negatives = ''; - let result; +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; - if (parts.positives.length) { - positives = parts.positives.join('|'); + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; } - if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.join('|')})`; - } + var listeners = this._events[evt]; - if (positives && negatives) { - result = `${positives}|${negatives}`; + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } } else { - result = positives || negatives; - } + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } - if (options.wrap) { - return `(${prefix}${result})`; + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); } - return result; + return this; }; -const toRange = (a, b, isNumbers, options) => { - if (isNumbers) { - return toRegexRange(a, b, { wrap: false, ...options }); - } - - let start = String.fromCharCode(a); - if (a === b) return start; - - let stop = String.fromCharCode(b); - return `[${start}-${stop}]`; -}; +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; -const toRegex = (start, end, options) => { - if (Array.isArray(start)) { - let wrap = options.wrap === true; - let prefix = options.capture ? '' : '?:'; - return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; } - return toRegexRange(start, end, options); -}; -const rangeError = (...args) => { - return new RangeError('Invalid range arguments: ' + util.inspect(...args)); + return this; }; -const invalidRange = (start, end, options) => { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; -}; +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; -const invalidStep = (step, options) => { - if (options.strictRanges === true) { - throw new TypeError(`Expected step "${step}" to be a number`); - } - return []; -}; +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; -const fillNumbers = (start, end, step = 1, options = {}) => { - let a = Number(start); - let b = Number(end); +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; - if (!Number.isInteger(a) || !Number.isInteger(b)) { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; - } +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} - // fix negative zero - if (a === 0) a = 0; - if (b === 0) b = 0; - let descending = a > b; - let startString = String(start); - let endString = String(end); - let stepString = String(step); - step = Math.max(Math.abs(step), 1); +/***/ }), - let padded = zeros(startString) || zeros(endString) || zeros(stepString); - let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; - let toNumber = padded === false && stringify(start, end, options) === false; - let format = options.transform || transform(toNumber); +/***/ 27030: +/***/ ((module) => { - if (options.toRegex && step === 1) { - return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); +module.exports = class FixedFIFO { + constructor (hwm) { + if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') + this.buffer = new Array(hwm) + this.mask = hwm - 1 + this.top = 0 + this.btm = 0 + this.next = null } - let parts = { negatives: [], positives: [] }; - let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); - let range = []; - let index = 0; + clear () { + this.top = this.btm = 0 + this.next = null + this.buffer.fill(undefined) + } - while (descending ? a >= b : a <= b) { - if (options.toRegex === true && step > 1) { - push(a); - } else { - range.push(pad(format(a, index), maxLen, toNumber)); - } - a = descending ? a - step : a + step; - index++; + push (data) { + if (this.buffer[this.top] !== undefined) return false + this.buffer[this.top] = data + this.top = (this.top + 1) & this.mask + return true } - if (options.toRegex === true) { - return step > 1 - ? toSequence(parts, options) - : toRegex(range, null, { wrap: false, ...options }); + shift () { + const last = this.buffer[this.btm] + if (last === undefined) return undefined + this.buffer[this.btm] = undefined + this.btm = (this.btm + 1) & this.mask + return last } - return range; -}; + peek () { + return this.buffer[this.btm] + } -const fillLetters = (start, end, step = 1, options = {}) => { - if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { - return invalidRange(start, end, options); + isEmpty () { + return this.buffer[this.btm] === undefined } +} - let format = options.transform || (val => String.fromCharCode(val)); - let a = `${start}`.charCodeAt(0); - let b = `${end}`.charCodeAt(0); +/***/ }), - let descending = a > b; - let min = Math.min(a, b); - let max = Math.max(a, b); +/***/ 92958: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options.toRegex && step === 1) { - return toRange(min, max, false, options); - } +const FixedFIFO = __nccwpck_require__(27030) - let range = []; - let index = 0; +module.exports = class FastFIFO { + constructor (hwm) { + this.hwm = hwm || 16 + this.head = new FixedFIFO(this.hwm) + this.tail = this.head + this.length = 0 + } - while (descending ? a >= b : a <= b) { - range.push(format(a, index)); - a = descending ? a - step : a + step; - index++; + clear () { + this.head = this.tail + this.head.clear() + this.length = 0 } - if (options.toRegex === true) { - return toRegex(range, null, { wrap: false, options }); + push (val) { + this.length++ + if (!this.head.push(val)) { + const prev = this.head + this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length) + this.head.push(val) + } } - return range; -}; + shift () { + if (this.length !== 0) this.length-- + const val = this.tail.shift() + if (val === undefined && this.tail.next) { + const next = this.tail.next + this.tail.next = null + this.tail = next + return this.tail.shift() + } -const fill = (start, end, step, options = {}) => { - if (end == null && isValidValue(start)) { - return [start]; + return val } - if (!isValidValue(start) || !isValidValue(end)) { - return invalidRange(start, end, options); + peek () { + const val = this.tail.peek() + if (val === undefined && this.tail.next) return this.tail.next.peek() + return val } - if (typeof step === 'function') { - return fill(start, end, 1, { transform: step }); + isEmpty () { + return this.length === 0 } +} - if (isObject(step)) { - return fill(start, end, 0, step); - } - let opts = { ...options }; - if (opts.capture === true) opts.wrap = true; - step = step || opts.step || 1; +/***/ }), - if (!isNumber(step)) { - if (step != null && !isObject(step)) return invalidStep(step, opts); - return fill(start, end, 1, step); - } +/***/ 35582: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isNumber(start) && isNumber(end)) { - return fillNumbers(start, end, step, opts); +"use strict"; + + +const stringify = __nccwpck_require__(64810); +const compile = __nccwpck_require__(7123); +const expand = __nccwpck_require__(46944); +const parse = __nccwpck_require__(79889); + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (const pattern of input) { + const result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); } - return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; }; -module.exports = fill; +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ +braces.parse = (input, options = {}) => parse(input, options); -/***/ }), +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -/***/ 43338: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); +}; -"use strict"; +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile(input, options); +}; -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const mkdirsSync = (__nccwpck_require__(98605).mkdirsSync) -const utimesMillisSync = (__nccwpck_require__(52548).utimesMillisSync) -const stat = __nccwpck_require__(73901) +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -function copySync (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts } +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); } - opts = opts || {} - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + let result = expand(input, options); - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); } - const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy') - stat.checkParentPathsSync(src, srcStat, dest, 'copy') - return handleFilterAndCopy(destStat, src, dest, opts) -} + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } -function handleFilterAndCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path.dirname(dest) - if (!fs.existsSync(destParent)) mkdirsSync(destParent) - return startCopy(destStat, src, dest, opts) -} + return result; +}; -function startCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - return getStats(destStat, src, dest, opts) -} +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs.statSync : fs.lstatSync - const srcStat = statSync(src) +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) -} + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} +/** + * Expose "braces" + */ -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs.unlinkSync(dest) - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} +module.exports = braces; -function copyFile (srcStat, src, dest, opts) { - fs.copyFileSync(src, dest) - if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) - return setDestMode(dest, srcStat.mode) -} -function handleTimestamps (srcMode, src, dest) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) - return setDestTimestamps(src, dest) -} +/***/ }), -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} +/***/ 7123: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} +"use strict"; -function setDestMode (dest, srcMode) { - return fs.chmodSync(dest, srcMode) -} -function setDestTimestamps (src, dest) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - const updatedSrcStat = fs.statSync(src) - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) -} +const fill = __nccwpck_require__(90791); +const utils = __nccwpck_require__(27691); -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) - if (destStat && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - return copyDir(src, dest, opts) -} +const compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; -function mkDirAndCopy (srcMode, src, dest, opts) { - fs.mkdirSync(dest) - copyDir(src, dest, opts) - return setDestMode(dest, srcMode) -} + if (node.isOpen === true) { + return prefix + node.value; + } -function copyDir (src, dest, opts) { - fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) -} + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); + return prefix + node.value; + } -function copyDirItem (item, src, dest, opts) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy') - return startCopy(destStat, srcItem, destItem, opts) -} + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs.readlinkSync(src) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } - if (!destStat) { - return fs.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest - try { - resolvedDest = fs.readlinkSync(dest) - } catch (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) - throw err + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) + + if (node.value) { + return node.value; } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } } - // prevent copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + if (node.nodes) { + for (const child of node.nodes) { + output += walk(child, node); + } } - return copyLink(resolvedSrc, dest) - } -} -function copyLink (resolvedSrc, dest) { - fs.unlinkSync(dest) - return fs.symlinkSync(resolvedSrc, dest) -} + return output; + }; -module.exports = copySync + return walk(ast); +}; + +module.exports = compile; /***/ }), -/***/ 11135: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 45412: +/***/ ((module) => { "use strict"; module.exports = { - copySync: __nccwpck_require__(43338) -} - + MAX_LENGTH: 10000, -/***/ }), + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ -/***/ 38834: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ -"use strict"; + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + CHAR_ASTERISK: '*', /* * */ -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const mkdirs = (__nccwpck_require__(98605).mkdirs) -const pathExists = (__nccwpck_require__(43835).pathExists) -const utimesMillis = (__nccwpck_require__(52548).utimesMillis) -const stat = __nccwpck_require__(73901) + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; -function copy (src, dest, opts, cb) { - if (typeof opts === 'function' && !cb) { - cb = opts - opts = {} - } else if (typeof opts === 'function') { - opts = { filter: opts } - } - cb = cb || function () {} - opts = opts || {} +/***/ }), - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber +/***/ 46944: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n - see https://github.com/jprichardson/node-fs-extra/issues/269`) - } +"use strict"; - stat.checkPaths(src, dest, 'copy', (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'copy', err => { - if (err) return cb(err) - if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) - return checkParentDir(destStat, src, dest, opts, cb) - }) - }) -} -function checkParentDir (destStat, src, dest, opts, cb) { - const destParent = path.dirname(dest) - pathExists(destParent, (err, dirExists) => { - if (err) return cb(err) - if (dirExists) return startCopy(destStat, src, dest, opts, cb) - mkdirs(destParent, err => { - if (err) return cb(err) - return startCopy(destStat, src, dest, opts, cb) - }) - }) -} +const fill = __nccwpck_require__(90791); +const stringify = __nccwpck_require__(64810); +const utils = __nccwpck_require__(27691); -function handleFilter (onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then(include => { - if (include) return onInclude(destStat, src, dest, opts, cb) - return cb() - }, error => cb(error)) -} +const append = (queue = '', stash = '', enclose = false) => { + const result = []; -function startCopy (destStat, src, dest, opts, cb) { - if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) - return getStats(destStat, src, dest, opts, cb) -} + queue = [].concat(queue); + stash = [].concat(stash); -function getStats (destStat, src, dest, opts, cb) { - const stat = opts.dereference ? fs.stat : fs.lstat - stat(src, (err, srcStat) => { - if (err) return cb(err) + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) - }) -} + for (const item of queue) { + if (Array.isArray(item)) { + for (const value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + return utils.flatten(result); +}; -function onFile (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return copyFile(srcStat, src, dest, opts, cb) - return mayCopyFile(srcStat, src, dest, opts, cb) -} +const expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; -function mayCopyFile (srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs.unlink(dest, err => { - if (err) return cb(err) - return copyFile(srcStat, src, dest, opts, cb) - }) - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)) - } else return cb() -} + const walk = (node, parent = {}) => { + node.queue = []; -function copyFile (srcStat, src, dest, opts, cb) { - fs.copyFile(src, dest, err => { - if (err) return cb(err) - if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) - return setDestMode(dest, srcStat.mode, cb) - }) -} + let p = parent; + let q = parent.queue; -function handleTimestampsAndMode (srcMode, src, dest, cb) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) { - return makeFileWritable(dest, srcMode, err => { - if (err) return cb(err) - return setDestTimestampsAndMode(srcMode, src, dest, cb) - }) - } - return setDestTimestampsAndMode(srcMode, src, dest, cb) -} + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } -function makeFileWritable (dest, srcMode, cb) { - return setDestMode(dest, srcMode | 0o200, cb) -} + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } -function setDestTimestampsAndMode (srcMode, src, dest, cb) { - setDestTimestamps(src, dest, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) -} + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); -function setDestMode (dest, srcMode, cb) { - return fs.chmod(dest, srcMode, cb) -} + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } -function setDestTimestamps (src, dest, cb) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - fs.stat(src, (err, updatedSrcStat) => { - if (err) return cb(err) - return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) - }) -} + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } -function onDir (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) - if (destStat && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) - } - return copyDir(src, dest, opts, cb) -} + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } -function mkDirAndCopy (srcMode, src, dest, opts, cb) { - fs.mkdir(dest, err => { - if (err) return cb(err) - copyDir(src, dest, opts, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) - }) -} + const enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; -function copyDir (src, dest, opts, cb) { - fs.readdir(src, (err, items) => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) -} + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } -function copyDirItems (items, src, dest, opts, cb) { - const item = items.pop() - if (!item) return cb() - return copyDirItem(items, item, src, dest, opts, cb) -} + for (let i = 0; i < node.nodes.length; i++) { + const child = node.nodes[i]; -function copyDirItem (items, item, src, dest, opts, cb) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => { - if (err) return cb(err) - const { destStat } = stats - startCopy(destStat, srcItem, destItem, opts, err => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) - }) -} + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } -function onLink (destStat, src, dest, opts, cb) { - fs.readlink(src, (err, resolvedSrc) => { - if (err) return cb(err) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } - if (!destStat) { - return fs.symlink(resolvedSrc, dest, cb) - } else { - fs.readlink(dest, (err, resolvedDest) => { - if (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) - return cb(err) - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) - } + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } - // do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) - } - return copyLink(resolvedSrc, dest, cb) - }) + if (child.nodes) { + walk(child, node); + } } - }) -} -function copyLink (resolvedSrc, dest, cb) { - fs.unlink(dest, err => { - if (err) return cb(err) - return fs.symlink(resolvedSrc, dest, cb) - }) -} + return queue; + }; -module.exports = copy + return utils.flatten(walk(ast)); +}; + +module.exports = expand; /***/ }), -/***/ 61335: +/***/ 79889: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const u = (__nccwpck_require__(9046).fromCallback) -module.exports = { - copy: u(__nccwpck_require__(38834)) -} +const stringify = __nccwpck_require__(64810); +/** + * Constants + */ -/***/ }), +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = __nccwpck_require__(45412); -/***/ 96970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * parse + */ -"use strict"; +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index = 0; + let depth = 0; + let value; -const u = (__nccwpck_require__(9046).fromCallback) -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const mkdir = __nccwpck_require__(98605) -const remove = __nccwpck_require__(47357) + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; -const emptyDir = u(function emptyDir (dir, callback) { - callback = callback || function () {} - fs.readdir(dir, (err, items) => { - if (err) return mkdir.mkdirs(dir, callback) + push({ type: 'bos' }); - items = items.map(item => path.join(dir, item)) + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); - deleteItem() + /** + * Invalid chars + */ - function deleteItem () { - const item = items.pop() - if (!item) return callback() - remove.remove(item, err => { - if (err) return callback(err) - deleteItem() - }) + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; } - }) -}) -function emptyDirSync (dir) { - let items - try { - items = fs.readdirSync(dir) - } catch { - return mkdir.mkdirsSync(dir) - } + /** + * Escaped chars + */ - items.forEach(item => { - item = path.join(dir, item) - remove.removeSync(item) - }) -} + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } -module.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir -} + /** + * Right square bracket (literal): ']' + */ + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } -/***/ }), + /** + * Left square bracket: '[' + */ -/***/ 2164: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; -"use strict"; + let next; + while (index < length && (next = advance())) { + value += next; -const u = (__nccwpck_require__(9046).fromCallback) -const path = __nccwpck_require__(71017) -const fs = __nccwpck_require__(14178) -const mkdir = __nccwpck_require__(98605) + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } -function createFile (file, callback) { - function makeFile () { - fs.writeFile(file, '', err => { - if (err) return callback(err) - callback() - }) - } + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } - fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err - if (!err && stats.isFile()) return callback() - const dir = path.dirname(file) - fs.stat(dir, (err, stats) => { - if (err) { - // if the directory doesn't exist, make it - if (err.code === 'ENOENT') { - return mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeFile() - }) + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } } - return callback(err) } - if (stats.isDirectory()) makeFile() - else { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdir(dir, err => { - if (err) return callback(err) - }) + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; } - }) - }) -} + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } -function createFileSync (file) { - let stats - try { - stats = fs.statSync(file) - } catch {} - if (stats && stats.isFile()) return + /** + * Quotes: '|"|` + */ - const dir = path.dirname(file) - try { - if (!fs.statSync(dir).isDirectory()) { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdirSync(dir) + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; } - } catch (err) { - // If the stat call above failed because the directory doesn't exist, create it - if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) - else throw err - } - fs.writeFileSync(file, '') -} + /** + * Left curly brace: '{' + */ -module.exports = { - createFile: u(createFile), - createFileSync -} + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; -/***/ }), + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } -/***/ 40055: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Right curly brace: '}' + */ -"use strict"; + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + const type = 'close'; + block = stack.pop(); + block.close = true; -const file = __nccwpck_require__(2164) -const link = __nccwpck_require__(53797) -const symlink = __nccwpck_require__(72549) + push({ type, value }); + depth--; -module.exports = { - // file - createFile: file.createFile, - createFileSync: file.createFileSync, - ensureFile: file.createFile, - ensureFileSync: file.createFileSync, - // link - createLink: link.createLink, - createLinkSync: link.createLinkSync, - ensureLink: link.createLink, - ensureLinkSync: link.createLinkSync, - // symlink - createSymlink: symlink.createSymlink, - createSymlinkSync: symlink.createSymlinkSync, - ensureSymlink: symlink.createSymlink, - ensureSymlinkSync: symlink.createSymlinkSync -} + block = stack[stack.length - 1]; + continue; + } + /** + * Comma: ',' + */ -/***/ }), + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } -/***/ 53797: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + push({ type: 'comma', value }); + block.commas++; + continue; + } -"use strict"; + /** + * Dot: '.' + */ + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; -const u = (__nccwpck_require__(9046).fromCallback) -const path = __nccwpck_require__(71017) -const fs = __nccwpck_require__(14178) -const mkdir = __nccwpck_require__(98605) -const pathExists = (__nccwpck_require__(43835).pathExists) + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } -function createLink (srcpath, dstpath, callback) { - function makeLink (srcpath, dstpath) { - fs.link(srcpath, dstpath, err => { - if (err) return callback(err) - callback(null) - }) - } + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; - pathExists(dstpath, (err, destinationExists) => { - if (err) return callback(err) - if (destinationExists) return callback(null) - fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureLink') - return callback(err) + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; } - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return makeLink(srcpath, dstpath) - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeLink(srcpath, dstpath) - }) - }) - }) - }) -} + if (prev.type === 'range') { + siblings.pop(); -function createLinkSync (srcpath, dstpath) { - const destinationExists = fs.existsSync(dstpath) - if (destinationExists) return undefined + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } - try { - fs.lstatSync(srcpath) - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink') - throw err + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); } - const dir = path.dirname(dstpath) - const dirExists = fs.existsSync(dir) - if (dirExists) return fs.linkSync(srcpath, dstpath) - mkdir.mkdirsSync(dir) + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); - return fs.linkSync(srcpath, dstpath) -} + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); -module.exports = { - createLink: u(createLink), - createLinkSync -} + // get the location of the block on parent.nodes (block's siblings) + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; /***/ }), -/***/ 53727: +/***/ 64810: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(71017) -const fs = __nccwpck_require__(14178) -const pathExists = (__nccwpck_require__(43835).pathExists) +const utils = __nccwpck_require__(27691); -/** - * Function that returns two types of paths, one relative to symlink, and one - * relative to the current working directory. Checks if path is absolute or - * relative. If the path is relative, this function checks if the path is - * relative to symlink or relative to current working directory. This is an - * initiative to find a smarter `srcpath` to supply when building symlinks. - * This allows you to determine which path to use out of one of three possible - * types of source paths. The first is an absolute path. This is detected by - * `path.isAbsolute()`. When an absolute path is provided, it is checked to - * see if it exists. If it does it's used, if not an error is returned - * (callback)/ thrown (sync). The other two options for `srcpath` are a - * relative url. By default Node's `fs.symlink` works by creating a symlink - * using `dstpath` and expects the `srcpath` to be relative to the newly - * created symlink. If you provide a `srcpath` that does not exist on the file - * system it results in a broken symlink. To minimize this, the function - * checks to see if the 'relative to symlink' source file exists, and if it - * does it will use it. If it does not, it checks if there's a file that - * exists that is relative to the current working directory, if does its used. - * This preserves the expectations of the original fs.symlink spec and adds - * the ability to pass in `relative to current working direcotry` paths. - */ +module.exports = (ast, options = {}) => { + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; -function symlinkPaths (srcpath, dstpath, callback) { - if (path.isAbsolute(srcpath)) { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: srcpath - }) - }) - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - return pathExists(relativeToDst, (err, exists) => { - if (err) return callback(err) - if (exists) { - return callback(null, { - toCwd: relativeToDst, - toDst: srcpath - }) - } else { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - }) - }) + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; } - }) - } -} + return node.value; + } -function symlinkPathsSync (srcpath, dstpath) { - let exists - if (path.isAbsolute(srcpath)) { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('absolute srcpath does not exist') - return { - toCwd: srcpath, - toDst: srcpath + if (node.value) { + return node.value; } - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - exists = fs.existsSync(relativeToDst) - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - } - } else { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('relative srcpath does not exist') - return { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) + + if (node.nodes) { + for (const child of node.nodes) { + output += stringify(child); } } - } -} + return output; + }; + + return stringify(ast); +}; -module.exports = { - symlinkPaths, - symlinkPathsSync -} /***/ }), -/***/ 18254: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 27691: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const fs = __nccwpck_require__(14178) +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; -function symlinkType (srcpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - if (type) return callback(null, type) - fs.lstat(srcpath, (err, stats) => { - if (err) return callback(null, 'file') - type = (stats && stats.isDirectory()) ? 'dir' : 'file' - callback(null, type) - }) -} +/** + * Find a node of the given type + */ -function symlinkTypeSync (srcpath, type) { - let stats +exports.find = (node, type) => node.nodes.find(node => node.type === type); - if (type) return type - try { - stats = fs.lstatSync(srcpath) - } catch { - return 'file' - } - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} +/** + * Find a node of the given type + */ -module.exports = { - symlinkType, - symlinkTypeSync -} +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; +/** + * Escape the given node with '\\' before node.value + */ -/***/ }), +exports.escapeNode = (block, n = 0, type) => { + const node = block.nodes[n]; + if (!node) return; -/***/ 72549: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; -"use strict"; +/** + * Returns true if the given brace node should be enclosed in literal braces + */ +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; -const u = (__nccwpck_require__(9046).fromCallback) -const path = __nccwpck_require__(71017) -const fs = __nccwpck_require__(14178) -const _mkdirs = __nccwpck_require__(98605) -const mkdirs = _mkdirs.mkdirs -const mkdirsSync = _mkdirs.mkdirsSync +/** + * Returns true if a brace node is invalid. + */ -const _symlinkPaths = __nccwpck_require__(53727) -const symlinkPaths = _symlinkPaths.symlinkPaths -const symlinkPathsSync = _symlinkPaths.symlinkPathsSync +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; -const _symlinkType = __nccwpck_require__(18254) -const symlinkType = _symlinkType.symlinkType -const symlinkTypeSync = _symlinkType.symlinkTypeSync +/** + * Returns true if a node is an open or close node + */ -const pathExists = (__nccwpck_require__(43835).pathExists) +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; -function createSymlink (srcpath, dstpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type +/** + * Reduce an array of text nodes. + */ - pathExists(dstpath, (err, destinationExists) => { - if (err) return callback(err) - if (destinationExists) return callback(null) - symlinkPaths(srcpath, dstpath, (err, relative) => { - if (err) return callback(err) - srcpath = relative.toDst - symlinkType(relative.toCwd, type, (err, type) => { - if (err) return callback(err) - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) - mkdirs(dir, err => { - if (err) return callback(err) - fs.symlink(srcpath, dstpath, type, callback) - }) - }) - }) - }) - }) -} +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); -function createSymlinkSync (srcpath, dstpath, type) { - const destinationExists = fs.existsSync(dstpath) - if (destinationExists) return undefined +/** + * Flatten an array + */ - const relative = symlinkPathsSync(srcpath, dstpath) - srcpath = relative.toDst - type = symlinkTypeSync(relative.toCwd, type) - const dir = path.dirname(dstpath) - const exists = fs.existsSync(dir) - if (exists) return fs.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir) - return fs.symlinkSync(srcpath, dstpath, type) -} +exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } + } + return result; + }; -module.exports = { - createSymlink: u(createSymlink), - createSymlinkSync -} + flat(args); + return result; +}; /***/ }), -/***/ 61176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 90791: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ -// This is adapted from https://github.com/normalize/mz -// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors -const u = (__nccwpck_require__(9046).fromCallback) -const fs = __nccwpck_require__(14178) -const api = [ - 'access', - 'appendFile', - 'chmod', - 'chown', - 'close', - 'copyFile', - 'fchmod', - 'fchown', - 'fdatasync', - 'fstat', - 'fsync', - 'ftruncate', - 'futimes', - 'lchmod', - 'lchown', - 'link', - 'lstat', - 'mkdir', - 'mkdtemp', - 'open', - 'opendir', - 'readdir', - 'readFile', - 'readlink', - 'realpath', - 'rename', - 'rm', - 'rmdir', - 'stat', - 'symlink', - 'truncate', - 'unlink', - 'utimes', - 'writeFile' -].filter(key => { - // Some commands are not available on some systems. Ex: - // fs.opendir was added in Node.js v12.12.0 - // fs.rm was added in Node.js v14.14.0 - // fs.lchown is not available on at least some Linux - return typeof fs[key] === 'function' -}) -// Export all keys: -Object.keys(fs).forEach(key => { - if (key === 'promises') { - // fs.promises is a getter property that triggers ExperimentalWarning - // Don't re-export it here, the getter is defined in "lib/index.js" - return - } - exports[key] = fs[key] -}) +const util = __nccwpck_require__(73837); +const toRegexRange = __nccwpck_require__(1861); -// Universalify async methods: -api.forEach(method => { - exports[method] = u(fs[method]) -}) +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -// We differ from mz/fs in that we still ship the old, broken, fs.exists() -// since we are a drop-in replacement for the native module -exports.exists = function (filename, callback) { - if (typeof callback === 'function') { - return fs.exists(filename, callback) - } - return new Promise(resolve => { - return fs.exists(filename, resolve) - }) -} +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; -// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; -exports.read = function (fd, buffer, offset, length, position, callback) { - if (typeof callback === 'function') { - return fs.read(fd, buffer, offset, length, position, callback) - } - return new Promise((resolve, reject) => { - fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { - if (err) return reject(err) - resolve({ bytesRead, buffer }) - }) - }) -} +const isNumber = num => Number.isInteger(+num); -// Function signature can be -// fs.write(fd, buffer[, offset[, length[, position]]], callback) -// OR -// fs.write(fd, string[, position[, encoding]], callback) -// We need to handle both cases, so we use ...args -exports.write = function (fd, buffer, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.write(fd, buffer, ...args) - } +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; - return new Promise((resolve, reject) => { - fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { - if (err) return reject(err) - resolve({ bytesWritten, buffer }) - }) - }) -} +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; -// fs.writev only available in Node v12.9.0+ -if (typeof fs.writev === 'function') { - // Function signature is - // s.writev(fd, buffers[, position], callback) - // We need to handle the optional arg, so we use ...args - exports.writev = function (fd, buffers, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.writev(fd, buffers, ...args) - } +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; - return new Promise((resolve, reject) => { - fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { - if (err) return reject(err) - resolve({ bytesWritten, buffers }) - }) - }) +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; } -} + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; -// fs.realpath.native only available in Node v9.2+ -if (typeof fs.realpath.native === 'function') { - exports.realpath.native = u(fs.realpath.native) -} +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; -/***/ }), + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } -/***/ 5630: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } -"use strict"; + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + if (options.wrap) { + return `(${prefix}${result})`; + } -module.exports = { - // Export promiseified graceful-fs: - ...__nccwpck_require__(61176), - // Export extra methods: - ...__nccwpck_require__(11135), - ...__nccwpck_require__(61335), - ...__nccwpck_require__(96970), - ...__nccwpck_require__(40055), - ...__nccwpck_require__(40213), - ...__nccwpck_require__(98605), - ...__nccwpck_require__(69665), - ...__nccwpck_require__(41497), - ...__nccwpck_require__(16570), - ...__nccwpck_require__(43835), - ...__nccwpck_require__(47357) -} + return result; +}; -// Export fs.promises as a getter property so that we don't trigger -// ExperimentalWarning before fs.promises is actually accessed. -const fs = __nccwpck_require__(57147) -if (Object.getOwnPropertyDescriptor(fs, 'promises')) { - Object.defineProperty(module.exports, "promises", ({ - get () { return fs.promises } - })) -} +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + let start = String.fromCharCode(a); + if (a === b) return start; -/***/ }), + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; -/***/ 40213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; -"use strict"; +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; -const u = (__nccwpck_require__(9046).fromPromise) -const jsonFile = __nccwpck_require__(18970) +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; -jsonFile.outputJson = u(__nccwpck_require__(60531)) -jsonFile.outputJsonSync = __nccwpck_require__(19421) -// aliases -jsonFile.outputJSON = jsonFile.outputJson -jsonFile.outputJSONSync = jsonFile.outputJsonSync -jsonFile.writeJSON = jsonFile.writeJson -jsonFile.writeJSONSync = jsonFile.writeJsonSync -jsonFile.readJSON = jsonFile.readJson -jsonFile.readJSONSync = jsonFile.readJsonSync +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); -module.exports = jsonFile + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; -/***/ }), + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); -/***/ 18970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); -"use strict"; + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; -const jsonFile = __nccwpck_require__(26160) + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } -module.exports = { - // jsonfile exports - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync -} + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } + return range; +}; -/***/ }), +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } -/***/ 19421: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); -"use strict"; + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } -const { stringify } = __nccwpck_require__(35902) -const { outputFileSync } = __nccwpck_require__(16570) + let range = []; + let index = 0; -function outputJsonSync (file, data, options) { - const str = stringify(data, options) + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } - outputFileSync(file, str, options) -} + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } -module.exports = outputJsonSync + return range; +}; +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } -/***/ }), + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } -/***/ 60531: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } -"use strict"; + if (isObject(step)) { + return fill(start, end, 0, step); + } + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; -const { stringify } = __nccwpck_require__(35902) -const { outputFile } = __nccwpck_require__(16570) + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } -async function outputJson (file, data, options = {}) { - const str = stringify(data, options) + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } - await outputFile(file, str, options) -} + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; -module.exports = outputJson +module.exports = fill; /***/ }), -/***/ 98605: +/***/ 23913: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const u = (__nccwpck_require__(9046).fromPromise) -const { makeDir: _makeDir, makeDirSync } = __nccwpck_require__(52751) -const makeDir = u(_makeDir) -module.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync -} +const util = __nccwpck_require__(73837); +const braces = __nccwpck_require__(35582); +const picomatch = __nccwpck_require__(78569); +const utils = __nccwpck_require__(30479); +const isEmptyString = v => v === '' || v === './'; +const hasBraces = v => { + const index = v.indexOf('{'); + return index > -1 && v.indexOf('}', index) > -1; +}; -/***/ }), +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ -/***/ 52751: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); -"use strict"; -// Adapted from https://github.com/sindresorhus/make-dir -// Copyright (c) Sindre Sorhus (sindresorhus.com) -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; -const fs = __nccwpck_require__(61176) -const path = __nccwpck_require__(71017) -const atLeastNode = __nccwpck_require__(25995) + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; -const useNativeRecursiveOption = atLeastNode('10.12.0') + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -const checkPath = pth => { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) + for (let item of list) { + let matched = isMatch(item, true); - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`) - error.code = 'EINVAL' - throw error + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } } } -} - -const processOptions = options => { - const defaults = { mode: 0o777 } - if (typeof options === 'number') options = { mode: options } - return { ...defaults, ...options } -} - -const permissionError = pth => { - // This replicates the exception of `fs.mkdir` with native the - // `recusive` option when run on an invalid drive under Windows. - const error = new Error(`operation not permitted, mkdir '${pth}'`) - error.code = 'EPERM' - error.errno = -4048 - error.path = pth - error.syscall = 'mkdir' - return error -} -module.exports.makeDir = async (input, options) => { - checkPath(input) - options = processOptions(options) + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); - if (useNativeRecursiveOption) { - const pth = path.resolve(input) + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } - return fs.mkdir(pth, { - mode: options.mode, - recursive: true - }) + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } } - const make = async pth => { - try { - await fs.mkdir(pth, options.mode) - } catch (error) { - if (error.code === 'EPERM') { - throw error - } + return matches; +}; - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth) - } +/** + * Backwards compatibility + */ - if (error.message.includes('null bytes')) { - throw error - } +micromatch.match = micromatch; - await make(path.dirname(pth)) - return make(pth) - } +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ - try { - const stats = await fs.stat(pth) - if (!stats.isDirectory()) { - // This error is never exposed to the user - // it is caught below, and the original error is thrown - throw new Error('The path is not a directory') - } - } catch { - throw error - } - } - } +micromatch.matcher = (pattern, options) => picomatch(pattern, options); - return make(path.resolve(input)) -} +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ -module.exports.makeDirSync = (input, options) => { - checkPath(input) - options = processOptions(options) +micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); - if (useNativeRecursiveOption) { - const pth = path.resolve(input) +/** + * Backwards compatibility + */ - return fs.mkdirSync(pth, { - mode: options.mode, - recursive: true - }) - } +micromatch.any = micromatch.isMatch; - const make = pth => { - try { - fs.mkdirSync(pth, options.mode) - } catch (error) { - if (error.code === 'EPERM') { - throw error - } +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ - if (error.code === 'ENOENT') { - if (path.dirname(pth) === pth) { - throw permissionError(pth) - } +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; - if (error.message.includes('null bytes')) { - throw error - } + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; - make(path.dirname(pth)) - return make(pth) - } + let matches = new Set(micromatch(list, patterns, { ...options, onResult })); - try { - if (!fs.statSync(pth).isDirectory()) { - // This error is never exposed to the user - // it is caught below, and the original error is thrown - throw new Error('The path is not a directory') - } - } catch { - throw error - } + for (let item of items) { + if (!matches.has(item)) { + result.add(item); } } + return [...result]; +}; - return make(path.resolve(input)) -} +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } -/***/ }), + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } -/***/ 69665: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } -"use strict"; + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + return micromatch.isMatch(str, pattern, { ...options, contains: true }); +}; -module.exports = { - moveSync: __nccwpck_require__(96445) -} +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; -/***/ }), +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ -/***/ 96445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); -"use strict"; + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const copySync = (__nccwpck_require__(11135).copySync) -const removeSync = (__nccwpck_require__(47357).removeSync) -const mkdirpSync = (__nccwpck_require__(98605).mkdirpSync) -const stat = __nccwpck_require__(73901) +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); -function moveSync (src, dest, opts) { - opts = opts || {} - const overwrite = opts.overwrite || opts.clobber || false + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; - const { srcStat } = stat.checkPathsSync(src, dest, 'move') - stat.checkParentPathsSync(src, srcStat, dest, 'move') - mkdirpSync(path.dirname(dest)) - return doRename(src, dest, overwrite) -} +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ -function doRename (src, dest, overwrite) { - if (overwrite) { - removeSync(dest) - return rename(src, dest, overwrite) +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); } - if (fs.existsSync(dest)) throw new Error('dest already exists.') - return rename(src, dest, overwrite) -} -function rename (src, dest, overwrite) { - try { - fs.renameSync(src, dest) - } catch (err) { - if (err.code !== 'EXDEV') throw err - return moveAcrossDevice(src, dest, overwrite) - } -} + return [].concat(patterns).every(p => picomatch(p, options)(str)); +}; -function moveAcrossDevice (src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); } - copySync(src, dest, opts) - return removeSync(src) -} +}; -module.exports = moveSync +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ +micromatch.makeRe = (...args) => picomatch.makeRe(...args); -/***/ }), +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ -/***/ 41497: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +micromatch.scan = (...args) => picomatch.scan(...args); -"use strict"; +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ +micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; +}; -const u = (__nccwpck_require__(9046).fromCallback) -module.exports = { - move: u(__nccwpck_require__(72231)) -} +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !hasBraces(pattern)) { + return [pattern]; + } + return braces(pattern, options); +}; -/***/ }), +/** + * Expand braces + */ -/***/ 72231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, { ...options, expand: true }); +}; -"use strict"; +/** + * Expose micromatch + */ +// exposed for tests +micromatch.hasBraces = hasBraces; +module.exports = micromatch; -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const copy = (__nccwpck_require__(61335).copy) -const remove = (__nccwpck_require__(47357).remove) -const mkdirp = (__nccwpck_require__(98605).mkdirp) -const pathExists = (__nccwpck_require__(43835).pathExists) -const stat = __nccwpck_require__(73901) -function move (src, dest, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = {} - } +/***/ }), - const overwrite = opts.overwrite || opts.clobber || false +/***/ 43664: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - stat.checkPaths(src, dest, 'move', (err, stats) => { - if (err) return cb(err) - const { srcStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'move', err => { - if (err) return cb(err) - mkdirp(path.dirname(dest), err => { - if (err) return cb(err) - return doRename(src, dest, overwrite, cb) - }) - }) - }) -} +"use strict"; -function doRename (src, dest, overwrite, cb) { - if (overwrite) { - return remove(dest, err => { - if (err) return cb(err) - return rename(src, dest, overwrite, cb) - }) - } - pathExists(dest, (err, destExists) => { - if (err) return cb(err) - if (destExists) return cb(new Error('dest already exists.')) - return rename(src, dest, overwrite, cb) - }) +const taskManager = __nccwpck_require__(42708); +const async_1 = __nccwpck_require__(95679); +const stream_1 = __nccwpck_require__(94630); +const sync_1 = __nccwpck_require__(42405); +const settings_1 = __nccwpck_require__(10952); +const utils = __nccwpck_require__(45444); +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); } - -function rename (src, dest, overwrite, cb) { - fs.rename(src, dest, err => { - if (!err) return cb() - if (err.code !== 'EXDEV') return cb(err) - return moveAcrossDevice(src, dest, overwrite, cb) - }) +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + let posix; + (function (posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(posix = FastGlob.posix || (FastGlob.posix = {})); + let win32; + (function (win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); } - -function moveAcrossDevice (src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - } - copy(src, dest, opts, err => { - if (err) return cb(err) - return remove(src, cb) - }) +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } } - -module.exports = move +module.exports = FastGlob; /***/ }), -/***/ 16570: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42708: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const u = (__nccwpck_require__(9046).fromCallback) -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const mkdir = __nccwpck_require__(98605) -const pathExists = (__nccwpck_require__(43835).pathExists) - -function outputFile (file, data, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding - encoding = 'utf8' - } - - const dir = path.dirname(file) - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return fs.writeFile(file, data, encoding, callback) - - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - - fs.writeFile(file, data, encoding, callback) - }) - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; +const utils = __nccwpck_require__(45444); +function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); } - -function outputFileSync (file, ...args) { - const dir = path.dirname(file) - if (fs.existsSync(dir)) { - return fs.writeFileSync(file, ...args) - } - mkdir.mkdirsSync(dir) - fs.writeFileSync(file, ...args) +exports.generate = generate; +function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) { + patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + } + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + } + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); } - -module.exports = { - outputFile: u(outputFile), - outputFileSync +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; } - - -/***/ }), - -/***/ 43835: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const u = (__nccwpck_require__(9046).fromPromise) -const fs = __nccwpck_require__(61176) - -function pathExists (path) { - return fs.access(path).then(() => true).catch(() => false) +exports.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); } - -module.exports = { - pathExists: u(pathExists), - pathExistsSync: fs.existsSync +exports.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils.pattern.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) + }; } +exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ }), -/***/ 47357: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 95679: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const u = (__nccwpck_require__(9046).fromCallback) -const rimraf = __nccwpck_require__(38761) - -module.exports = { - remove: u(rimraf), - removeSync: rimraf.sync +Object.defineProperty(exports, "__esModule", ({ value: true })); +const async_1 = __nccwpck_require__(97747); +const provider_1 = __nccwpck_require__(60257); +class ProviderAsync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new async_1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } } +exports["default"] = ProviderAsync; /***/ }), -/***/ 38761: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36983: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const fs = __nccwpck_require__(14178) -const path = __nccwpck_require__(71017) -const assert = __nccwpck_require__(39491) - -const isWindows = (process.platform === 'win32') - -function defaults (options) { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 -} - -function rimraf (p, options, cb) { - let busyTries = 0 - - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && - busyTries < options.maxBusyTries) { - busyTries++ - const time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), time) - } - - // already gone - if (er.code === 'ENOENT') er = null +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(45444); +const partial_1 = __nccwpck_require__(35295); +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; } - - cb(er) - }) -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === 'ENOENT') { - return cb(null) + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); } - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === 'EPERM' && isWindows) { - return fixWinEPERM(p, options, er, cb) + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); } - - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb) + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } - - options.unlink(p, er => { - if (er) { - if (er.code === 'ENOENT') { - return cb(null) + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; } - if (er.code === 'EPERM') { - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) + if (this._isSkippedSymbolicLink(entry)) { + return false; } - if (er.code === 'EISDIR') { - return rmdir(p, options, er, cb) + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; } - } - return cb(er) - }) - }) -} - -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.chmod(p, 0o666, er2 => { - if (er2) { - cb(er2.code === 'ENOENT' ? null : er) - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === 'ENOENT' ? null : er) - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb) - } else { - options.unlink(p, cb) + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; } - }) + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } - }) -} - -function fixWinEPERMSync (p, options, er) { - let stats - - assert(p) - assert(options) - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === 'ENOENT') { - return - } else { - throw er + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; } - } - - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === 'ENOENT') { - return - } else { - throw er + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } - } - - if (stats.isDirectory()) { - rmdirSync(p, options, er) - } else { - options.unlinkSync(p) - } -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { - rmkids(p, options, cb) - } else if (er && er.code === 'ENOTDIR') { - cb(originalEr) - } else { - cb(er) + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); } - }) } +exports["default"] = DeepFilter; -function rmkids (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - options.readdir(p, (er, files) => { - if (er) return cb(er) +/***/ }), - let n = files.length - let errState +/***/ 71343: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (n === 0) return options.rmdir(p, cb) +"use strict"; - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) { - return +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(45444); +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); + } + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; } - if (er) return cb(errState = er) - if (--n === 0) { - options.rmdir(p, cb) + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; } - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - let st - - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === 'ENOENT') { - return + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); + if (this._settings.unique && isMatched) { + this._createIndexRecord(filepath); + } + return isMatched; } - - // Windows can EPERM on stat. Life is suffering. - if (er.code === 'EPERM' && isWindows) { - fixWinEPERMSync(p, options, er) + _isDuplicateEntry(filepath) { + return this.index.has(filepath); } - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) { - rmdirSync(p, options, null) - } else { - options.unlinkSync(p) + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); } - } catch (er) { - if (er.code === 'ENOENT') { - return - } else if (er.code === 'EPERM') { - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - } else if (er.code !== 'EISDIR') { - throw er + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); } - rmdirSync(p, options, er) - } -} - -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === 'ENOTDIR') { - throw originalEr - } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { - rmkidsSync(p, options) - } else if (er.code !== 'ENOENT') { - throw er + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { + return false; + } + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { + return false; + } + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; + } + return true; + } + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + // Trying to match files and directories by patterns. + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; } - } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - if (isWindows) { - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const startTime = Date.now() - do { - try { - const ret = options.rmdirSync(p, options) - return ret - } catch {} - } while (Date.now() - startTime < 500) // give up after 500ms - } else { - const ret = options.rmdirSync(p, options) - return ret - } } - -module.exports = rimraf -rimraf.sync = rimrafSync +exports["default"] = EntryFilter; /***/ }), -/***/ 73901: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36654: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const fs = __nccwpck_require__(61176) -const path = __nccwpck_require__(71017) -const util = __nccwpck_require__(73837) -const atLeastNode = __nccwpck_require__(25995) - -const nodeSupportsBigInt = atLeastNode('10.5.0') -const stat = (file) => nodeSupportsBigInt ? fs.stat(file, { bigint: true }) : fs.stat(file) -const statSync = (file) => nodeSupportsBigInt ? fs.statSync(file, { bigint: true }) : fs.statSync(file) - -function getStats (src, dest) { - return Promise.all([ - stat(src), - stat(dest).catch(err => { - if (err.code === 'ENOENT') return null - throw err - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) -} - -function getStatsSync (src, dest) { - let destStat - const srcStat = statSync(src) - try { - destStat = statSync(dest) - } catch (err) { - if (err.code === 'ENOENT') return { srcStat, destStat: null } - throw err - } - return { srcStat, destStat } -} - -function checkPaths (src, dest, funcName, cb) { - util.callbackify(getStats)(src, dest, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - if (destStat && areIdentical(srcStat, destStat)) { - return cb(new Error('Source and destination must not be the same.')) - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return cb(null, { srcStat, destStat }) - }) -} - -function checkPathsSync (src, dest, funcName) { - const { srcStat, destStat } = getStatsSync(src, dest) - if (destStat && areIdentical(srcStat, destStat)) { - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - return { srcStat, destStat } -} - -// recursively check if dest parent is a subdirectory of src. -// It works for all file types including symlinks since it -// checks the src and dest inodes. It starts from the deepest -// parent and stops once it reaches the src parent or the root path. -function checkParentPaths (src, srcStat, dest, funcName, cb) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() - const callback = (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb() - return cb(err) - } - if (areIdentical(srcStat, destStat)) { - return cb(new Error(errMsg(src, dest, funcName))) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(45444); +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; } - return checkParentPaths(src, srcStat, destParent, funcName, cb) - } - if (nodeSupportsBigInt) fs.stat(destParent, { bigint: true }, callback) - else fs.stat(destParent, callback) -} - -function checkParentPathsSync (src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return - let destStat - try { - destStat = statSync(destParent) - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)) - } - return checkParentPathsSync(src, srcStat, destParent, funcName) -} - -function areIdentical (srcStat, destStat) { - if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) { - if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) { - // definitive answer - return true + getFilter() { + return (error) => this._isNonFatalError(error); } - // Use additional heuristics if we can't use 'bigint'. - // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER - // See issue 657 - if (destStat.size === srcStat.size && - destStat.mode === srcStat.mode && - destStat.nlink === srcStat.nlink && - destStat.atimeMs === srcStat.atimeMs && - destStat.mtimeMs === srcStat.mtimeMs && - destStat.ctimeMs === srcStat.ctimeMs && - destStat.birthtimeMs === srcStat.birthtimeMs) { - // heuristic answer - return true + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } - } - return false -} - -// return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = path.resolve(src).split(path.sep).filter(i => i) - const destArr = path.resolve(dest).split(path.sep).filter(i => i) - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) -} - -function errMsg (src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` -} - -module.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir } +exports["default"] = ErrorFilter; /***/ }), -/***/ 52548: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 32576: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const fs = __nccwpck_require__(14178) - -function utimesMillis (path, atime, mtime, callback) { - // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) - fs.open(path, 'r+', (err, fd) => { - if (err) return callback(err) - fs.futimes(fd, atime, mtime, futimesErr => { - fs.close(fd, closeErr => { - if (callback) callback(futimesErr || closeErr) - }) - }) - }) -} - -function utimesMillisSync (path, atime, mtime) { - const fd = fs.openSync(path, 'r+') - fs.futimesSync(fd, atime, mtime) - return fs.closeSync(fd) -} - -module.exports = { - utimesMillis, - utimesMillisSync +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(45444); +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); + } } +exports["default"] = Matcher; /***/ }), -/***/ 25086: -/***/ ((module) => { +/***/ 35295: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = clone - -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -} - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy +Object.defineProperty(exports, "__esModule", ({ value: true })); +const matcher_1 = __nccwpck_require__(32576); +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } } +exports["default"] = PartialMatcher; /***/ }), -/***/ 14178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var fs = __nccwpck_require__(57147) -var polyfills = __nccwpck_require__(35027) -var legacy = __nccwpck_require__(73836) -var clone = __nccwpck_require__(25086) - -var util = __nccwpck_require__(73837) - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} +/***/ 60257: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function noop () {} +"use strict"; -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue +Object.defineProperty(exports, "__esModule", ({ value: true })); +const path = __nccwpck_require__(71017); +const deep_1 = __nccwpck_require__(36983); +const entry_1 = __nccwpck_require__(71343); +const error_1 = __nccwpck_require__(36654); +const entry_2 = __nccwpck_require__(94029); +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); } - }) -} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) + _getRootDirectory(task) { + return path.resolve(this._settings.cwd, task.base); } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) - - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; } - - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) - - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) - }) - } -} - -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); } +exports["default"] = Provider; -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch +/***/ }), - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ 94630: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return go$readFile(path, options, cb) +"use strict"; - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(12781); +const stream_2 = __nccwpck_require__(12083); +const provider_1 = __nccwpck_require__(60257); +class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); } - }) + return this._reader.static(task.patterns, options); } - } - - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +} +exports["default"] = ProviderStream; - return go$writeFile(path, data, options, cb) - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +/***/ }), - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ 42405: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return go$appendFile(path, data, options, cb) +"use strict"; - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const sync_1 = __nccwpck_require__(76234); +const provider_1 = __nccwpck_require__(60257); +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); } - } - - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); } - return go$copyFile(src, dest, flags, cb) - - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); } - }) + return this._reader.static(task.patterns, options); } - } +} +exports["default"] = ProviderSync; - var fs$readdir = fs.readdir - fs.readdir = readdir - var noReaddirOptionVersions = /^v[0-5]\./ - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - } +/***/ }), - return go$readdir(path, options, cb) +/***/ 94029: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]) - else { - if (files && files.sort) - files.sort() +"use strict"; - if (typeof cb === 'function') - cb.call(this, err, files) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(45444); +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); } - } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); } - } +} +exports["default"] = EntryTransformer; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } +/***/ }), - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +/***/ 97747: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) +"use strict"; - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); +const stream_1 = __nccwpck_require__(12083); +class ReaderAsync extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +exports["default"] = ReaderAsync; - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() +/***/ }), - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } +/***/ 65582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +"use strict"; - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const path = __nccwpck_require__(71017); +const fsStat = __nccwpck_require__(70109); +const utils = __nccwpck_require__(45444); +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +exports["default"] = Reader; - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } +/***/ }), - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null +/***/ 12083: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return go$open(path, flags, mode, cb) +"use strict"; - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(12781); +const fsStat = __nccwpck_require__(70109); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); +class ReaderStream extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); } - }) + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); } - } - - return fs } +exports["default"] = ReaderStream; -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} -// keep track of the timeout between retry() calls -var retryTimer +/***/ }), -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime +/***/ 76234: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fsStat = __nccwpck_require__(70109); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); } - } - // call retry to make sure we're actively processing the queue - retry() } +exports["default"] = ReaderSync; -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined - if (fs[gracefulQueue].length === 0) - return +/***/ }), - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] +/***/ 10952: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } +"use strict"; - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; +const fs = __nccwpck_require__(57147); +const os = __nccwpck_require__(22037); +/** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ +const CPU_COUNT = Math.max(os.cpus().length, 1); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + // Remove the cast to the array in the next major (#404). + this.ignore = [].concat(this.ignore); + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } } +exports["default"] = Settings; /***/ }), -/***/ 73836: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 85325: +/***/ ((__unused_webpack_module, exports) => { -var Stream = (__nccwpck_require__(12781).Stream) +"use strict"; -module.exports = legacy +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitWhen = exports.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +exports.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +exports.splitWhen = splitWhen; -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +/***/ }), - Stream.call(this); +/***/ 41230: +/***/ ((__unused_webpack_module, exports) => { - var self = this; +"use strict"; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +exports.isEnoentCodeError = isEnoentCodeError; - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - options = options || {}; +/***/ }), - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; +/***/ 17543: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; - if (this.encoding) this.setEncoding(this.encoding); - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +/***/ }), - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +/***/ 45444: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.pos = this.start; - } +"use strict"; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; +const array = __nccwpck_require__(85325); +exports.array = array; +const errno = __nccwpck_require__(41230); +exports.errno = errno; +const fs = __nccwpck_require__(17543); +exports.fs = fs; +const path = __nccwpck_require__(63873); +exports.path = path; +const pattern = __nccwpck_require__(81221); +exports.pattern = pattern; +const stream = __nccwpck_require__(18382); +exports.stream = stream; +const string = __nccwpck_require__(52203); +exports.string = string; - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } +/***/ }), - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); +/***/ 63873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Stream.call(this); +"use strict"; - this.path = path; - this.fd = null; - this.writable = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; +const os = __nccwpck_require__(22037); +const path = __nccwpck_require__(71017); +const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +/** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ +const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; +const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; +/** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ +const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; +/** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ +const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path.resolve(cwd, filepath); +} +exports.makeAbsolute = makeAbsolute; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +exports.removeLeadingDotSegment = removeLeadingDotSegment; +exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapePosixPath = escapePosixPath; +exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +exports.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +exports.convertPosixPathToPattern = convertPosixPathToPattern; - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - options = options || {}; +/***/ }), - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +/***/ 81221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } +"use strict"; - this.pos = this.start; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +const path = __nccwpck_require__(71017); +const globParent = __nccwpck_require__(54655); +const micromatch = __nccwpck_require__(23913); +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; +const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ +const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +exports.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; +} +exports.isDynamicPattern = isDynamicPattern; +function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf('{'); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); +} +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +exports.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +exports.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ''); +} +exports.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +exports.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +exports.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +exports.matchAny = matchAny; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, '/'); +} +exports.removeDuplicateSlashes = removeDuplicateSlashes; +function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) { + if (isAbsolute(pattern)) { + absolute.push(pattern); + } + else { + relative.push(pattern); + } + } + return [absolute, relative]; +} +exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; +function isAbsolute(pattern) { + return path.isAbsolute(pattern); +} +exports.isAbsolute = isAbsolute; - this.busy = false; - this._queue = []; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } +/***/ }), + +/***/ 18382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.merge = void 0; +const merge2 = __nccwpck_require__(82578); +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +exports.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); } /***/ }), -/***/ 35027: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var constants = __nccwpck_require__(22057) - -var origCwd = process.cwd -var cwd = null +/***/ 52203: +/***/ ((__unused_webpack_module, exports) => { -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +"use strict"; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isEmpty = exports.isString = void 0; +function isString(input) { + return typeof input === 'string'; } -try { - process.cwd() -} catch (er) {} - -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +exports.isString = isString; +function isEmpty(input) { + return input === ''; } +exports.isEmpty = isEmpty; -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) - - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) +/***/ }), - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) +/***/ 12603: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +"use strict"; - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +const validator = __nccwpck_require__(61739); +const XMLParser = __nccwpck_require__(42380); +const XMLBuilder = __nccwpck_require__(80660); - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) - return rename - })(fs.rename) - } +module.exports = { + XMLParser: XMLParser, + XMLValidator: validator, + XMLBuilder: XMLBuilder +} - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +/***/ }), - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +/***/ 4958: +/***/ ((module) => { - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } +function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) } + return () => false +} - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +module.exports = getIgnoreAttributesFn - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/***/ }), - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +/***/ 38280: +/***/ ((__unused_webpack_module, exports) => { - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +"use strict"; - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; +const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' +const regexName = new RegExp('^' + nameRegexp + '$'); - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); } + matches.push(allmatches); + match = regex.exec(string); } + return matches; +}; +const isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); +}; - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +exports.isExist = function(v) { + return typeof v !== 'undefined'; +}; - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +exports.isEmptyObject = function(obj) { + return Object.keys(obj).length === 0; +}; - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) +/** + * Copy all the properties of a into b. + * @param {*} target + * @param {*} a + */ +exports.merge = function(target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); // will return an array of own properties + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + if (arrayMode === 'strict') { + target[keys[i]] = [ a[keys[i]] ]; + } else { + target[keys[i]] = a[keys[i]]; } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) } } +}; +/* exports.merge =function (b,a){ + return Object.assign(b,a); +} */ - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } +exports.getValue = function(v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; } +}; - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +// const fakeCall = function(a) {return a;}; +// const fakeCallNoReturn = function() {}; - return false - } -} +exports.isName = isName; +exports.getAllMatches = getAllMatches; +exports.nameRegexp = nameRegexp; /***/ }), -/***/ 19320: -/***/ ((module) => { +/***/ 61739: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +const util = __nccwpck_require__(38280); - return bound; +const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] }; +//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); +exports.validate = function (xmlData, options) { + options = Object.assign({}, defaultOptions, options); -/***/ }), - -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; -var implementation = __nccwpck_require__(19320); + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { -module.exports = Function.prototype.bind || implementation; + if (xmlData[i] === '<' && xmlData[i+1] === '?') { + i+=2; + i = readPI(xmlData,i); + if (i.err) return i; + }else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '"+tagName+"' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } -/***/ }), + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; -/***/ 74538: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } -"use strict"; + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if(options.unpairedTags.indexOf(tagName) !== -1){ + //don't push into stack + } else { + tags.push({tagName, tagStartPos}); + } + tagFound = true; + } -var undefined; + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i+1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else{ + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + }else{ + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if ( isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + }else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + }else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '"+ + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ + "' found.", {line: 1, col: 1}); + } -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} + return true; }; -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } +function isWhiteSpace(char){ + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; +} +/** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; } -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = __nccwpck_require__(40587)(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = __nccwpck_require__(88334); -var hasOwn = __nccwpck_require__(76339); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } + return i; +} - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } +const doubleQuote = '"'; +const singleQuote = "'"; - return { - alias: alias, - name: intrinsicName, - value: value - }; - } +/** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ +function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa + } else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; +} -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } +/** + * Select all the attributes whether valid or invalid. + */ +const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; +//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; +function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } + //if(attrStr.trim().length === 0) return true; //empty string - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); + } + } - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; + return true; +} - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; +function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; +} +function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; +} -/***/ }), +function validateAttrName(attrName) { + return util.isName(attrName); +} -/***/ 14780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// const startsWithXML = /^xml/i; -"use strict"; -/** - * gitignore-to-glob - * https://github.com/EE/gitignore-to-glob - * - * Author Michał Gołębiowski - * Licensed under the MIT license. - */ +function validateTagName(tagname) { + return util.isName(tagname) /* && !tagname.match(startsWithXML) */; +} +//this function returns the line number for the character at the given index +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} -const fs = __nccwpck_require__(57147); -const path = __nccwpck_require__(71017); +//this function returns the position of the first character of match within attrStr +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} -module.exports = (gitignorePath, dirsToCheck) => { - gitignorePath = path.resolve(gitignorePath || '.gitignore'); - return fs.readFileSync(gitignorePath, {encoding: 'utf8'}) - .split('\n') +/***/ }), - // Filter out empty lines and comments. - .filter(pattern => !!pattern && pattern[0] !== '#') +/***/ 80660: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // '!' in .gitignore and glob mean opposite things so we need to swap it. - // Return pairt [ignoreFlag, pattern], we'll concatenate it later. - .map(pattern => pattern[0] === '!' ? ['', pattern.substring(1)] : ['!', pattern]) +"use strict"; - // Filter out hidden files/directories (i.e. starting with a dot). - .filter(patternPair => { - const pattern = patternPair[1]; - return pattern.indexOf('/.') === -1 && pattern.indexOf('.') !== 0; - }) +//parse Empty Node as self closing node +const buildFromOrderedJs = __nccwpck_require__(72462); +const getIgnoreAttributesFn = __nccwpck_require__(4958) - // There may be a lot of files outside of directories from `dirsToCheck`, don't ignore - // them wasting time. - .filter(patternPair => { - const pattern = patternPair[1]; - return pattern[0] !== '/' || !dirsToCheck || - new RegExp(`^/(?:${ dirsToCheck.join('|') })(?:/|$)`).test(pattern); - }) +const defaultOptions = { + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: ' ', + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" },//it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("\'", "g"), val: "'" }, + { regex: new RegExp("\"", "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false +}; - // Patterns not starting with '/' are in fact "starting" with '**/'. Since that would - // catch a lot of files, restrict it to directories we check. - // Patterns starting with '/' are relative to the project directory and glob would - // treat them as relative to the OS root directory so strip the slash then. - .map(patternPair => { - const pattern = patternPair[1]; - if (pattern[0] !== '/') { - return [patternPair[0], - `${ dirsToCheck ? `{${ dirsToCheck }}/` : '' }**/${ pattern }`]; - } - return [patternPair[0], pattern.substring(1)]; - }) +function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function(/*a*/) { + return false; + }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } - // We don't know whether a pattern points to a directory or a file and we need files. - // Therefore, include both `pattern` and `pattern/**` for every pattern in the array. - .reduce((result, patternPair) => { - const pattern = patternPair.join(''); - result.push(pattern); - result.push(`${ pattern }/**`); - return result; - }, []); -}; + this.processTextOrObjNode = processTextOrObjNode + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = '>\n'; + this.newLine = '\n'; + } else { + this.indentate = function() { + return ''; + }; + this.tagEndChar = '>'; + this.newLine = ''; + } +} -/***/ }), +Builder.prototype.build = function(jObj) { + if(this.options.preserveOrder){ + return buildFromOrderedJs(jObj, this.options); + }else { + if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ + jObj = { + [this.options.arrayNodeName] : jObj + } + } + return this.j2x(jObj, 0, []).val; + } +}; -/***/ 54655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Builder.prototype.j2x = function(jObj, level, ajPath) { + let attrStr = ''; + let val = ''; + const jPath = ajPath.join('.') + for (let key in jObj) { + if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === 'undefined') { + // supress undefined node only if it is not an attribute + if (this.isAttribute(key)) { + val += ''; + } + } else if (jObj[key] === null) { + // null attribute should be ignored by the attribute list, but should not cause the tag closing + if (this.isAttribute(key)) { + val += ''; + } else if (key[0] === '?') { + val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (jObj[key] instanceof Date) { + val += this.buildTextValNode(jObj[key], key, '', level); + } else if (typeof jObj[key] !== 'object') { + //premitive type + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); + } else if (!attr) { + //tag value + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, '' + jObj[key]); + val += this.replaceEntitiesValue(newval); + } else { + val += this.buildTextValNode(jObj[key], key, '', level); + } + } + } else if (Array.isArray(jObj[key])) { + //repeated nodes + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === 'undefined') { + // supress undefined node + } else if (item === null) { + if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (typeof item === 'object') { + if(this.options.oneListGroup){ + const result = this.j2x(item, level + 1, ajPath.concat(key)); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr + } + }else{ + listTagVal += this.processTextOrObjNode(item, key, level, ajPath) + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, '', level); + } + } + } + if(this.options.oneListGroup){ + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val += listTagVal; + } else { + //nested node + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); + } + } else { + val += this.processTextOrObjNode(jObj[key], key, level, ajPath) + } + } + } + return {attrStr: attrStr, val: val}; +}; -"use strict"; +Builder.prototype.buildAttrPairStr = function(attrName, val){ + val = this.options.attributeValueProcessor(attrName, '' + val); + val = this.replaceEntitiesValue(val); + if (this.options.suppressBooleanAttributes && val === "true") { + return ' ' + attrName; + } else return ' ' + attrName + '="' + val + '"'; +} +function processTextOrObjNode (object, key, level, ajPath) { + const result = this.j2x(object, level + 1, ajPath.concat(key)); + if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } +} -var isGlob = __nccwpck_require__(34466); -var pathPosixDirname = (__nccwpck_require__(71017).posix.dirname); -var isWin32 = (__nccwpck_require__(22037).platform)() === 'win32'; +Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { + if(val === ""){ + if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + }else{ -var slash = '/'; -var backslash = /\\/g; -var enclosure = /[\{\[].*[\}\]]$/; -var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; -var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + let tagEndExp = '' + val + tagEndExp ); + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + }else { + return ( + this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + + val + + this.indentate(level) + tagEndExp ); + } + } +} -/** - * @param {string} str - * @param {Object} opts - * @param {boolean} [opts.flipBackslashes=true] - * @returns {string} - */ -module.exports = function globParent(str, opts) { - var options = Object.assign({ flipBackslashes: true }, opts); +Builder.prototype.closeTag = function(key){ + let closeTag = ""; + if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired + if(!this.options.suppressUnpairedNode) closeTag = "/" + }else if(this.options.suppressEmptyNode){ //empty + closeTag = "/"; + }else{ + closeTag = `>` + this.newLine; + }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + }else if(key[0] === "?") {//PI tag + return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + }else{ + let textValue = this.options.tagValueProcessor(key, val); + textValue = this.replaceEntitiesValue(textValue); + + if( textValue === ''){ + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + }else{ + return this.indentate(level) + '<' + key + attrStr + '>' + + textValue + + ' 0 && this.options.processEntities){ + for (let i=0; i { -"use strict"; +const EOL = "\n"; +/** + * + * @param {array} jArray + * @param {any} options + * @returns + */ +function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; + } + return arrToStr(jArray, options, "", indentation); +} -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; +function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if(tagName === undefined) continue; -/***/ }), + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName + else newJPath = `${jPath}.${tagName}`; -/***/ 40587: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; + isPreviousElementTag = true; + continue; + } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + } -"use strict"; + return xmlStr; +} +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(!obj.hasOwnProperty(key)) continue; + if (key !== ":@") return key; + } +} -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = __nccwpck_require__(57747); +function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if(!attrMap.hasOwnProperty(attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; +} -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } +function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + } + return false; +} - return hasSymbolSham(); -}; +function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; +} +module.exports = toXml; /***/ }), -/***/ 57747: -/***/ ((module) => { - -"use strict"; - +/***/ 6072: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } +const util = __nccwpck_require__(38280); - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } +//TODO: handle comments +function readDocType(xmlData, i){ + + const entities = {}; + if( xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') + { + i = i+9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for(;i') { //Read tag content + if(comment){ + if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ + comment = false; + angleBracketsCount--; + } + }else{ + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + }else if( xmlData[i] === '['){ + hasBody = true; + }else{ + exp += xmlData[i]; + } + } + if(angleBracketsCount !== 0){ + throw new Error(`Unclosed DOCTYPE`); + } + }else{ + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return {entities, i}; +} - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } +function readEntityExp(xmlData,i){ + //External entities are not supported + // - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + //Parameter entities are not supported + // - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + //Internal entities are supported + // + + //read EntityName + let entityName = ""; + for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { + // if(xmlData[i] === " ") continue; + // else + entityName += xmlData[i]; + } + entityName = entityName.trim(); + if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + //read Entity Value + const startChar = xmlData[i++]; + let val = "" + for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { + val += xmlData[i]; + } + return [entityName, val, i]; +} - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } +function isComment(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === '-' && + xmlData[i+3] === '-') return true + return false +} +function isEntity(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'N' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'I' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'Y') return true + return false +} +function isElement(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'L' && + xmlData[i+4] === 'E' && + xmlData[i+5] === 'M' && + xmlData[i+6] === 'E' && + xmlData[i+7] === 'N' && + xmlData[i+8] === 'T') return true + return false +} - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } +function isAttlist(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'A' && + xmlData[i+3] === 'T' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'L' && + xmlData[i+6] === 'I' && + xmlData[i+7] === 'S' && + xmlData[i+8] === 'T') return true + return false +} +function isNotation(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'N' && + xmlData[i+3] === 'O' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'A' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'I' && + xmlData[i+8] === 'O' && + xmlData[i+9] === 'N') return true + return false +} - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } +function validateEntityName(name){ + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); +} - return true; -}; +module.exports = readDocType; /***/ }), -/***/ 99038: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +/***/ 86993: +/***/ ((__unused_webpack_module, exports) => { -var hasSymbols = __nccwpck_require__(57747); -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; +const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function(tagName, val) { + return val; + }, + attributeValueProcessor: function(attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs){ + return tagName + }, + // skipEmptyListItem: false +}; + +const buildOptions = function(options) { + return Object.assign({}, defaultOptions, options); }; +exports.buildOptions = buildOptions; +exports.defaultOptions = defaultOptions; /***/ }), -/***/ 76339: +/***/ 25832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +///@ts-check -var bind = __nccwpck_require__(88334); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - - -/***/ }), +const util = __nccwpck_require__(38280); +const xmlNode = __nccwpck_require__(7462); +const readDocType = __nccwpck_require__(6072); +const toNumber = __nccwpck_require__(14526); +const getIgnoreAttributesFn = __nccwpck_require__(4958) -/***/ 23764: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// const regx = +// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' +// .replace(/NAME/g, util.nameRegexp); -"use strict"; +//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); +//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpProxyAgent = void 0; -const net = __importStar(__nccwpck_require__(41808)); -const tls = __importStar(__nccwpck_require__(24404)); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const events_1 = __nccwpck_require__(82361); -const agent_base_1 = __nccwpck_require__(70694); -const url_1 = __nccwpck_require__(57310); -const debug = (0, debug_1.default)('http-proxy-agent'); -/** - * The `HttpProxyAgent` implements an HTTP Agent subclass that connects - * to the specified "HTTP proxy server" in order to proxy HTTP requests. - */ -class HttpProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); - // Trim off the brackets from IPv6 addresses - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); - const port = this.proxy.port - ? parseInt(this.proxy.port, 10) - : this.proxy.protocol === 'https:' - ? 443 - : 80; - this.connectOpts = { - ...(opts ? omit(opts, 'headers') : null), - host, - port, - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - // @ts-expect-error `addRequest()` isn't defined in `@types/node` - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? 'https:' : 'http:'; - const hostname = req.getHeader('host') || 'localhost'; - const base = `${protocol}//${hostname}`; - const url = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url.port = String(opts.port); - } - // Change the `http.ClientRequest` instance's "path" field - // to the absolute path of the URL that will be requested. - req.path = String(url); - // Inject the `Proxy-Authorization` header if necessary. - const headers = typeof this.proxyHeaders === 'function' - ? this.proxyHeaders() - : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; - } - if (!headers['Proxy-Connection']) { - headers['Proxy-Connection'] = this.keepAlive - ? 'Keep-Alive' - : 'close'; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes('://')) { - this.setRequestProps(req, opts); - } - // At this point, the http ClientRequest's internal `_header` field - // might have already been set. If this is the case then we'll need - // to re-generate the string since we just changed the `req.path`. - let first; - let endOfHeaders; - debug('Regenerating stored HTTP header string for request'); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug('Patching connection write() output buffer with updated header'); - first = req.outputData[0].data; - endOfHeaders = first.indexOf('\r\n\r\n') + 4; - req.outputData[0].data = - req._header + first.substring(endOfHeaders); - debug('Output buffer: %o', req.outputData[0].data); - } - // Create a socket connection to the proxy server. - let socket; - if (this.proxy.protocol === 'https:') { - debug('Creating `tls.Socket`: %o', this.connectOpts); - socket = tls.connect(this.connectOpts); - } - else { - debug('Creating `net.Socket`: %o', this.connectOpts); - socket = net.connect(this.connectOpts); - } - // Wait for the socket's `connect` event, so that this `callback()` - // function throws instead of the `http` request machinery. This is - // important for i.e. `PacProxyAgent` which determines a failed proxy - // connection via the `callback()` function throwing. - await (0, events_1.once)(socket, 'connect'); - return socket; +class OrderedObjParser{ + constructor(options){ + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes) + } + +} + +function addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.lastEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : externalEntities[ent] } + } } -HttpProxyAgent.protocols = ['http', 'https']; -exports.HttpProxyAgent = HttpProxyAgent; -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; + +/** + * @param {string} val + * @param {string} tagName + * @param {string} jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities + */ +function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val !== undefined) { + if (this.options.trimValues && !dontTrim) { + val = val.trim(); + } + if(val.length > 0){ + if(!escapeEntities) val = this.replaceEntitiesValue(val); + + const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); + if(newval === null || newval === undefined){ + //don't parse + return val; + }else if(typeof newval !== typeof val || newval !== val){ + //overwrite + return newval; + }else if(this.options.trimValues){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + const trimmedVal = val.trim(); + if(trimmedVal === val){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + return val; } + } } - return ret; + } } -//# sourceMappingURL=index.js.map -/***/ }), +function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; +} -/***/ 77219: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +//TODO: change regex to capture NS +//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); -"use strict"; +function buildAttributesMap(attrStr, jPath, tagName) { + if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + if (this.ignoreAttributesFn(attrName, jPath)) { + continue + } + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + if(aName === "__proto__") aName = "#__proto__"; + if (oldVal !== undefined) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if(newVal === null || newVal === undefined){ + //don't parse + attrs[aName] = oldVal; + }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ + //overwrite + attrs[aName] = newVal; + }else{ + //parse + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } + } } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpsProxyAgent = void 0; -const net = __importStar(__nccwpck_require__(41808)); -const tls = __importStar(__nccwpck_require__(24404)); -const assert_1 = __importDefault(__nccwpck_require__(39491)); -const debug_1 = __importDefault(__nccwpck_require__(6785)); -const agent_base_1 = __nccwpck_require__(70694); -const url_1 = __nccwpck_require__(57310); -const parse_proxy_response_1 = __nccwpck_require__(595); -const debug = (0, debug_1.default)('https-proxy-agent'); -const setServernameFromNonIpHost = (options) => { - if (options.servername === undefined && - options.host && - !net.isIP(options.host)) { - return { - ...options, - servername: options.host, - }; + if (!Object.keys(attrs).length) { + return; } - return options; -}; -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: undefined }; - this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); - // Trim off the brackets from IPv6 addresses - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); - const port = this.proxy.port - ? parseInt(this.proxy.port, 10) - : this.proxy.protocol === 'https:' - ? 443 - : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ['http/1.1'], - ...(opts ? omit(opts, 'headers') : null), - host, - port, - }; + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); - } - // Create a socket connection to the proxy server. - let socket; - if (proxy.protocol === 'https:') { - debug('Creating `tls.Socket`: %o', this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + return attrs + } +} + +const parseXml = function(xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + for(let i=0; i< xmlData.length; i++){//for each char in XML data + const ch = xmlData[i]; + if(ch === '<'){ + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + if( xmlData[i+1] === '/') {//Closing Tag + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") + let tagName = xmlData.substring(i+2,closeIndex).trim(); + + if(this.options.removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + } } - else { - debug('Creating `net.Socket`: %o', this.connectOpts); - socket = net.connect(this.connectOpts); + + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); } - const headers = typeof this.proxyHeaders === 'function' - ? this.proxyHeaders() - : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + + if(currentNode){ + textData = this.saveTextToParentTag(textData, currentNode, jPath); } - headers.Host = `${host}:${opts.port}`; - if (!headers['Proxy-Connection']) { - headers['Proxy-Connection'] = this.keepAlive - ? 'Keep-Alive' - : 'close'; + + //check if last tag of nested tag was unpaired tag + const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); + if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ + throw new Error(`Unpaired tag can not be used as closing tag: `); } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; + let propIndex = 0 + if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ + propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) + this.tagsNodeStack.pop(); + }else{ + propIndex = jPath.lastIndexOf("."); } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r\n`); - const { connect, buffered } = await proxyResponsePromise; - req.emit('proxyConnect', connect); - this.emit('proxyConnect', connect, req); - if (connect.statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), - socket, - }); - } - return socket; + jPath = jPath.substring(0, propIndex); + + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if( xmlData[i+1] === '?') { + + let tagData = readTagExp(xmlData,i, false, "?>"); + if(!tagData) throw new Error("Pi Tag is not closed."); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ + + }else{ + + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + + if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath) + } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('Replaying proxy buffer for failed request'); - (0, assert_1.default)(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } -} -HttpsProxyAgent.protocols = ['http', 'https']; -exports.HttpsProxyAgent = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; + + + i = tagData.closeIndex + 1; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") + if(this.options.commentPropName){ + const comment = xmlData.substring(i + 4, endIndex - 2); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + + currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); } - } - return ret; -} -//# sourceMappingURL=index.js.map + i = endIndex; + } else if( xmlData.substr(i + 1, 2) === '!D') { + const result = readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + }else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9,closeIndex); -/***/ }), + textData = this.saveTextToParentTag(textData, currentNode, jPath); -/***/ 595: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if(val == undefined) val = ""; -"use strict"; + //cdata should be set even if it is 0 length string + if(this.options.cdataPropName){ + currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); + }else{ + currentNode.add(this.options.textNodeName, val); + } + + i = closeIndex + 2; + }else {//Opening tag + let result = readTagExp(xmlData,i, this.options.removeNSPrefix); + let tagName= result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseProxyResponse = void 0; -const debug_1 = __importDefault(__nccwpck_require__(6785)); -const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('readable', read); + + //save text as child node + if (currentNode && textData) { + if(currentNode.tagname !== '!xml'){ + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } } - function onend() { - cleanup(); - debug('onend'); - reject(new Error('Proxy connection ended before receiving CONNECT response')); + + //check if last tag was unpaired tag + const lastTag = currentNode; + if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); + if(tagName !== xmlObj.tagname){ + jPath += jPath ? "." + tagName : tagName; } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; + if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + let tagContent = ""; + //self-closing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); } - const headerParts = buffered - .slice(0, endOfHeaders) - .toString('ascii') - .split('\r\n'); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error('No header received from proxy CONNECT response')); + i = result.closeIndex; + } + //unpaired tag + else if(this.options.unpairedTags.indexOf(tagName) !== -1){ + + i = result.closeIndex; + } + //normal tag + else{ + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if(!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } + + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if(tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + + this.addChild(currentNode, childNode, jPath) + }else{ + //selfClosing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); } - const firstLineParts = firstLine.split(' '); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(' '); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(':'); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === 'string') { - headers[key] = [current, value]; - } - else if (Array.isArray(current)) { - current.push(value); - } - else { - headers[key] = value; - } + + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); } - debug('got proxy server response: %o %o', firstLine, headers); - cleanup(); - resolve({ - connect: { - statusCode, - statusText, - headers, - }, - buffered, - }); + + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } + //opening tag + else{ + const childNode = new xmlNode( tagName); + this.tagsNodeStack.push(currentNode); + + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + currentNode = childNode; + } + textData = ""; + i = closeIndex; } - socket.on('error', onerror); - socket.on('end', onend); - read(); - }); + } + }else{ + textData += xmlData[i]; + } + } + return xmlObj.child; } -exports.parseProxyResponse = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map -/***/ }), +function addChild(currentNode, childNode, jPath){ + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) + if(result === false){ + }else if(typeof result === "string"){ + childNode.tagname = result + currentNode.addChild(childNode); + }else{ + currentNode.addChild(childNode); + } +} -/***/ 90814: -/***/ ((module, exports, __nccwpck_require__) => { +const replaceEntitiesValue = function(val){ -/* eslint-env browser */ + if(this.options.processEntities){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.options.htmlEntities){ + for(let entityName in this.htmlEntities){ + const entity = this.htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( this.ampEntity.regex, this.ampEntity.val); + } + return val; +} +function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { + if (textData) { //store previously collected data as textNode + if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0 + + textData = this.parseTextData(textData, + currentNode.tagname, + jPath, + false, + currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, + isLeafNode); + + if (textData !== undefined && textData !== "") + currentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; +} +//TODO: use jPath to simplify the logic /** - * This is the web browser implementation of `debug()`. + * + * @param {string[]} stopNodes + * @param {string} jPath + * @param {string} currentTagName */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); +function isItStopNode(stopNodes, jPath, currentTagName){ + const allNodesExp = "*." + currentTagName; + for (const stopNodePath in stopNodes) { + const stopNodeExp = stopNodes[stopNodePath]; + if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; + } + return false; +} /** - * Colors. + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns */ +function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = "";//reset + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if(closingChar[1]){ + if(xmlData[index + 1] === closingChar[1]){ + return { + data: tagExp, + index: index + } + } + }else{ + return { + data: tagExp, + index: index + } + } + } else if (ch === '\t') { + ch = " " + } + tagExp += ch; + } +} -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +function findClosingIndex(xmlData, str, i, errMsg){ + const closingIndex = xmlData.indexOf(str, i); + if(closingIndex === -1){ + throw new Error(errMsg) + }else{ + return closingIndex + str.length - 1; + } +} + +function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ + const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); + if(!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if(separatorIndex !== -1){//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + + const rawTagName = tagName; + if(removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, + } +} /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i */ +function readStopNodeData(xmlData, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + for (; i < xmlData.length; i++) { + if( xmlData[i] === "<"){ + if (xmlData[i+1] === "/") {//close tag + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlData[i+1] === '?') { + const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlData, i, '>') - let m; + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - // eslint-disable-next-line no-return-assign - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if(newval === 'true' ) return true; + else if(newval === 'false' ) return false; + else return toNumber(val, options); + } else { + if (util.isExist(val)) { + return val; + } else { + return ''; + } + } } -/** - * Colorize log arguments if enabled. - * - * @api public - */ -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); +module.exports = OrderedObjParser; - if (!this.useColors) { - return; - } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); +/***/ }), - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +/***/ 42380: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - args.splice(lastC, 0, c); +const { buildOptions} = __nccwpck_require__(86993); +const OrderedObjParser = __nccwpck_require__(25832); +const { prettify} = __nccwpck_require__(42882); +const validator = __nccwpck_require__(61739); + +class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData,validationOption){ + if(typeof xmlData === "string"){ + }else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else{ + throw new Error("XML data is accepted in String or Bytes[] form.") + } + if( validationOption){ + if(validationOption === true) validationOption = {}; //validate with default options + + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else{ + this.externalEntities[key] = value; + } + } } -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); +module.exports = XMLParser; + +/***/ }), + +/***/ 42882: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * + * @param {array} node + * @param {any} options + * @returns */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function prettify(node, options){ + return compress( node, options); } /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * + * @param {array} arr + * @param {object} options + * @param {string} jPath + * @returns object */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function compress(arr, options, jPath){ + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if(jPath === undefined) newJpath = property; + else newJpath = jPath + "." + property; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + if(property === options.textNodeName){ + if(text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + }else if(property === undefined){ + continue; + }else if(tagObj[property]){ + + let val = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val, options); - return r; + if(tagObj[":@"]){ + assignAttributes( val, tagObj[":@"], newJpath, options); + }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ + val = val[options.textNodeName]; + }else if(Object.keys(val).length === 0){ + if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { + if(!Array.isArray(compressedObj[property])) { + compressedObj[property] = [ compressedObj[property] ]; + } + compressedObj[property].push(val); + }else{ + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + if (options.isArray(property, newJpath, isLeaf )) { + compressedObj[property] = [val]; + }else{ + compressedObj[property] = val; + } + } + } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if(typeof text === "string"){ + if(text.length > 0) compressedObj[options.textNodeName] = text; + }else if(text !== undefined) compressedObj[options.textNodeName] = text; + return compressedObj; } -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +function propName(obj){ + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(key !== ":@") return key; + } +} -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function assignAttributes(obj, attrMap, jpath, options){ + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [ attrMap[atrrName] ]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } } -module.exports = __nccwpck_require__(76127)(exports); +function isLeafTag(obj, options){ + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } -const {formatters} = module.exports; + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + return false; +} +exports.prettify = prettify; -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } + +/***/ }), + +/***/ 7462: +/***/ ((module) => { + +"use strict"; + + +class XmlNode{ + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = {}; //attributes map + } + add(key,val){ + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if(key === "__proto__") key = "#__proto__"; + this.child.push( {[key]: val }); + } + addChild(node) { + if(node.tagname === "__proto__") node.tagname = "#__proto__"; + if(node[":@"] && Object.keys(node[":@"]).length > 0){ + this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); + }else{ + this.child.push( { [node.tagname]: node.child }); + } + }; }; +module.exports = XmlNode; + /***/ }), -/***/ 76127: +/***/ 7340: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(80900); - createDebug.destroy = destroy; +/* eslint-disable no-var */ - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +var reusify = __nccwpck_require__(32113) - /** - * The currently active debug mode names, and names to skip. - */ +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker + worker = context + context = null + } - createDebug.names = []; - createDebug.skips = []; + if (concurrency < 1) { + throw new Error('fastqueue concurrency must be greater than 1') + } - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 + var errorHandler = null - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error + } - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + return self - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + function running () { + return _running + } - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; + function pause () { + self.paused = true + } - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + function length () { + var current = queueHead + var counter = 0 - const self = debug; + while (current) { + current = current.next + counter++ + } - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + return counter + } - args[0] = createDebug.coerce(args[0]); + function getQueue () { + var current = queueHead + var tasks = [] - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + while (current) { + tasks.push(current.value) + current = current.next + } - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + return tasks + } - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + function resume () { + if (!self.paused) return + self.paused = false + for (var i = 0; i < self.concurrency; i++) { + _running++ + release() + } + } - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + function idle () { + return _running === 0 && self.length() === 0 + } - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + function push (value, done) { + var current = cache.get() - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + function unshift (value, done) { + var current = cache.get() - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + current.context = context + current.release = release + current.value = value + current.callback = done || noop - return debug; - } + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } + } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; + function kill () { + queueHead = null + queueTail = null + self.drain = noop + } - createDebug.names = []; - createDebug.skips = []; + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop + } - const split = (typeof namespaces === 'string' ? namespaces : '') - .trim() - .replace(' ', ',') - .split(',') - .filter(Boolean); + function error (handler) { + errorHandler = handler + } +} - for (const ns of split) { - if (ns[0] === '-') { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } +function noop () {} - /** - * Checks if the given string matches a namespace template, honoring - * asterisks as wildcards. - * - * @param {String} search - * @param {String} template - * @return {Boolean} - */ - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null + this.errorHandler = null - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { - // Match character or proceed with wildcard - if (template[templateIndex] === '*') { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; // Skip the '*' - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition - // Backtrack to the last '*' and try to match more characters - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; // No match - } - } + var self = this - // Handle trailing '*' in template - while (templateIndex < template.length && template[templateIndex] === '*') { - templateIndex++; - } + this.worked = function worked (err, result) { + var callback = self.callback + var errorHandler = self.errorHandler + var val = self.value + self.value = null + self.callback = noop + if (self.errorHandler) { + errorHandler(err, val) + } + callback.call(self.context, err, result) + self.release(self) + } +} - return templateIndex === template.length; - } +function queueAsPromised (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker + worker = context + context = null + } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res) + }, cb) + } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } + var queue = fastqueue(context, asyncWrapper, concurrency) - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } + var pushCb = queue.push + var unshiftCb = queue.unshift - return false; - } + queue.push = push + queue.unshift = unshift + queue.drained = drained - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + return queue - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) - createDebug.enable(createDebug.load()); + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) - return createDebug; + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function drained () { + var previousDrain = queue.drain + + var p = new Promise(function (resolve) { + queue.drain = function () { + previousDrain() + resolve() + } + }) + + return p + } } -module.exports = setup; +module.exports = fastqueue +module.exports.promise = queueAsPromised /***/ }), -/***/ 6785: +/***/ 89618: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ +"use strict"; -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(90814); -} else { - module.exports = __nccwpck_require__(49559); + +const fs = __nccwpck_require__(14178) +const path = __nccwpck_require__(71017) +const mkdirsSync = (__nccwpck_require__(98605).mkdirsSync) +const utimesMillisSync = (__nccwpck_require__(52548).utimesMillisSync) +const stat = __nccwpck_require__(73901) + +function copySync (src, dest, opts) { + if (typeof opts === 'function') { + opts = { filter: opts } + } + + opts = opts || {} + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0002' + ) + } + + const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) + stat.checkParentPathsSync(src, srcStat, dest, 'copy') + if (opts.filter && !opts.filter(src, dest)) return + const destParent = path.dirname(dest) + if (!fs.existsSync(destParent)) mkdirsSync(destParent) + return getStats(destStat, src, dest, opts) } +function getStats (destStat, src, dest, opts) { + const statSync = opts.dereference ? fs.statSync : fs.lstatSync + const srcStat = statSync(src) -/***/ }), + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) + else if (srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) + else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) + else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) +} -/***/ 49559: -/***/ ((module, exports, __nccwpck_require__) => { +function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + return mayCopyFile(srcStat, src, dest, opts) +} -/** - * Module dependencies. - */ +function mayCopyFile (srcStat, src, dest, opts) { + if (opts.overwrite) { + fs.unlinkSync(dest) + return copyFile(srcStat, src, dest, opts) + } else if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } +} -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); +function copyFile (srcStat, src, dest, opts) { + fs.copyFileSync(src, dest) + if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) + return setDestMode(dest, srcStat.mode) +} -/** - * This is the Node.js implementation of `debug()`. - */ +function handleTimestamps (srcMode, src, dest) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) + return setDestTimestamps(src, dest) +} -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} -/** - * Colors. - */ +function makeFileWritable (dest, srcMode) { + return setDestMode(dest, srcMode | 0o200) +} -exports.colors = [6, 2, 3, 4, 5, 1]; +function setDestMode (dest, srcMode) { + return fs.chmodSync(dest, srcMode) +} -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); +function setDestTimestamps (src, dest) { + // The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = fs.statSync(src) + return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) +} - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. +function onDir (srcStat, destStat, src, dest, opts) { + if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) + return copyDir(src, dest, opts) } -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +function mkDirAndCopy (srcMode, src, dest, opts) { + fs.mkdirSync(dest) + copyDir(src, dest, opts) + return setDestMode(dest, srcMode) +} -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +function copyDir (src, dest, opts) { + const dir = fs.opendirSync(src) - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + try { + let dirent - obj[prop] = val; - return obj; -}, {}); + while ((dirent = dir.readSync()) !== null) { + copyDirItem(dirent.name, src, dest, opts) + } + } finally { + dir.closeSync() + } +} -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +function copyDirItem (item, src, dest, opts) { + const srcItem = path.join(src, item) + const destItem = path.join(dest, item) + if (opts.filter && !opts.filter(srcItem, destItem)) return + const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) + return getStats(destStat, srcItem, destItem, opts) +} + +function onLink (destStat, src, dest, opts) { + let resolvedSrc = fs.readlinkSync(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } + + if (!destStat) { + return fs.symlinkSync(resolvedSrc, dest) + } else { + let resolvedDest + try { + resolvedDest = fs.readlinkSync(dest) + } catch (err) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) + throw err + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } + + // prevent copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } + return copyLink(resolvedSrc, dest) + } +} + +function copyLink (resolvedSrc, dest) { + fs.unlinkSync(dest) + return fs.symlinkSync(resolvedSrc, dest) +} + +module.exports = copySync + + +/***/ }), + +/***/ 38834: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const fs = __nccwpck_require__(61176) +const path = __nccwpck_require__(71017) +const { mkdirs } = __nccwpck_require__(98605) +const { pathExists } = __nccwpck_require__(43835) +const { utimesMillis } = __nccwpck_require__(52548) +const stat = __nccwpck_require__(73901) + +async function copy (src, dest, opts = {}) { + if (typeof opts === 'function') { + opts = { filter: opts } + } + + opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now + opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber + + // Warn about using preserveTimestamps on 32-bit node + if (opts.preserveTimestamps && process.arch === 'ia32') { + process.emitWarning( + 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', + 'Warning', 'fs-extra-WARN0001' + ) + } + + const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts) + + await stat.checkParentPaths(src, srcStat, dest, 'copy') + + const include = await runFilter(src, dest, opts) + + if (!include) return + + // check if the parent of dest exists, and create it if it doesn't exist + const destParent = path.dirname(dest) + const dirExists = await pathExists(destParent) + if (!dirExists) { + await mkdirs(destParent) + } + + await getStatsAndPerformCopy(destStat, src, dest, opts) +} -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +async function runFilter (src, dest, opts) { + if (!opts.filter) return true + return opts.filter(src, dest) } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +async function getStatsAndPerformCopy (destStat, src, dest, opts) { + const statFn = opts.dereference ? fs.stat : fs.lstat + const srcStat = await statFn(src) -function formatArgs(args) { - const {namespace: name, useColors} = this; + if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + if ( + srcStat.isFile() || + srcStat.isCharacterDevice() || + srcStat.isBlockDevice() + ) return onFile(srcStat, destStat, src, dest, opts) - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } + if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) + if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) + if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) + throw new Error(`Unknown file: ${src}`) } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; +async function onFile (srcStat, destStat, src, dest, opts) { + if (!destStat) return copyFile(srcStat, src, dest, opts) + + if (opts.overwrite) { + await fs.unlink(dest) + return copyFile(srcStat, src, dest, opts) + } + if (opts.errorOnExist) { + throw new Error(`'${dest}' already exists`) + } } -/** - * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. - */ +async function copyFile (srcStat, src, dest, opts) { + await fs.copyFile(src, dest) + if (opts.preserveTimestamps) { + // Make sure the file is writable before setting the timestamp + // otherwise open fails with EPERM when invoked with 'r+' + // (through utimes call) + if (fileIsNotWritable(srcStat.mode)) { + await makeFileWritable(dest, srcStat.mode) + } -function log(...args) { - return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); -} + // Set timestamps and mode correspondingly -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } + // Note that The initial srcStat.atime cannot be trusted + // because it is modified by the read(2) system call + // (See https://nodejs.org/api/fs.html#fs_stat_time_values) + const updatedSrcStat = await fs.stat(src) + await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime) + } + + return fs.chmod(dest, srcStat.mode) } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +function fileIsNotWritable (srcMode) { + return (srcMode & 0o200) === 0 +} -function load() { - return process.env.DEBUG; +function makeFileWritable (dest, srcMode) { + return fs.chmod(dest, srcMode | 0o200) } -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +async function onDir (srcStat, destStat, src, dest, opts) { + // the dest directory might not exist, create it + if (!destStat) { + await fs.mkdir(dest) + } -function init(debug) { - debug.inspectOpts = {}; + const promises = [] - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + // loop through the files in the current directory to copy everything + for await (const item of await fs.opendir(src)) { + const srcItem = path.join(src, item.name) + const destItem = path.join(dest, item.name) -module.exports = __nccwpck_require__(76127)(exports); + promises.push( + runFilter(srcItem, destItem, opts).then(include => { + if (include) { + // only copy the item if it matches the filter function + return stat.checkPaths(srcItem, destItem, 'copy', opts).then(({ destStat }) => { + // If the item is a copyable file, `getStatsAndPerformCopy` will copy it + // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively + return getStatsAndPerformCopy(destStat, srcItem, destItem, opts) + }) + } + }) + ) + } -const {formatters} = module.exports; + await Promise.all(promises) -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (!destStat) { + await fs.chmod(dest, srcStat.mode) + } +} -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +async function onLink (destStat, src, dest, opts) { + let resolvedSrc = await fs.readlink(src) + if (opts.dereference) { + resolvedSrc = path.resolve(process.cwd(), resolvedSrc) + } + if (!destStat) { + return fs.symlink(resolvedSrc, dest) + } -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + let resolvedDest = null + try { + resolvedDest = await fs.readlink(dest) + } catch (e) { + // dest exists and is a regular file or directory, + // Windows may throw UNKNOWN error. If dest already exists, + // fs throws error anyway, so no need to guard against it here. + if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest) + throw e + } + if (opts.dereference) { + resolvedDest = path.resolve(process.cwd(), resolvedDest) + } + if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { + throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) + } -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + // do not copy if src is a subdir of dest since unlinking + // dest in this case would result in removing src contents + // and therefore a broken symlink would be created. + if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) { + throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) + } + + // copy the link + await fs.unlink(dest) + return fs.symlink(resolvedSrc, dest) +} + +module.exports = copy /***/ }), -/***/ 44124: +/***/ 61335: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -try { - var util = __nccwpck_require__(73837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); +"use strict"; + + +const u = (__nccwpck_require__(9046).fromPromise) +module.exports = { + copy: u(__nccwpck_require__(38834)), + copySync: __nccwpck_require__(89618) } /***/ }), -/***/ 8544: -/***/ ((module) => { +/***/ 96970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } +"use strict"; + + +const u = (__nccwpck_require__(9046).fromPromise) +const fs = __nccwpck_require__(61176) +const path = __nccwpck_require__(71017) +const mkdir = __nccwpck_require__(98605) +const remove = __nccwpck_require__(47357) + +const emptyDir = u(async function emptyDir (dir) { + let items + try { + items = await fs.readdir(dir) + } catch { + return mkdir.mkdirs(dir) + } + + return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) +}) + +function emptyDirSync (dir) { + let items + try { + items = fs.readdirSync(dir) + } catch { + return mkdir.mkdirsSync(dir) } + + items.forEach(item => { + item = path.join(dir, item) + remove.removeSync(item) + }) +} + +module.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir } /***/ }), -/***/ 53448: +/***/ 2164: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var acorn = __nccwpck_require__(74012); -var objectAssign = __nccwpck_require__(17426); - -module.exports = isExpression; +const u = (__nccwpck_require__(9046).fromPromise) +const path = __nccwpck_require__(71017) +const fs = __nccwpck_require__(61176) +const mkdir = __nccwpck_require__(98605) -var DEFAULT_OPTIONS = { - throw: false, - strict: false, - lineComment: false -}; +async function createFile (file) { + let stats + try { + stats = await fs.stat(file) + } catch { } + if (stats && stats.isFile()) return -function isExpression(src, options) { - options = objectAssign({}, DEFAULT_OPTIONS, options); + const dir = path.dirname(file) + let dirStats = null try { - var parser = new acorn.Parser(options, src, 0); - - if (options.strict) { - parser.strict = true; + dirStats = await fs.stat(dir) + } catch (err) { + // if the directory doesn't exist, make it + if (err.code === 'ENOENT') { + await mkdir.mkdirs(dir) + await fs.writeFile(file, '') + return + } else { + throw err } + } - if (!options.lineComment) { - parser.skipLineComment = function (startSkip) { - this.raise(this.pos, 'Line comments not allowed in an expression'); - }; - } + if (dirStats.isDirectory()) { + await fs.writeFile(file, '') + } else { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + await fs.readdir(dir) + } +} - parser.nextToken(); - parser.parseExpression(); +function createFileSync (file) { + let stats + try { + stats = fs.statSync(file) + } catch { } + if (stats && stats.isFile()) return - if (parser.type !== acorn.tokTypes.eof) { - parser.unexpected(); - } - } catch (ex) { - if (!options.throw) { - return false; + const dir = path.dirname(file) + try { + if (!fs.statSync(dir).isDirectory()) { + // parent is not a directory + // This is just to cause an internal ENOTDIR error to be thrown + fs.readdirSync(dir) } - - throw ex; + } catch (err) { + // If the stat call above failed because the directory doesn't exist, create it + if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) + else throw err } - return true; + fs.writeFileSync(file, '') +} + +module.exports = { + createFile: u(createFile), + createFileSync } /***/ }), -/***/ 74012: -/***/ (function(__unused_webpack_module, exports) { +/***/ 40055: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; +"use strict"; - // Reserved word lists for various dialects of the language - var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" - }; +const { createFile, createFileSync } = __nccwpck_require__(2164) +const { createLink, createLinkSync } = __nccwpck_require__(53797) +const { createSymlink, createSymlinkSync } = __nccwpck_require__(72549) - // And the keywords +module.exports = { + // file + createFile, + createFileSync, + ensureFile: createFile, + ensureFileSync: createFileSync, + // link + createLink, + createLinkSync, + ensureLink: createLink, + ensureLinkSync: createLinkSync, + // symlink + createSymlink, + createSymlinkSync, + ensureSymlink: createSymlink, + ensureSymlinkSync: createSymlinkSync +} - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; - var keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" - }; +/***/ }), - var keywordRelationalOperator = /^in(stanceof)?$/; +/***/ 53797: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // ## Character categories +"use strict"; - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `bin/generate-identifier-regex.js`. - var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +const u = (__nccwpck_require__(9046).fromPromise) +const path = __nccwpck_require__(71017) +const fs = __nccwpck_require__(61176) +const mkdir = __nccwpck_require__(98605) +const { pathExists } = __nccwpck_require__(43835) +const { areIdentical } = __nccwpck_require__(73901) - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +async function createLink (srcpath, dstpath) { + let dstStat + try { + dstStat = await fs.lstat(dstpath) + } catch { + // ignore error + } - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by bin/generate-identifier-regex.js + let srcStat + try { + srcStat = await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err + } - // eslint-disable-next-line comma-spacing - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; + if (dstStat && areIdentical(srcStat, dstStat)) return - // eslint-disable-next-line comma-spacing - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; + const dir = path.dirname(dstpath) - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) { return false } - pos += set[i + 1]; - if (pos >= code) { return true } - } + const dirExists = await pathExists(dir) + + if (!dirExists) { + await mkdir.mkdirs(dir) } - // Test whether a given character code starts an identifier. + await fs.link(srcpath, dstpath) +} - function isIdentifierStart(code, astral) { - if (code < 65) { return code === 36 } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) +function createLinkSync (srcpath, dstpath) { + let dstStat + try { + dstStat = fs.lstatSync(dstpath) + } catch {} + + try { + const srcStat = fs.lstatSync(srcpath) + if (dstStat && areIdentical(srcStat, dstStat)) return + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err } - // Test whether a given character is part of an identifier. + const dir = path.dirname(dstpath) + const dirExists = fs.existsSync(dir) + if (dirExists) return fs.linkSync(srcpath, dstpath) + mkdir.mkdirsSync(dir) - function isIdentifierChar(code, astral) { - if (code < 48) { return code === 36 } - if (code < 58) { return true } - if (code < 65) { return false } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) - } + return fs.linkSync(srcpath, dstpath) +} - // ## Token types +module.exports = { + createLink: u(createLink), + createLinkSync +} - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. - // All token type variables start with an underscore, to make them - // easy to recognize. +/***/ }), - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // The `startsExpr` property is used to check if the token ends a - // `yield` expression. It is set on all token types that either can - // directly start an expression (like a quotation mark) or can - // continue an expression (like the body of a string). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. +/***/ 53727: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; +"use strict"; - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; - }; - function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) - } - var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; +const path = __nccwpck_require__(71017) +const fs = __nccwpck_require__(61176) +const { pathExists } = __nccwpck_require__(43835) - // Map keyword names to token types. +const u = (__nccwpck_require__(9046).fromPromise) - var keywords$1 = {}; +/** + * Function that returns two types of paths, one relative to symlink, and one + * relative to the current working directory. Checks if path is absolute or + * relative. If the path is relative, this function checks if the path is + * relative to symlink or relative to current working directory. This is an + * initiative to find a smarter `srcpath` to supply when building symlinks. + * This allows you to determine which path to use out of one of three possible + * types of source paths. The first is an absolute path. This is detected by + * `path.isAbsolute()`. When an absolute path is provided, it is checked to + * see if it exists. If it does it's used, if not an error is returned + * (callback)/ thrown (sync). The other two options for `srcpath` are a + * relative url. By default Node's `fs.symlink` works by creating a symlink + * using `dstpath` and expects the `srcpath` to be relative to the newly + * created symlink. If you provide a `srcpath` that does not exist on the file + * system it results in a broken symlink. To minimize this, the function + * checks to see if the 'relative to symlink' source file exists, and if it + * does it will use it. If it does not, it checks if there's a file that + * exists that is relative to the current working directory, if does its used. + * This preserves the expectations of the original fs.symlink spec and adds + * the ability to pass in `relative to current working direcotry` paths. + */ - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; +async function symlinkPaths (srcpath, dstpath) { + if (path.isAbsolute(srcpath)) { + try { + await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + throw err + } - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) + return { + toCwd: srcpath, + toDst: srcpath + } } - var types = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - questionDot: new TokenType("?."), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - invalidTemplate: new TokenType("invalidTemplate"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. + const exists = await pathExists(relativeToDst) + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath + } + } - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=/===/!==", 6), - relational: binop("/<=/>=", 7), - bitShift: binop("<>/>>>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - coalesce: binop("??", 1), + try { + await fs.lstat(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + throw err + } - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class", startsExpr), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import", startsExpr), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) - }; + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) + } +} - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. +function symlinkPathsSync (srcpath, dstpath) { + if (path.isAbsolute(srcpath)) { + const exists = fs.existsSync(srcpath) + if (!exists) throw new Error('absolute srcpath does not exist') + return { + toCwd: srcpath, + toDst: srcpath + } + } - var lineBreak = /\r\n?|\n|\u2028|\u2029/; - var lineBreakG = new RegExp(lineBreak.source, "g"); + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + const exists = fs.existsSync(relativeToDst) + if (exists) { + return { + toCwd: relativeToDst, + toDst: srcpath + } + } - function isNewLine(code, ecma2019String) { - return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) + const srcExists = fs.existsSync(srcpath) + if (!srcExists) throw new Error('relative srcpath does not exist') + return { + toCwd: srcpath, + toDst: path.relative(dstdir, srcpath) } +} - var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; +module.exports = { + symlinkPaths: u(symlinkPaths), + symlinkPathsSync +} - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - var ref = Object.prototype; - var hasOwnProperty = ref.hasOwnProperty; - var toString = ref.toString; +/***/ }), - // Checks if an object has a property. +/***/ 18254: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function has(obj, propName) { - return hasOwnProperty.call(obj, propName) +"use strict"; + + +const fs = __nccwpck_require__(61176) +const u = (__nccwpck_require__(9046).fromPromise) + +async function symlinkType (srcpath, type) { + if (type) return type + + let stats + try { + stats = await fs.lstat(srcpath) + } catch { + return 'file' } - var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" - ); }); + return (stats && stats.isDirectory()) ? 'dir' : 'file' +} - function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") +function symlinkTypeSync (srcpath, type) { + if (type) return type + + let stats + try { + stats = fs.lstatSync(srcpath) + } catch { + return 'file' } + return (stats && stats.isDirectory()) ? 'dir' : 'file' +} - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. +module.exports = { + symlinkType: u(symlinkType), + symlinkTypeSync +} - var Position = function Position(line, col) { - this.line = line; - this.column = col; - }; - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) - }; +/***/ }), - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start; - this.end = end; - if (p.sourceFile !== null) { this.source = p.sourceFile; } - }; +/***/ 72549: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. +"use strict"; - function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur) - } - } - } - // A second optional argument can be given to further configure - // the parser process. These options are recognized: +const u = (__nccwpck_require__(9046).fromPromise) +const path = __nccwpck_require__(71017) +const fs = __nccwpck_require__(61176) - var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must be - // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 - // (2019). This influences support for strict mode, the set of - // reserved words, and support for new syntax features. The default - // is 10. - ecmaVersion: 10, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // the position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // When enabled, await identifiers are allowed to appear at the top-level scope, - // but they are still not allowed in non-async functions. - allowAwaitOutsideFunction: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false - }; +const { mkdirs, mkdirsSync } = __nccwpck_require__(98605) - // Interpret and default an options object +const { symlinkPaths, symlinkPathsSync } = __nccwpck_require__(53727) +const { symlinkType, symlinkTypeSync } = __nccwpck_require__(18254) - function getOptions(opts) { - var options = {}; +const { pathExists } = __nccwpck_require__(43835) - for (var opt in defaultOptions) - { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } +const { areIdentical } = __nccwpck_require__(73901) - if (options.ecmaVersion >= 2015) - { options.ecmaVersion -= 2009; } +async function createSymlink (srcpath, dstpath, type) { + let stats + try { + stats = await fs.lstat(dstpath) + } catch { } - if (options.allowReserved == null) - { options.allowReserved = options.ecmaVersion < 5; } + if (stats && stats.isSymbolicLink()) { + const [srcStat, dstStat] = await Promise.all([ + fs.stat(srcpath), + fs.stat(dstpath) + ]) - if (isArray(options.onToken)) { - var tokens = options.onToken; - options.onToken = function (token) { return tokens.push(token); }; - } - if (isArray(options.onComment)) - { options.onComment = pushComment(options, options.onComment); } + if (areIdentical(srcStat, dstStat)) return + } - return options + const relative = await symlinkPaths(srcpath, dstpath) + srcpath = relative.toDst + const toType = await symlinkType(relative.toCwd, type) + const dir = path.dirname(dstpath) + + if (!(await pathExists(dir))) { + await mkdirs(dir) } - function pushComment(options, array) { - return function(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "Block" : "Line", - value: text, - start: start, - end: end - }; - if (options.locations) - { comment.loc = new SourceLocation(this, startLoc, endLoc); } - if (options.ranges) - { comment.range = [start, end]; } - array.push(comment); - } + return fs.symlink(srcpath, dstpath, toType) +} + +function createSymlinkSync (srcpath, dstpath, type) { + let stats + try { + stats = fs.lstatSync(dstpath) + } catch { } + if (stats && stats.isSymbolicLink()) { + const srcStat = fs.statSync(srcpath) + const dstStat = fs.statSync(dstpath) + if (areIdentical(srcStat, dstStat)) return } - // Each scope gets a bitset that may contain these flags - var - SCOPE_TOP = 1, - SCOPE_FUNCTION = 2, - SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, - SCOPE_ASYNC = 4, - SCOPE_GENERATOR = 8, - SCOPE_ARROW = 16, - SCOPE_SIMPLE_CATCH = 32, - SCOPE_SUPER = 64, - SCOPE_DIRECT_SUPER = 128; + const relative = symlinkPathsSync(srcpath, dstpath) + srcpath = relative.toDst + type = symlinkTypeSync(relative.toCwd, type) + const dir = path.dirname(dstpath) + const exists = fs.existsSync(dir) + if (exists) return fs.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir) + return fs.symlinkSync(srcpath, dstpath, type) +} - function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) +module.exports = { + createSymlink: u(createSymlink), + createSymlinkSync +} + + +/***/ }), + +/***/ 61176: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// This is adapted from https://github.com/normalize/mz +// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors +const u = (__nccwpck_require__(9046).fromCallback) +const fs = __nccwpck_require__(14178) + +const api = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'copyFile', + 'cp', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'glob', + 'lchmod', + 'lchown', + 'lutimes', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'opendir', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', + 'rmdir', + 'stat', + 'statfs', + 'symlink', + 'truncate', + 'unlink', + 'utimes', + 'writeFile' +].filter(key => { + // Some commands are not available on some systems. Ex: + // fs.cp was added in Node.js v16.7.0 + // fs.statfs was added in Node v19.6.0, v18.15.0 + // fs.glob was added in Node.js v22.0.0 + // fs.lchown is not available on at least some Linux + return typeof fs[key] === 'function' +}) + +// Export cloned fs: +Object.assign(exports, fs) + +// Universalify async methods: +api.forEach(method => { + exports[method] = u(fs[method]) +}) + +// We differ from mz/fs in that we still ship the old, broken, fs.exists() +// since we are a drop-in replacement for the native module +exports.exists = function (filename, callback) { + if (typeof callback === 'function') { + return fs.exists(filename, callback) } + return new Promise(resolve => { + return fs.exists(filename, resolve) + }) +} - // Used in checkLVal and declareName to determine the type of a binding - var - BIND_NONE = 0, // Not a binding - BIND_VAR = 1, // Var-style binding - BIND_LEXICAL = 2, // Let- or const-style binding - BIND_FUNCTION = 3, // Function declaration - BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding - BIND_OUTSIDE = 5; // Special case for function names as bound inside the function +// fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args - var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options); - this.sourceFile = options.sourceFile; - this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); - var reserved = ""; - if (options.allowReserved !== true) { - for (var v = options.ecmaVersion;; v--) - { if (reserved = reservedWords[v]) { break } } - if (options.sourceType === "module") { reserved += " await"; } - } - this.reservedWords = wordsRegexp(reserved); - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; - this.reservedWordsStrict = wordsRegexp(reservedStrict); - this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); - this.input = String(input); +exports.read = function (fd, buffer, offset, length, position, callback) { + if (typeof callback === 'function') { + return fs.read(fd, buffer, offset, length, position, callback) + } + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { + if (err) return reject(err) + resolve({ bytesRead, buffer }) + }) + }) +} - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false; +// Function signature can be +// fs.write(fd, buffer[, offset[, length[, position]]], callback) +// OR +// fs.write(fd, string[, position[, encoding]], callback) +// We need to handle both cases, so we use ...args +exports.write = function (fd, buffer, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.write(fd, buffer, ...args) + } - // Set up token state + return new Promise((resolve, reject) => { + fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { + if (err) return reject(err) + resolve({ bytesWritten, buffer }) + }) + }) +} - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos; - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; - } else { - this.pos = this.lineStart = 0; - this.curLine = 1; - } +// Function signature is +// s.readv(fd, buffers[, position], callback) +// We need to handle the optional arg, so we use ...args +exports.readv = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.readv(fd, buffers, ...args) + } - // Properties of the current token: - // Its type - this.type = types.eof; - // For tokens that include more information than their type, the value - this.value = null; - // Its start and end offset - this.start = this.end = this.pos; - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition(); + return new Promise((resolve, reject) => { + fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { + if (err) return reject(err) + resolve({ bytesRead, buffers }) + }) + }) +} - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; +// Function signature is +// s.writev(fd, buffers[, position], callback) +// We need to handle the optional arg, so we use ...args +exports.writev = function (fd, buffers, ...args) { + if (typeof args[args.length - 1] === 'function') { + return fs.writev(fd, buffers, ...args) + } - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext(); - this.exprAllowed = true; + return new Promise((resolve, reject) => { + fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { + if (err) return reject(err) + resolve({ bytesWritten, buffers }) + }) + }) +} - // Figure out if it's a module code. - this.inModule = options.sourceType === "module"; - this.strict = this.inModule || this.strictDirective(this.pos); +// fs.realpath.native sometimes not available if fs is monkey-patched +if (typeof fs.realpath.native === 'function') { + exports.realpath.native = u(fs.realpath.native) +} else { + process.emitWarning( + 'fs.realpath.native is not a function. Is fs being monkey-patched?', + 'Warning', 'fs-extra-WARN0003' + ) +} - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1; - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; - // Labels in scope. - this.labels = []; - // Thus-far undefined exports. - this.undefinedExports = {}; +/***/ }), - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") - { this.skipLineComment(2); } +/***/ 5630: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); +"use strict"; - // For RegExp validation - this.regexpState = null; - }; - var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; +module.exports = { + // Export promiseified graceful-fs: + ...__nccwpck_require__(61176), + // Export extra methods: + ...__nccwpck_require__(61335), + ...__nccwpck_require__(96970), + ...__nccwpck_require__(40055), + ...__nccwpck_require__(40213), + ...__nccwpck_require__(98605), + ...__nccwpck_require__(41497), + ...__nccwpck_require__(91832), + ...__nccwpck_require__(43835), + ...__nccwpck_require__(47357) +} - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) - }; - prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; - prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; - prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; - prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; - prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; - prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; +/***/ }), - // Switch to a getter for 7.0.0. - Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; +/***/ 40213: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; +"use strict"; - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls - }; - Parser.parse = function parse (input, options) { - return new this(options, input).parse() - }; +const u = (__nccwpck_require__(9046).fromPromise) +const jsonFile = __nccwpck_require__(18970) - Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() - }; +jsonFile.outputJson = u(__nccwpck_require__(60531)) +jsonFile.outputJsonSync = __nccwpck_require__(19421) +// aliases +jsonFile.outputJSON = jsonFile.outputJson +jsonFile.outputJSONSync = jsonFile.outputJsonSync +jsonFile.writeJSON = jsonFile.writeJson +jsonFile.writeJSONSync = jsonFile.writeJsonSync +jsonFile.readJSON = jsonFile.readJson +jsonFile.readJSONSync = jsonFile.readJsonSync - Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) - }; +module.exports = jsonFile - Object.defineProperties( Parser.prototype, prototypeAccessors ); - var pp = Parser.prototype; +/***/ }), - // ## Parser utilities +/***/ 18970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; - pp.strictDirective = function(start) { - for (;;) { - // Try to find string literal. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - var match = literal.exec(this.input.slice(start)); - if (!match) { return false } - if ((match[1] || match[2]) === "use strict") { - skipWhiteSpace.lastIndex = start + match[0].length; - var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; - var next = this.input.charAt(end); - return next === ";" || next === "}" || - (lineBreak.test(spaceAfter[0]) && - !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) - } - start += match[0].length; +"use strict"; - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - if (this.input[start] === ";") - { start++; } - } - }; - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. +const jsonFile = __nccwpck_require__(26160) - pp.eat = function(type) { - if (this.type === type) { - this.next(); - return true - } else { - return false - } - }; +module.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync +} - // Tests whether parsed token is a contextual keyword. - pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc - }; +/***/ }), - // Consumes contextual keyword if possible. +/***/ 19421: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true - }; +"use strict"; - // Asserts that following token is given contextual keyword. - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } - }; +const { stringify } = __nccwpck_require__(35902) +const { outputFileSync } = __nccwpck_require__(91832) - // Test whether a semicolon can be inserted at the current position. +function outputJsonSync (file, data, options) { + const str = stringify(data, options) - pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; + outputFileSync(file, str, options) +} - pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } - return true - } - }; +module.exports = outputJsonSync - // Consume a semicolon, or, failing that, see if we are allowed to - // pretend that there is a semicolon at this position. - pp.semicolon = function() { - if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } - }; +/***/ }), - pp.afterTrailingComma = function(tokType, notNext) { - if (this.type === tokType) { - if (this.options.onTrailingComma) - { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } - if (!notNext) - { this.next(); } - return true - } - }; +/***/ 60531: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Expect a token of a given type. If found, consume it, otherwise, - // raise an unexpected token error. +"use strict"; - pp.expect = function(type) { - this.eat(type) || this.unexpected(); - }; - // Raise an unexpected token error. +const { stringify } = __nccwpck_require__(35902) +const { outputFile } = __nccwpck_require__(91832) - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); - }; +async function outputJson (file, data, options = {}) { + const str = stringify(data, options) - function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; - } + await outputFile(file, str, options) +} - pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { - if (!refDestructuringErrors) { return } - if (refDestructuringErrors.trailingComma > -1) - { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } - var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; - if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } - }; +module.exports = outputJson - pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - if (!refDestructuringErrors) { return false } - var shorthandAssign = refDestructuringErrors.shorthandAssign; - var doubleProto = refDestructuringErrors.doubleProto; - if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } - if (shorthandAssign >= 0) - { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } - if (doubleProto >= 0) - { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } - }; - pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } - if (this.awaitPos) - { this.raise(this.awaitPos, "Await expression cannot be a default value"); } - }; +/***/ }), - pp.isSimpleAssignTarget = function(expr) { - if (expr.type === "ParenthesizedExpression") - { return this.isSimpleAssignTarget(expr.expression) } - return expr.type === "Identifier" || expr.type === "MemberExpression" - }; +/***/ 98605: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var pp$1 = Parser.prototype; +"use strict"; - // ### Statement parsing +const u = (__nccwpck_require__(9046).fromPromise) +const { makeDir: _makeDir, makeDirSync } = __nccwpck_require__(52751) +const makeDir = u(_makeDir) - // Parse a program. Initializes the parser, reads any number of - // statements, and wraps them in a Program node. Optionally takes a - // `program` argument. If present, the statements will be appended - // to its body instead of creating a new node. +module.exports = { + mkdirs: makeDir, + mkdirsSync: makeDirSync, + // alias + mkdirp: makeDir, + mkdirpSync: makeDirSync, + ensureDir: makeDir, + ensureDirSync: makeDirSync +} - pp$1.parseTopLevel = function(node) { - var exports = {}; - if (!node.body) { node.body = []; } - while (this.type !== types.eof) { - var stmt = this.parseStatement(null, true, exports); - node.body.push(stmt); - } - if (this.inModule) - { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) - { - var name = list[i]; - this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); - } } - this.adaptDirectivePrologue(node.body); - this.next(); - node.sourceType = this.options.sourceType; - return this.finishNode(node, "Program") - }; +/***/ }), - var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; +/***/ 52751: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$1.isLet = function(context) { - if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - // For ambiguous cases, determine if a LexicalDeclaration (or only a - // Statement) is allowed here. If context is not empty then only a Statement - // is allowed. However, `let [` is an explicit negative lookahead for - // ExpressionStatement, so special-case it first. - if (nextCh === 91) { return true } // '[' - if (context) { return false } +"use strict"; - if (nextCh === 123) { return true } // '{' - if (isIdentifierStart(nextCh, true)) { - var pos = next + 1; - while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } - var ident = this.input.slice(next, pos); - if (!keywordRelationalOperator.test(ident)) { return true } - } - return false - }; +const fs = __nccwpck_require__(61176) +const { checkPath } = __nccwpck_require__(59907) - // check 'async [no LineTerminator here] function' - // - 'async /*foo*/ function' is OK. - // - 'async /*\n*/ function' is invalid. - pp$1.isAsyncFunction = function() { - if (this.options.ecmaVersion < 8 || !this.isContextual("async")) - { return false } +const getMode = options => { + const defaults = { mode: 0o777 } + if (typeof options === 'number') return options + return ({ ...defaults, ...options }).mode +} - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length; - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) - }; +module.exports.makeDir = async (dir, options) => { + checkPath(dir) - // Parse a single statement. - // - // If expecting a statement and finding a slash operator, parse a - // regular expression literal. This is to handle cases like - // `if (foo) /blah/.exec(foo)`, where looking at the previous token - // does not help. + return fs.mkdir(dir, { + mode: getMode(options), + recursive: true + }) +} - pp$1.parseStatement = function(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; +module.exports.makeDirSync = (dir, options) => { + checkPath(dir) - if (this.isLet(context)) { - starttype = types._var; - kind = "let"; - } + return fs.mkdirSync(dir, { + mode: getMode(options), + recursive: true + }) +} - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - switch (starttype) { - case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case types._debugger: return this.parseDebuggerStatement(node) - case types._do: return this.parseDoStatement(node) - case types._for: return this.parseForStatement(node) - case types._function: - // Function as sole body of either an if statement or a labeled statement - // works, but not when it is part of a labeled statement that is the sole - // body of an if statement. - if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } - return this.parseFunctionStatement(node, false, !context) - case types._class: - if (context) { this.unexpected(); } - return this.parseClass(node, true) - case types._if: return this.parseIfStatement(node) - case types._return: return this.parseReturnStatement(node) - case types._switch: return this.parseSwitchStatement(node) - case types._throw: return this.parseThrowStatement(node) - case types._try: return this.parseTryStatement(node) - case types._const: case types._var: - kind = kind || this.value; - if (context && kind !== "var") { this.unexpected(); } - return this.parseVarStatement(node, kind) - case types._while: return this.parseWhileStatement(node) - case types._with: return this.parseWithStatement(node) - case types.braceL: return this.parseBlock(true, node) - case types.semi: return this.parseEmptyStatement(node) - case types._export: - case types._import: - if (this.options.ecmaVersion > 10 && starttype === types._import) { - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - if (nextCh === 40 || nextCh === 46) // '(' or '.' - { return this.parseExpressionStatement(node, this.parseExpression()) } - } +/***/ }), - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } - if (!this.inModule) - { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } - } - return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) +/***/ 59907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction()) { - if (context) { this.unexpected(); } - this.next(); - return this.parseFunctionStatement(node, true, !context) - } +"use strict"; +// Adapted from https://github.com/sindresorhus/make-dir +// Copyright (c) Sindre Sorhus (sindresorhus.com) +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - var maybeName = this.value, expr = this.parseExpression(); - if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) - { return this.parseLabeledStatement(node, maybeName, expr, context) } - else { return this.parseExpressionStatement(node, expr) } - } - }; +const path = __nccwpck_require__(71017) - pp$1.parseBreakContinueStatement = function(node, keyword) { - var isBreak = keyword === "break"; - this.next(); - if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } - else if (this.type !== types.name) { this.unexpected(); } - else { - node.label = this.parseIdent(); - this.semicolon(); - } +// https://github.com/nodejs/node/issues/8987 +// https://github.com/libuv/libuv/pull/1088 +module.exports.checkPath = function checkPath (pth) { + if (process.platform === 'win32') { + const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) - // Verify that there is an actual destination to break or - // continue to. - var i = 0; - for (; i < this.labels.length; ++i) { - var lab = this.labels[i]; - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } - if (node.label && isBreak) { break } - } + if (pathHasInvalidWinCharacters) { + const error = new Error(`Path contains invalid characters: ${pth}`) + error.code = 'EINVAL' + throw error } - if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") - }; + } +} - pp$1.parseDebuggerStatement = function(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement") - }; - pp$1.parseDoStatement = function(node) { - this.next(); - this.labels.push(loopLabel); - node.body = this.parseStatement("do"); - this.labels.pop(); - this.expect(types._while); - node.test = this.parseParenExpression(); - if (this.options.ecmaVersion >= 6) - { this.eat(types.semi); } - else - { this.semicolon(); } - return this.finishNode(node, "DoWhileStatement") - }; +/***/ }), - // Disambiguating between a `for` and a `for`/`in` or `for`/`of` - // loop is non-trivial. Basically, we have to parse the init `var` - // statement or expression, disallowing the `in` operator (see - // the second parameter to `parseExpression`), and then check - // whether the next token is `in` or `of`. When there is no init - // part (semicolon immediately after the opening parenthesis), it - // is a regular `for` loop. +/***/ 41497: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$1.parseForStatement = function(node) { - this.next(); - var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; - this.labels.push(loopLabel); - this.enterScope(0); - this.expect(types.parenL); - if (this.type === types.semi) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, null) - } - var isLet = this.isLet(); - if (this.type === types._var || this.type === types._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value; - this.next(); - this.parseVar(init$1, true, kind); - this.finishNode(init$1, "VariableDeclaration"); - if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - return this.parseForIn(node, init$1) - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init$1) - } - var refDestructuringErrors = new DestructuringErrors; - var init = this.parseExpression(true, refDestructuringErrors); - if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - this.toAssignable(init, false, refDestructuringErrors); - this.checkLVal(init); - return this.parseForIn(node, init) - } else { - this.checkExpressionErrors(refDestructuringErrors, true); - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init) - }; +"use strict"; - pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) - }; - pp$1.parseIfStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement("if"); - node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; - return this.finishNode(node, "IfStatement") - }; +const u = (__nccwpck_require__(9046).fromPromise) +module.exports = { + move: u(__nccwpck_require__(72231)), + moveSync: __nccwpck_require__(42047) +} - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - { this.raise(this.start, "'return' outside of function"); } - this.next(); - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. +/***/ }), - if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } - else { node.argument = this.parseExpression(); this.semicolon(); } - return this.finishNode(node, "ReturnStatement") - }; +/***/ 42047: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$1.parseSwitchStatement = function(node) { - this.next(); - node.discriminant = this.parseParenExpression(); - node.cases = []; - this.expect(types.braceL); - this.labels.push(switchLabel); - this.enterScope(0); +"use strict"; - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - var cur; - for (var sawDefault = false; this.type !== types.braceR;) { - if (this.type === types._case || this.type === types._default) { - var isCase = this.type === types._case; - if (cur) { this.finishNode(cur, "SwitchCase"); } - node.cases.push(cur = this.startNode()); - cur.consequent = []; - this.next(); - if (isCase) { - cur.test = this.parseExpression(); - } else { - if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } - sawDefault = true; - cur.test = null; - } - this.expect(types.colon); - } else { - if (!cur) { this.unexpected(); } - cur.consequent.push(this.parseStatement(null)); - } - } - this.exitScope(); - if (cur) { this.finishNode(cur, "SwitchCase"); } - this.next(); // Closing brace - this.labels.pop(); - return this.finishNode(node, "SwitchStatement") - }; +const fs = __nccwpck_require__(14178) +const path = __nccwpck_require__(71017) +const copySync = (__nccwpck_require__(61335).copySync) +const removeSync = (__nccwpck_require__(47357).removeSync) +const mkdirpSync = (__nccwpck_require__(98605).mkdirpSync) +const stat = __nccwpck_require__(73901) - pp$1.parseThrowStatement = function(node) { - this.next(); - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - { this.raise(this.lastTokEnd, "Illegal newline after throw"); } - node.argument = this.parseExpression(); - this.semicolon(); - return this.finishNode(node, "ThrowStatement") - }; +function moveSync (src, dest, opts) { + opts = opts || {} + const overwrite = opts.overwrite || opts.clobber || false - // Reused empty array added for node fields that are always empty. + const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) + stat.checkParentPathsSync(src, srcStat, dest, 'move') + if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) + return doRename(src, dest, overwrite, isChangingCase) +} - var empty = []; +function isParentRoot (dest) { + const parent = path.dirname(dest) + const parsedPath = path.parse(parent) + return parsedPath.root === parent +} - pp$1.parseTryStatement = function(node) { - this.next(); - node.block = this.parseBlock(); - node.handler = null; - if (this.type === types._catch) { - var clause = this.startNode(); - this.next(); - if (this.eat(types.parenL)) { - clause.param = this.parseBindingAtom(); - var simple = clause.param.type === "Identifier"; - this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); - this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); - this.expect(types.parenR); - } else { - if (this.options.ecmaVersion < 10) { this.unexpected(); } - clause.param = null; - this.enterScope(0); - } - clause.body = this.parseBlock(false); - this.exitScope(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; - if (!node.handler && !node.finalizer) - { this.raise(node.start, "Missing catch or finally clause"); } - return this.finishNode(node, "TryStatement") - }; +function doRename (src, dest, overwrite, isChangingCase) { + if (isChangingCase) return rename(src, dest, overwrite) + if (overwrite) { + removeSync(dest) + return rename(src, dest, overwrite) + } + if (fs.existsSync(dest)) throw new Error('dest already exists.') + return rename(src, dest, overwrite) +} - pp$1.parseVarStatement = function(node, kind) { - this.next(); - this.parseVar(node, false, kind); - this.semicolon(); - return this.finishNode(node, "VariableDeclaration") - }; +function rename (src, dest, overwrite) { + try { + fs.renameSync(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') throw err + return moveAcrossDevice(src, dest, overwrite) + } +} - pp$1.parseWhileStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - this.labels.push(loopLabel); - node.body = this.parseStatement("while"); - this.labels.pop(); - return this.finishNode(node, "WhileStatement") - }; +function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true, + preserveTimestamps: true + } + copySync(src, dest, opts) + return removeSync(src) +} - pp$1.parseWithStatement = function(node) { - if (this.strict) { this.raise(this.start, "'with' in strict mode"); } - this.next(); - node.object = this.parseParenExpression(); - node.body = this.parseStatement("with"); - return this.finishNode(node, "WithStatement") - }; +module.exports = moveSync - pp$1.parseEmptyStatement = function(node) { - this.next(); - return this.finishNode(node, "EmptyStatement") - }; - pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { - for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) - { - var label = list[i$1]; +/***/ }), - if (label.name === maybeName) - { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); - } } - var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; - for (var i = this.labels.length - 1; i >= 0; i--) { - var label$1 = this.labels[i]; - if (label$1.statementStart === node.start) { - // Update information about previous labels on this node - label$1.statementStart = this.start; - label$1.kind = kind; - } else { break } - } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); - node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); - this.labels.pop(); - node.label = expr; - return this.finishNode(node, "LabeledStatement") - }; +/***/ 72231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr; - this.semicolon(); - return this.finishNode(node, "ExpressionStatement") - }; +"use strict"; - // Parse a semicolon-enclosed block of statements, handling `"use - // strict"` declarations when `allowStrict` is true (used for - // function bodies). - pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { - if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; - if ( node === void 0 ) node = this.startNode(); +const fs = __nccwpck_require__(61176) +const path = __nccwpck_require__(71017) +const { copy } = __nccwpck_require__(61335) +const { remove } = __nccwpck_require__(47357) +const { mkdirp } = __nccwpck_require__(98605) +const { pathExists } = __nccwpck_require__(43835) +const stat = __nccwpck_require__(73901) - node.body = []; - this.expect(types.braceL); - if (createNewLexicalScope) { this.enterScope(0); } - while (this.type !== types.braceR) { - var stmt = this.parseStatement(null); - node.body.push(stmt); - } - if (exitStrict) { this.strict = false; } - this.next(); - if (createNewLexicalScope) { this.exitScope(); } - return this.finishNode(node, "BlockStatement") - }; +async function move (src, dest, opts = {}) { + const overwrite = opts.overwrite || opts.clobber || false - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. + const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts) - pp$1.parseFor = function(node, init) { - node.init = init; - this.expect(types.semi); - node.test = this.type === types.semi ? null : this.parseExpression(); - this.expect(types.semi); - node.update = this.type === types.parenR ? null : this.parseExpression(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, "ForStatement") - }; + await stat.checkParentPaths(src, srcStat, dest, 'move') - // Parse a `for`/`in` and `for`/`of` loop, which are almost - // same from parser's perspective. + // If the parent of dest is not root, make sure it exists before proceeding + const destParent = path.dirname(dest) + const parsedParentPath = path.parse(destParent) + if (parsedParentPath.root !== destParent) { + await mkdirp(destParent) + } - pp$1.parseForIn = function(node, init) { - var isForIn = this.type === types._in; - this.next(); + return doRename(src, dest, overwrite, isChangingCase) +} - if ( - init.type === "VariableDeclaration" && - init.declarations[0].init != null && - ( - !isForIn || - this.options.ecmaVersion < 8 || - this.strict || - init.kind !== "var" || - init.declarations[0].id.type !== "Identifier" - ) - ) { - this.raise( - init.start, - ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") - ); - } else if (init.type === "AssignmentPattern") { - this.raise(init.start, "Invalid left-hand side in for-loop"); +async function doRename (src, dest, overwrite, isChangingCase) { + if (!isChangingCase) { + if (overwrite) { + await remove(dest) + } else if (await pathExists(dest)) { + throw new Error('dest already exists.') } - node.left = init; - node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") - }; - - // Parse a list of variable declarations. + } - pp$1.parseVar = function(node, isFor, kind) { - node.declarations = []; - node.kind = kind; - for (;;) { - var decl = this.startNode(); - this.parseVarId(decl, kind); - if (this.eat(types.eq)) { - decl.init = this.parseMaybeAssign(isFor); - } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { - this.unexpected(); - } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { - this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); - } else { - decl.init = null; - } - node.declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(types.comma)) { break } + try { + // Try w/ rename first, and try copy + remove if EXDEV + await fs.rename(src, dest) + } catch (err) { + if (err.code !== 'EXDEV') { + throw err } - return node - }; + await moveAcrossDevice(src, dest, overwrite) + } +} - pp$1.parseVarId = function(decl, kind) { - decl.id = this.parseBindingAtom(); - this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); - }; +async function moveAcrossDevice (src, dest, overwrite) { + const opts = { + overwrite, + errorOnExist: true, + preserveTimestamps: true + } - var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + await copy(src, dest, opts) + return remove(src) +} - // Parse a function declaration or literal (depending on the - // `statement & FUNC_STATEMENT`). +module.exports = move - // Remove `allowExpressionBody` for 7.0.0, as it is only called with false - pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { - this.initFunction(node); - if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { - if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) - { this.unexpected(); } - node.generator = this.eat(types.star); - } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - if (statement & FUNC_STATEMENT) { - node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); - if (node.id && !(statement & FUNC_HANGING_STATEMENT)) - // If it is a regular function declaration in sloppy mode, then it is - // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding - // mode depends on properties of the current scope (see - // treatFunctionsAsVar). - { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } - } +/***/ }), - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(node.async, node.generator)); +/***/ 91832: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!(statement & FUNC_STATEMENT)) - { node.id = this.type === types.name ? this.parseIdent() : null; } +"use strict"; - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") - }; +const u = (__nccwpck_require__(9046).fromPromise) +const fs = __nccwpck_require__(61176) +const path = __nccwpck_require__(71017) +const mkdir = __nccwpck_require__(98605) +const pathExists = (__nccwpck_require__(43835).pathExists) - pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - }; +async function outputFile (file, data, encoding = 'utf-8') { + const dir = path.dirname(file) - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). + if (!(await pathExists(dir))) { + await mkdir.mkdirs(dir) + } - pp$1.parseClass = function(node, isStatement) { - this.next(); + return fs.writeFile(file, data, encoding) +} - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; +function outputFileSync (file, ...args) { + const dir = path.dirname(file) + if (!fs.existsSync(dir)) { + mkdir.mkdirsSync(dir) + } - this.parseClassId(node, isStatement); - this.parseClassSuper(node); - var classBody = this.startNode(); - var hadConstructor = false; - classBody.body = []; - this.expect(types.braceL); - while (this.type !== types.braceR) { - var element = this.parseClassElement(node.superClass !== null); - if (element) { - classBody.body.push(element); - if (element.type === "MethodDefinition" && element.kind === "constructor") { - if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } - hadConstructor = true; - } - } - } - this.strict = oldStrict; - this.next(); - node.body = this.finishNode(classBody, "ClassBody"); - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") - }; + fs.writeFileSync(file, ...args) +} - pp$1.parseClassElement = function(constructorAllowsSuper) { - var this$1 = this; +module.exports = { + outputFile: u(outputFile), + outputFileSync +} - if (this.eat(types.semi)) { return null } - var method = this.startNode(); - var tryContextual = function (k, noLineBreak) { - if ( noLineBreak === void 0 ) noLineBreak = false; +/***/ }), - var start = this$1.start, startLoc = this$1.startLoc; - if (!this$1.eatContextual(k)) { return false } - if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } - if (method.key) { this$1.unexpected(); } - method.computed = false; - method.key = this$1.startNodeAt(start, startLoc); - method.key.name = k; - this$1.finishNode(method.key, "Identifier"); - return false - }; +/***/ 43835: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - method.kind = "method"; - method.static = tryContextual("static"); - var isGenerator = this.eat(types.star); - var isAsync = false; - if (!isGenerator) { - if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - } else if (tryContextual("get")) { - method.kind = "get"; - } else if (tryContextual("set")) { - method.kind = "set"; - } - } - if (!method.key) { this.parsePropertyName(method); } - var key = method.key; - var allowsDirectSuper = false; - if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } - if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } - if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } - method.kind = "constructor"; - allowsDirectSuper = constructorAllowsSuper; - } else if (method.static && key.type === "Identifier" && key.name === "prototype") { - this.raise(key.start, "Classes may not have a static property named prototype"); - } - this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); - if (method.kind === "get" && method.value.params.length !== 0) - { this.raiseRecoverable(method.value.start, "getter should have no params"); } - if (method.kind === "set" && method.value.params.length !== 1) - { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } - if (method.kind === "set" && method.value.params[0].type === "RestElement") - { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } - return method - }; +"use strict"; - pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - return this.finishNode(method, "MethodDefinition") - }; +const u = (__nccwpck_require__(9046).fromPromise) +const fs = __nccwpck_require__(61176) - pp$1.parseClassId = function(node, isStatement) { - if (this.type === types.name) { - node.id = this.parseIdent(); - if (isStatement) - { this.checkLVal(node.id, BIND_LEXICAL, false); } - } else { - if (isStatement === true) - { this.unexpected(); } - node.id = null; - } - }; +function pathExists (path) { + return fs.access(path).then(() => true).catch(() => false) +} - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; - }; +module.exports = { + pathExists: u(pathExists), + pathExistsSync: fs.existsSync +} - // Parses module export declaration. - pp$1.parseExport = function(node, exports) { - this.next(); - // export * from '...' - if (this.eat(types.star)) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node.exported = this.parseIdent(true); - this.checkExport(exports, node.exported.name, this.lastTokStart); - } else { - node.exported = null; - } - } - this.expectContextual("from"); - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(types._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - if (this.type === types._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - if (isAsync) { this.next(); } - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === types._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - if (node.declaration.type === "VariableDeclaration") - { this.checkVariableExport(exports, node.declaration.declarations); } - else - { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } - node.specifiers = []; - node.source = null; - } else { // export { x, y as z } [from '...'] - node.declaration = null; - node.specifiers = this.parseExportSpecifiers(exports); - if (this.eatContextual("from")) { - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; +/***/ }), - this.checkUnreserved(spec.local); - // check if export is defined - this.checkLocalExport(spec.local); - } +/***/ 47357: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") - }; +"use strict"; - pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has(exports, name)) - { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } - exports[name] = true; - }; - pp$1.checkPatternExport = function(exports, pat) { - var type = pat.type; - if (type === "Identifier") - { this.checkExport(exports, pat.name, pat.start); } - else if (type === "ObjectPattern") - { for (var i = 0, list = pat.properties; i < list.length; i += 1) - { - var prop = list[i]; +const fs = __nccwpck_require__(14178) +const u = (__nccwpck_require__(9046).fromCallback) - this.checkPatternExport(exports, prop); - } } - else if (type === "ArrayPattern") - { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { - var elt = list$1[i$1]; +function remove (path, callback) { + fs.rm(path, { recursive: true, force: true }, callback) +} - if (elt) { this.checkPatternExport(exports, elt); } - } } - else if (type === "Property") - { this.checkPatternExport(exports, pat.value); } - else if (type === "AssignmentPattern") - { this.checkPatternExport(exports, pat.left); } - else if (type === "RestElement") - { this.checkPatternExport(exports, pat.argument); } - else if (type === "ParenthesizedExpression") - { this.checkPatternExport(exports, pat.expression); } - }; +function removeSync (path) { + fs.rmSync(path, { recursive: true, force: true }) +} - pp$1.checkVariableExport = function(exports, decls) { - if (!exports) { return } - for (var i = 0, list = decls; i < list.length; i += 1) - { - var decl = list[i]; +module.exports = { + remove: u(remove), + removeSync +} - this.checkPatternExport(exports, decl.id); - } - }; - pp$1.shouldParseExportStatement = function() { - return this.type.keyword === "var" || - this.type.keyword === "const" || - this.type.keyword === "class" || - this.type.keyword === "function" || - this.isLet() || - this.isAsyncFunction() - }; +/***/ }), - // Parses a comma-separated list of module exports. +/***/ 73901: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$1.parseExportSpecifiers = function(exports) { - var nodes = [], first = true; - // export { x, y as z } [from '...'] - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } +"use strict"; - var node = this.startNode(); - node.local = this.parseIdent(true); - node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; - this.checkExport(exports, node.exported.name, node.exported.start); - nodes.push(this.finishNode(node, "ExportSpecifier")); - } - return nodes - }; - // Parses import declaration. +const fs = __nccwpck_require__(61176) +const path = __nccwpck_require__(71017) +const u = (__nccwpck_require__(9046).fromPromise) - pp$1.parseImport = function(node) { - this.next(); - // import '...' - if (this.type === types.string) { - node.specifiers = empty; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); - } - this.semicolon(); - return this.finishNode(node, "ImportDeclaration") - }; +function getStats (src, dest, opts) { + const statFunc = opts.dereference + ? (file) => fs.stat(file, { bigint: true }) + : (file) => fs.lstat(file, { bigint: true }) + return Promise.all([ + statFunc(src), + statFunc(dest).catch(err => { + if (err.code === 'ENOENT') return null + throw err + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) +} - // Parses a comma-separated list of module imports. +function getStatsSync (src, dest, opts) { + let destStat + const statFunc = opts.dereference + ? (file) => fs.statSync(file, { bigint: true }) + : (file) => fs.lstatSync(file, { bigint: true }) + const srcStat = statFunc(src) + try { + destStat = statFunc(dest) + } catch (err) { + if (err.code === 'ENOENT') return { srcStat, destStat: null } + throw err + } + return { srcStat, destStat } +} - pp$1.parseImportSpecifiers = function() { - var nodes = [], first = true; - if (this.type === types.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode(); - node.local = this.parseIdent(); - this.checkLVal(node.local, BIND_LEXICAL); - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); - if (!this.eat(types.comma)) { return nodes } +async function checkPaths (src, dest, funcName, opts) { + const { srcStat, destStat } = await getStats(src, dest, opts) + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') } - if (this.type === types.star) { - var node$1 = this.startNode(); - this.next(); - this.expectContextual("as"); - node$1.local = this.parseIdent(); - this.checkLVal(node$1.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); - return nodes + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) + } + } - var node$2 = this.startNode(); - node$2.imported = this.parseIdent(true); - if (this.eatContextual("as")) { - node$2.local = this.parseIdent(); - } else { - this.checkUnreserved(node$2.imported); - node$2.local = node$2.imported; + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + + return { srcStat, destStat } +} + +function checkPathsSync (src, dest, funcName, opts) { + const { srcStat, destStat } = getStatsSync(src, dest, opts) + + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } } - this.checkLVal(node$2.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$2, "ImportSpecifier")); + throw new Error('Source and destination must not be the same.') } - return nodes - }; - - // Set `ExpressionStatement#directive` property for directive prologues. - pp$1.adaptDirectivePrologue = function(statements) { - for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { - statements[i].directive = statements[i].expression.raw.slice(1, -1); + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } - }; - pp$1.isDirectiveCandidate = function(statement) { - return ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - typeof statement.expression.value === "string" && - // Reject parenthesized strings. - (this.input[statement.start] === "\"" || this.input[statement.start] === "'") - ) - }; + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) + } + } - var pp$2 = Parser.prototype; + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + return { srcStat, destStat } +} - // Convert existing expression atom to assignable pattern - // if possible. +// recursively check if dest parent is a subdirectory of src. +// It works for all file types including symlinks since it +// checks the src and dest inodes. It starts from the deepest +// parent and stops once it reaches the src parent or the root path. +async function checkParentPaths (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return - pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } - break + let destStat + try { + destStat = await fs.stat(destParent, { bigint: true }) + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } - case "ObjectPattern": - case "ArrayPattern": - case "RestElement": - break + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } - case "ObjectExpression": - node.type = "ObjectPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; + return checkParentPaths(src, srcStat, destParent, funcName) +} - this.toAssignable(prop, isBinding); - // Early error: - // AssignmentRestProperty[Yield, Await] : - // `...` DestructuringAssignmentTarget[Yield, Await] - // - // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. - if ( - prop.type === "RestElement" && - (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") - ) { - this.raise(prop.argument.start, "Unexpected token"); - } - } - break +function checkParentPathsSync (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return + let destStat + try { + destStat = fs.statSync(destParent, { bigint: true }) + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + return checkParentPathsSync(src, srcStat, destParent, funcName) +} - case "Property": - // AssignmentProperty has type === "Property" - if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } - this.toAssignable(node.value, isBinding); - break +function areIdentical (srcStat, destStat) { + return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev +} - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break +// return true if dest is a subdir of src, otherwise false. +// It only checks the path strings. +function isSrcSubdir (src, dest) { + const srcArr = path.resolve(src).split(path.sep).filter(i => i) + const destArr = path.resolve(dest).split(path.sep).filter(i => i) + return srcArr.every((cur, i) => destArr[i] === cur) +} - case "SpreadElement": - node.type = "RestElement"; - this.toAssignable(node.argument, isBinding); - if (node.argument.type === "AssignmentPattern") - { this.raise(node.argument.start, "Rest elements cannot have a default value"); } - break +function errMsg (src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` +} - case "AssignmentExpression": - if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isBinding); - // falls through to AssignmentPattern +module.exports = { + // checkPaths + checkPaths: u(checkPaths), + checkPathsSync, + // checkParent + checkParentPaths: u(checkParentPaths), + checkParentPathsSync, + // Misc + isSrcSubdir, + areIdentical +} - case "AssignmentPattern": - break - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break +/***/ }), - case "ChainExpression": - this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); - break +/***/ 52548: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case "MemberExpression": - if (!isBinding) { break } +"use strict"; - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node - }; - // Convert list of expression atoms to binding list. +const fs = __nccwpck_require__(61176) +const u = (__nccwpck_require__(9046).fromPromise) - pp$2.toAssignableList = function(exprList, isBinding) { - var end = exprList.length; - for (var i = 0; i < end; i++) { - var elt = exprList[i]; - if (elt) { this.toAssignable(elt, isBinding); } - } - if (end) { - var last = exprList[end - 1]; - if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - { this.unexpected(last.argument.start); } +async function utimesMillis (path, atime, mtime) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + const fd = await fs.open(path, 'r+') + + let closeErr = null + + try { + await fs.futimes(fd, atime, mtime) + } finally { + try { + await fs.close(fd) + } catch (e) { + closeErr = e } - return exprList - }; + } - // Parses spread element. + if (closeErr) { + throw closeErr + } +} - pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeAssign(false, refDestructuringErrors); - return this.finishNode(node, "SpreadElement") - }; +function utimesMillisSync (path, atime, mtime) { + const fd = fs.openSync(path, 'r+') + fs.futimesSync(fd, atime, mtime) + return fs.closeSync(fd) +} - pp$2.parseRestBinding = function() { - var node = this.startNode(); - this.next(); +module.exports = { + utimesMillis: u(utimesMillis), + utimesMillisSync +} - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } - node.argument = this.parseBindingAtom(); +/***/ }), - return this.finishNode(node, "RestElement") - }; +/***/ 25086: +/***/ ((module) => { - // Parses lvalue (assignable) atom. +"use strict"; - pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion >= 6) { - switch (this.type) { - case types.bracketL: - var node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(types.bracketR, true, true); - return this.finishNode(node, "ArrayPattern") - case types.braceL: - return this.parseObj(true) - } +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} + + +/***/ }), + +/***/ 14178: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(35027) +var legacy = __nccwpck_require__(73836) +var clone = __nccwpck_require__(25086) + +var util = __nccwpck_require__(73837) + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue } - return this.parseIdent() - }; + }) +} - pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { - var elts = [], first = true; - while (!this.eat(close)) { - if (first) { first = false; } - else { this.expect(types.comma); } - if (allowEmpty && this.type === types.comma) { - elts.push(null); - } else if (allowTrailingComma && this.afterTrailingComma(close)) { - break - } else if (this.type === types.ellipsis) { - var rest = this.parseRestBinding(); - this.parseBindingListItem(rest); - elts.push(rest); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - this.expect(close); - break - } else { - var elem = this.parseMaybeDefault(this.start, this.startLoc); - this.parseBindingListItem(elem); - elts.push(elem); - } +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) } - return elts - }; - pp$2.parseBindingListItem = function(param) { - return param - }; + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - // Parses assignment pattern around given atom if possible. + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } - pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom(); - if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.right = this.parseMaybeAssign(); - return this.finishNode(node, "AssignmentPattern") - }; + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) - // Verify that a node is an lval — something that can be assigned - // to. - // bindingType can be either: - // 'var' indicating that the lval creates a 'var' binding - // 'let' indicating that the lval creates a lexical ('let' or 'const') binding - // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} - pp$2.checkLVal = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} - switch (expr.type) { - case "Identifier": - if (bindingType === BIND_LEXICAL && expr.name === "let") - { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } - if (checkClashes) { - if (has(checkClashes, expr.name)) - { this.raiseRecoverable(expr.start, "Argument name clash"); } - checkClashes[expr.name] = true; - } - if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } - break +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - case "ChainExpression": - this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); - break +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - case "MemberExpression": - if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) - { - var prop = list[i]; + return go$readFile(path, options, cb) - this.checkLVal(prop, bindingType, checkClashes); + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } - break + } - case "Property": - // AssignmentProperty has type === "Property" - this.checkLVal(expr.value, bindingType, checkClashes); - break + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - case "ArrayPattern": - for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { - var elem = list$1[i$1]; + return go$writeFile(path, data, options, cb) - if (elem) { this.checkLVal(elem, bindingType, checkClashes); } - } - break + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - case "AssignmentPattern": - this.checkLVal(expr.left, bindingType, checkClashes); - break + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - case "RestElement": - this.checkLVal(expr.argument, bindingType, checkClashes); - break + return go$appendFile(path, data, options, cb) - case "ParenthesizedExpression": - this.checkLVal(expr.expression, bindingType, checkClashes); - break + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - default: - this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 } - }; + return go$copyFile(src, dest, flags, cb) - // A recursive descent parser operates by defining functions for all + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - var pp$3 = Parser.prototype; + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - // Check if property name clashes with already added. - // Object/class getters and setters are not allowed to clash — - // either with each other or with an init property — and in - // strict mode, init properties are also not allowed to be repeated. + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } - pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { - if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") - { return } - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - { return } - var key = prop.key; - var name; - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) { - if (refDestructuringErrors) { - if (refDestructuringErrors.doubleProto < 0) - { refDestructuringErrors.doubleProto = key.start; } - // Backwards-compat kludge. Can be removed in version 6.0 - } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) } - propHash.proto = true; } - return } - name = "$" + name; - var other = propHash[name]; - if (other) { - var redefinition; - if (kind === "init") { - redefinition = this.strict && other.init || other.get || other.set; + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) } else { - redefinition = other.init || other[kind]; + that.fd = fd + that.emit('open', fd) + that.read() } - if (redefinition) - { this.raiseRecoverable(key.start, "Redefinition of property"); } - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - }; - } - other[kind] = true; - }; + }) + } - // ### Expression parsing + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - // These nest, from the most general expression type at the top to - // 'atomic', nondivisible expression types at the bottom. Most of - // the functions will simply let the function(s) below them parse, - // and, *if* the syntactic construct they handle is present, wrap - // the AST node that the inner parser gave them in another node. + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - // Parse a full expression. The optional arguments are used to - // forbid the `in` operator (in for loops initalization expressions) - // and provide reference for storing '=' operator inside shorthand - // property assignment in contexts where both object expression - // and object pattern might appear (so it's possible to raise - // delayed syntax error at correct position). + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } - pp$3.parseExpression = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); - if (this.type === types.comma) { - var node = this.startNodeAt(startPos, startLoc); - node.expressions = [expr]; - while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); } - return this.finishNode(node, "SequenceExpression") - } - return expr - }; + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } - // Parse an assignment expression. This includes applications of - // operators like `+=`. + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { - if (this.isContextual("yield")) { - if (this.inGenerator) { return this.parseYield(noIn) } - // The tokenizer will assume an expression is allowed after - // `yield`, but this isn't that kind of yield - else { this.exprAllowed = false; } + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } + } - var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; - if (refDestructuringErrors) { - oldParenAssign = refDestructuringErrors.parenthesizedAssign; - oldTrailingComma = refDestructuringErrors.trailingComma; - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; - } else { - refDestructuringErrors = new DestructuringErrors; - ownDestructuringErrors = true; + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime } + } + // call retry to make sure we're actively processing the queue + retry() +} - var startPos = this.start, startLoc = this.startLoc; - if (this.type === types.parenL || this.type === types.name) - { this.potentialArrowAt = this.start; } - var left = this.parseMaybeConditional(noIn, refDestructuringErrors); - if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } - if (this.type.isAssign) { - var node = this.startNodeAt(startPos, startLoc); - node.operator = this.value; - node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; - if (!ownDestructuringErrors) { - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; - } - if (refDestructuringErrors.shorthandAssign >= node.left.start) - { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly - this.checkLVal(left); - this.next(); - node.right = this.parseMaybeAssign(noIn); - return this.finishNode(node, "AssignmentExpression") +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) } else { - if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) } - if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } - if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } - return left - }; + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} + + +/***/ }), + +/***/ 73836: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream) + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } - // Parse a ternary conditional (`?:`) operator. + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprOps(noIn, refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - if (this.eat(types.question)) { - var node = this.startNodeAt(startPos, startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssign(); - this.expect(types.colon); - node.alternate = this.parseMaybeAssign(noIn); - return this.finishNode(node, "ConditionalExpression") - } - return expr - }; + Stream.call(this); - // Start the precedence parser. + var self = this; - pp$3.parseExprOps = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeUnary(refDestructuringErrors, false); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) - }; + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - // Parse binary operators with the operator precedence parsing - // algorithm. `left` is the left-hand side of the operator. - // `minPrec` provides context that allows the function to stop and - // defer further parser to one of its callers when it encounters an - // operator that has a lower precedence than the set it is parsing. + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { - var prec = this.type.binop; - if (prec != null && (!noIn || this.type !== types._in)) { - if (prec > minPrec) { - var logical = this.type === types.logicalOR || this.type === types.logicalAND; - var coalesce = this.type === types.coalesce; - if (coalesce) { - // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. - // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. - prec = types.logicalAND.binop; - } - var op = this.value; - this.next(); - var startPos = this.start, startLoc = this.startLoc; - var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); - if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { - this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); - } - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) - } + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - return left - }; - pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.operator = op; - node.right = right; - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") - }; + if (this.encoding) this.setEncoding(this.encoding); - // Parse unary operators, both prefix and postfix. + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } - pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { - var startPos = this.start, startLoc = this.startLoc, expr; - if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { - expr = this.parseAwait(); - sawUnary = true; - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === types.incDec; - node.operator = this.value; - node.prefix = true; - this.next(); - node.argument = this.parseMaybeUnary(null, true); - this.checkExpressionErrors(refDestructuringErrors, true); - if (update) { this.checkLVal(node.argument); } - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } - else { sawUnary = true; } - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); - } else { - expr = this.parseExprSubscripts(refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.operator = this.value; - node$1.prefix = false; - node$1.argument = expr; - this.checkLVal(expr); - this.next(); - expr = this.finishNode(node$1, "UpdateExpression"); + if (this.start > this.end) { + throw new Error('start must be <= end'); } + + this.pos = this.start; } - if (!sawUnary && this.eat(types.starstar)) - { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } - else - { return expr } - }; + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } - // Parse call, dot, and `[]`-subscript expressions. + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } - pp$3.parseExprSubscripts = function(refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprAtom(refDestructuringErrors); - if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") - { return expr } - var result = this.parseSubscripts(expr, startPos, startLoc); - if (refDestructuringErrors && result.type === "MemberExpression") { - if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } - if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } - } - return result - }; + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && - this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && - this.potentialArrowAt === base.start; - var optionalChained = false; + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - while (true) { - var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); + Stream.call(this); - if (element.optional) { optionalChained = true; } - if (element === base || element.type === "ArrowFunctionExpression") { - if (optionalChained) { - var chainNode = this.startNodeAt(startPos, startLoc); - chainNode.expression = element; - element = this.finishNode(chainNode, "ChainExpression"); - } - return element - } + this.path = path; + this.fd = null; + this.writable = true; - base = element; - } - }; + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { - var optionalSupported = this.options.ecmaVersion >= 11; - var optional = optionalSupported && this.eat(types.questionDot); - if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + options = options || {}; - var computed = this.eat(types.bracketL); - if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { - var node = this.startNodeAt(startPos, startLoc); - node.object = base; - node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); - node.computed = !!computed; - if (computed) { this.expect(types.bracketR); } - if (optionalSupported) { - node.optional = optional; - } - base = this.finishNode(node, "MemberExpression"); - } else if (!noCalls && this.eat(types.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); - if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - if (this.awaitIdentPos > 0) - { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) - } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.callee = base; - node$1.arguments = exprList; - if (optionalSupported) { - node$1.optional = optional; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - base = this.finishNode(node$1, "CallExpression"); - } else if (this.type === types.backQuote) { - if (optional || optionalChained) { - this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + if (this.start < 0) { + throw new Error('start must be >= zero'); } - var node$2 = this.startNodeAt(startPos, startLoc); - node$2.tag = base; - node$2.quasi = this.parseTemplate({isTagged: true}); - base = this.finishNode(node$2, "TaggedTemplateExpression"); - } - return base - }; - // Parse an atomic expression — either a single token that is an - // expression, an expression started by a keyword like `function` or - // `new`, or an expression wrapped in punctuation like `()`, `[]`, - // or `{}`. + this.pos = this.start; + } - pp$3.parseExprAtom = function(refDestructuringErrors) { - // If a division operator appears in an expression position, the - // tokenizer got confused, and we force it to read a regexp instead. - if (this.type === types.slash) { this.readRegexp(); } + this.busy = false; + this._queue = []; - var node, canBeArrow = this.potentialArrowAt === this.start; - switch (this.type) { - case types._super: - if (!this.allowSuper) - { this.raise(this.start, "'super' keyword outside a method"); } - node = this.startNode(); - this.next(); - if (this.type === types.parenL && !this.allowDirectSuper) - { this.raise(node.start, "super() call outside constructor of a subclass"); } - // The `super` keyword can appear at below: - // SuperProperty: - // super [ Expression ] - // super . IdentifierName - // SuperCall: - // super ( Arguments ) - if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) - { this.unexpected(); } - return this.finishNode(node, "Super") + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} - case types._this: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression") - case types.name: - var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; - var id = this.parseIdent(false); - if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) - { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(types.arrow)) - { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { - id = this.parseIdent(false); - if (this.canInsertSemicolon() || !this.eat(types.arrow)) - { this.unexpected(); } - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id +/***/ }), - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node +/***/ 35027: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case types.num: case types.string: - return this.parseLiteral(this.value) +var constants = __nccwpck_require__(22057) - case types._null: case types._true: case types._false: - node = this.startNode(); - node.value = this.type === types._null ? null : this.type === types._true; - node.raw = this.type.keyword; - this.next(); - return this.finishNode(node, "Literal") +var origCwd = process.cwd +var cwd = null - case types.parenL: - var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); - if (refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) - { refDestructuringErrors.parenthesizedAssign = start; } - if (refDestructuringErrors.parenthesizedBind < 0) - { refDestructuringErrors.parenthesizedBind = start; } - } - return expr +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - case types.braceL: - return this.parseObj(false, refDestructuringErrors) +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) +module.exports = patch - case types._class: - return this.parseClass(this.startNode(), false) +function patch (fs) { + // (re-)implement some things that are known busted or missing. - case types._new: - return this.parseNew() + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } - case types.backQuote: - return this.parseTemplate() + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - case types._import: - if (this.options.ecmaVersion >= 11) { - return this.parseExprImport() - } else { - return this.unexpected() - } + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - default: - this.unexpected(); - } - }; + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - pp$3.parseExprImport = function() { - var node = this.startNode(); + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - // Consume `import` as an identifier for `import.meta`. - // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } - var meta = this.parseIdent(true); + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - switch (this.type) { - case types.parenL: - return this.parseDynamicImport(node) - case types.dot: - node.meta = meta; - return this.parseImportMeta(node) - default: - this.unexpected(); - } - }; + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - pp$3.parseDynamicImport = function(node) { - this.next(); // skip `(` + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - // Parse node.source. - node.source = this.parseMaybeAssign(); + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - // Verify ending. - if (!this.eat(types.parenR)) { - var errorPos = this.start; - if (this.eat(types.comma) && this.eat(types.parenR)) { - this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); - } else { - this.unexpected(errorPos); - } + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - return this.finishNode(node, "ImportExpression") - }; - - pp$3.parseImportMeta = function(node) { - this.next(); // skip `.` + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } - if (node.property.name !== "meta") - { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } - if (this.options.sourceType !== "module") - { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } - return this.finishNode(node, "MetaProperty") - }; + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) - pp$3.parseLiteral = function(value) { - var node = this.startNode(); - node.value = value; - node.raw = this.input.slice(this.start, this.end); - if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } - this.next(); - return this.finishNode(node, "Literal") - }; + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - pp$3.parseParenExpression = function() { - this.expect(types.parenL); - var val = this.parseExpression(); - this.expect(types.parenR); - return val - }; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; - if (this.options.ecmaVersion >= 6) { - this.next(); + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - var innerStartPos = this.start, innerStartLoc = this.startLoc; - var exprList = [], first = true, lastIsComma = false; - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; - this.yieldPos = 0; - this.awaitPos = 0; - // Do not save awaitIdentPos to allow checking awaits nested in parameters - while (this.type !== types.parenR) { - first ? first = false : this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { - lastIsComma = true; - break - } else if (this.type === types.ellipsis) { - spreadStart = this.start; - exprList.push(this.parseParenItem(this.parseRestBinding())); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - break + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} } else { - exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + fs.closeSync(fd) } } - var innerEndPos = this.start, innerEndLoc = this.startLoc; - this.expect(types.parenR); + return ret + } + } - if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - return this.parseParenArrowList(startPos, startLoc, exprList) + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) } - if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } - if (spreadStart) { this.unexpected(spreadStart); } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc); - val.expressions = exprList; - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); - } else { - val = exprList[0]; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret } - } else { - val = this.parseParenExpression(); + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } + } - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc); - par.expression = val; - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - }; + } - pp$3.parseParenItem = function(item) { - return item - }; + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) - }; - // New's precedence is slightly tricky. It must allow its argument to - // be a `[]` or dot subscript expression, but not a call — at least, - // not without wrapping it in parentheses. Thus, it uses the noCalls - // argument to parseSubscripts to prevent it from consuming the - // argument list. + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - var empty$1 = []; + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - pp$3.parseNew = function() { - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } - var node = this.startNode(); - var meta = this.parseIdent(true); - if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { - node.meta = meta; - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - if (node.property.name !== "target") - { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } - if (!this.inNonArrowFunction()) - { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } - return this.finishNode(node, "MetaProperty") + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) } - var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); - if (isImport && node.callee.type === "ImportExpression") { - this.raise(startPos, "Cannot use new with import()"); + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; } - if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } - else { node.arguments = empty$1; } - return this.finishNode(node, "NewExpression") - }; + } - // Parse template expression. + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - pp$3.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; + if (er.code === "ENOSYS") + return true - var elem = this.startNode(); - if (this.type === types.invalidTemplate) { - if (!isTagged) { - this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); - } - elem.value = { - raw: this.value, - cooked: null - }; - } else { - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), - cooked: this.value - }; + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true } - this.next(); - elem.tail = this.type === types.backQuote; - return this.finishNode(elem, "TemplateElement") - }; - pp$3.parseTemplate = function(ref) { - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + return false + } +} - var node = this.startNode(); - this.next(); - node.expressions = []; - var curElt = this.parseTemplateElement({isTagged: isTagged}); - node.quasis = [curElt]; - while (!curElt.tail) { - if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } - this.expect(types.dollarBraceL); - node.expressions.push(this.parseExpression()); - this.expect(types.braceR); - node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); - } - this.next(); - return this.finishNode(node, "TemplateLiteral") - }; - pp$3.isAsyncProp = function(prop) { - return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && - (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && - !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; +/***/ }), - // Parse an object literal or binding pattern. +/***/ 19320: +/***/ ((module) => { - pp$3.parseObj = function(isPattern, refDestructuringErrors) { - var node = this.startNode(), first = true, propHash = {}; - node.properties = []; - this.next(); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } +"use strict"; - var prop = this.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") - }; + var args = slice.call(arguments, 1); - pp$3.parseProperty = function(isPattern, refDestructuringErrors) { - var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; - if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { - if (isPattern) { - prop.argument = this.parseIdent(false); - if (this.type === types.comma) { - this.raise(this.start, "Comma is not permitted after the rest element"); - } - return this.finishNode(prop, "RestElement") - } - // To disallow parenthesized identifier via `this.toAssignable()`. - if (this.type === types.parenL && refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0) { - refDestructuringErrors.parenthesizedAssign = this.start; - } - if (refDestructuringErrors.parenthesizedBind < 0) { - refDestructuringErrors.parenthesizedBind = this.start; + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); } - } - // Parse argument. - prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); - // To disallow trailing comma via `this.toAssignable()`. - if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { - refDestructuringErrors.trailingComma = this.start; - } - // Finish - return this.finishNode(prop, "SpreadElement") - } - if (this.options.ecmaVersion >= 6) { - prop.method = false; - prop.shorthand = false; - if (isPattern || refDestructuringErrors) { - startPos = this.start; - startLoc = this.startLoc; - } - if (!isPattern) - { isGenerator = this.eat(types.star); } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); } - var containsEsc = this.containsEsc; - this.parsePropertyName(prop); - if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - this.parsePropertyName(prop, refDestructuringErrors); - } else { - isAsync = false; + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; } - this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); - return this.finishNode(prop, "Property") - }; - pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { - if ((isGenerator || isAsync) && this.type === types.colon) - { this.unexpected(); } + return bound; +}; - if (this.eat(types.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); - prop.kind = "init"; - } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { - if (isPattern) { this.unexpected(); } - prop.kind = "init"; - prop.method = true; - prop.value = this.parseMethod(isGenerator, isAsync); - } else if (!isPattern && !containsEsc && - this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { - if (isGenerator || isAsync) { this.unexpected(); } - prop.kind = prop.key.name; - this.parsePropertyName(prop); - prop.value = this.parseMethod(false); - var paramCount = prop.kind === "get" ? 0 : 1; - if (prop.value.params.length !== paramCount) { - var start = prop.value.start; - if (prop.kind === "get") - { this.raiseRecoverable(start, "getter should have no params"); } - else - { this.raiseRecoverable(start, "setter should have exactly one param"); } - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (isGenerator || isAsync) { this.unexpected(); } - this.checkUnreserved(prop.key); - if (prop.key.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = startPos; } - prop.kind = "init"; - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); - } else if (this.type === types.eq && refDestructuringErrors) { - if (refDestructuringErrors.shorthandAssign < 0) - { refDestructuringErrors.shorthandAssign = this.start; } - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); - } else { - prop.value = prop.key; - } - prop.shorthand = true; - } else { this.unexpected(); } - }; - pp$3.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(types.bracketL)) { - prop.computed = true; - prop.key = this.parseMaybeAssign(); - this.expect(types.bracketR); - return prop.key - } else { - prop.computed = false; - } - } - return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") - }; +/***/ }), + +/***/ 88334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var implementation = __nccwpck_require__(19320); + +module.exports = Function.prototype.bind || implementation; + - // Initialize empty function node. +/***/ }), - pp$3.initFunction = function(node) { - node.id = null; - if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } - if (this.options.ecmaVersion >= 8) { node.async = false; } - }; +/***/ 74538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Parse object or class method. +"use strict"; - pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } +var undefined; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - this.parseFunctionBody(node, false, true); +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "FunctionExpression") - }; +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} - // Parse arrow function expression with given parameters. +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; - pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; +var hasSymbols = __nccwpck_require__(40587)(); - this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); - this.initFunction(node); - if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; +var needsEval = {}; - node.params = this.toAssignableList(params, true); - this.parseFunctionBody(node, true, false); +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "ArrowFunctionExpression") - }; +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; - // Parse function body and check parameters. +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } - pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; + INTRINSICS[name] = value; - if (isExpression) { - node.body = this.parseMaybeAssign(); - node.expression = true; - this.checkParams(node, false); - } else { - var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); - if (!oldStrict || nonSimple) { - useStrict = this.strictDirective(this.end); - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - if (useStrict && nonSimple) - { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } - } - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldLabels = this.labels; - this.labels = []; - if (useStrict) { this.strict = true; } + return value; +}; - // Add the params to varDeclaredNames to ensure that an error is thrown - // if a let/const declaration in the function clashes with one of the params. - this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); - // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' - if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } - node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); - node.expression = false; - this.adaptDirectivePrologue(node.body.body); - this.labels = oldLabels; - } - this.exitScope(); - }; +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; - pp$3.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; +var bind = __nccwpck_require__(88334); +var hasOwn = __nccwpck_require__(76339); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); - if (param.type !== "Identifier") { return false - } } - return true - }; +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } - pp$3.checkParams = function(node, allowDuplicates) { - var nameHash = {}; - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } - this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); - } - }; + return { + alias: alias, + name: intrinsicName, + value: value + }; + } - // Parses a comma-separated list of expressions, and returns them as - // an array. `close` is the token type that ends the list, and - // `allowEmpty` can be turned on to allow subsequent commas with - // nothing in between them to be parsed as `null` (which is needed - // for array literals). + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; - pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var elts = [], first = true; - while (!this.eat(close)) { - if (!first) { - this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(close)) { break } - } else { first = false; } +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } - var elt = (void 0); - if (allowEmpty && this.type === types.comma) - { elt = null; } - else if (this.type === types.ellipsis) { - elt = this.parseSpread(refDestructuringErrors); - if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) - { refDestructuringErrors.trailingComma = this.start; } - } else { - elt = this.parseMaybeAssign(false, refDestructuringErrors); - } - elts.push(elt); - } - return elts - }; + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - pp$3.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; - if (this.inGenerator && name === "yield") - { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } - if (this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } - if (this.keywords.test(name)) - { this.raise(start, ("Unexpected keyword '" + name + "'")); } - if (this.options.ecmaVersion < 6 && - this.input.slice(start, end).indexOf("\\") !== -1) { return } - var re = this.strict ? this.reservedWordsStrict : this.reservedWords; - if (re.test(name)) { - if (!this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } - this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); - } - }; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } - // Parse the next token as an identifier. If `liberal` is true (used - // when parsing properties), it will also convert keywords into - // identifiers. + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } - pp$3.parseIdent = function(liberal, isBinding) { - var node = this.startNode(); - if (this.type === types.name) { - node.name = this.value; - } else if (this.type.keyword) { - node.name = this.type.keyword; + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; - // To fix https://github.com/acornjs/acorn/issues/575 - // `class` and `function` keywords push new context into this.context. - // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. - // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword - if ((node.name === "class" || node.name === "function") && - (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { - this.context.pop(); - } - } else { - this.unexpected(); - } - this.next(!!liberal); - this.finishNode(node, "Identifier"); - if (!liberal) { - this.checkUnreserved(node); - if (node.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = node.start; } - } - return node - }; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; - // Parses yield expression inside generator. + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } - pp$3.parseYield = function(noIn) { - if (!this.yieldPos) { this.yieldPos = this.start; } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; - var node = this.startNode(); - this.next(); - if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { - node.delegate = false; - node.argument = null; - } else { - node.delegate = this.eat(types.star); - node.argument = this.parseMaybeAssign(noIn); - } - return this.finishNode(node, "YieldExpression") - }; - pp$3.parseAwait = function() { - if (!this.awaitPos) { this.awaitPos = this.start; } +/***/ }), - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeUnary(null, false); - return this.finishNode(node, "AwaitExpression") - }; +/***/ 54655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var pp$4 = Parser.prototype; +"use strict"; - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - pp$4.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos); - message += " (" + loc.line + ":" + loc.column + ")"; - var err = new SyntaxError(message); - err.pos = pos; err.loc = loc; err.raisedAt = this.pos; - throw err - }; +var isGlob = __nccwpck_require__(34466); +var pathPosixDirname = (__nccwpck_require__(71017).posix.dirname); +var isWin32 = (__nccwpck_require__(22037).platform)() === 'win32'; - pp$4.raiseRecoverable = pp$4.raise; +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; - pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - }; +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); - var pp$5 = Parser.prototype; + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } - var Scope = function Scope(flags) { - this.flags = flags; - // A list of var-declared names in the current lexical scope - this.var = []; - // A list of lexically-declared names in the current lexical scope - this.lexical = []; - // A list of lexically-declared FunctionDeclaration names in the current lexical scope - this.functions = []; - }; + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } - // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + // preserves full path in case of trailing path separator + str += 'a'; - pp$5.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); - }; + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); - pp$5.exitScope = function() { - this.scopeStack.pop(); - }; + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; - // The spec says: - // > At the top level of a function, or script, function declarations are - // > treated like var declarations rather than like lexical declarations. - pp$5.treatFunctionsAsVarInScope = function(scope) { - return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) - }; - pp$5.declareName = function(name, bindingType, pos) { - var redeclared = false; - if (bindingType === BIND_LEXICAL) { - var scope = this.currentScope(); - redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; - scope.lexical.push(name); - if (this.inModule && (scope.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - } else if (bindingType === BIND_SIMPLE_CATCH) { - var scope$1 = this.currentScope(); - scope$1.lexical.push(name); - } else if (bindingType === BIND_FUNCTION) { - var scope$2 = this.currentScope(); - if (this.treatFunctionsAsVar) - { redeclared = scope$2.lexical.indexOf(name) > -1; } - else - { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } - scope$2.functions.push(name); - } else { - for (var i = this.scopeStack.length - 1; i >= 0; --i) { - var scope$3 = this.scopeStack[i]; - if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || - !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { - redeclared = true; - break - } - scope$3.var.push(name); - if (this.inModule && (scope$3.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - if (scope$3.flags & SCOPE_VAR) { break } - } - } - if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } - }; +/***/ }), - pp$5.checkLocalExport = function(id) { - // scope.functions must be empty as Module code is always strict. - if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && - this.scopeStack[0].var.indexOf(id.name) === -1) { - this.undefinedExports[id.name] = id; - } - }; +/***/ 31621: +/***/ ((module) => { - pp$5.currentScope = function() { - return this.scopeStack[this.scopeStack.length - 1] - }; +"use strict"; - pp$5.currentVarScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR) { return scope } - } - }; - // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. - pp$5.currentThisScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } - } - }; +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; - var Node = function Node(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - if (parser.options.locations) - { this.loc = new SourceLocation(parser, loc); } - if (parser.options.directSourceFile) - { this.sourceFile = parser.options.directSourceFile; } - if (parser.options.ranges) - { this.range = [pos, 0]; } - }; - // Start an AST node, attaching a start offset. +/***/ }), - var pp$6 = Parser.prototype; +/***/ 40587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$6.startNode = function() { - return new Node(this, this.start, this.startLoc) - }; +"use strict"; - pp$6.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - }; - // Finish an AST node, adding `type` and `end` properties. +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __nccwpck_require__(57747); - function finishNodeAt(node, type, pos, loc) { - node.type = type; - node.end = pos; - if (this.options.locations) - { node.loc.end = loc; } - if (this.options.ranges) - { node.range[1] = pos; } - return node - } +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } - pp$6.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - }; + return hasSymbolSham(); +}; - // Finish node at given position - pp$6.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - }; +/***/ }), - // The algorithm used to determine whether a regexp can appear at a +/***/ 57747: +/***/ ((module) => { - var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; - }; +"use strict"; - var types$1 = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", false), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), - f_stat: new TokContext("function", false), - f_expr: new TokContext("function", true), - f_expr_gen: new TokContext("function", true, false, null, true), - f_gen: new TokContext("function", false, false, null, true) - }; - var pp$7 = Parser.prototype; +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } - pp$7.initialContext = function() { - return [types$1.b_stat] - }; + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } - pp$7.braceIsBlock = function(prevType) { - var parent = this.curContext(); - if (parent === types$1.f_expr || parent === types$1.f_stat) - { return true } - if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) - { return !parent.isExpr } + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - // The check for `tt.name && exprAllowed` detects whether we are - // after a `yield` or `of` construct. See the `updateContext` for - // `tt.name`. - if (prevType === types._return || prevType === types.name && this.exprAllowed) - { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } - if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) - { return true } - if (prevType === types.braceL) - { return parent === types$1.b_stat } - if (prevType === types._var || prevType === types._const || prevType === types.name) - { return false } - return !this.exprAllowed - }; + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } - pp$7.inGeneratorContext = function() { - for (var i = this.context.length - 1; i >= 1; i--) { - var context = this.context[i]; - if (context.token === "function") - { return context.generator } - } - return false - }; + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - pp$7.updateContext = function(prevType) { - var update, type = this.type; - if (type.keyword && prevType === types.dot) - { this.exprAllowed = false; } - else if (update = type.updateContext) - { update.call(this, prevType); } - else - { this.exprAllowed = type.beforeExpr; } - }; + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - // Token-specific context update code + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - types.parenR.updateContext = types.braceR.updateContext = function() { - if (this.context.length === 1) { - this.exprAllowed = true; - return - } - var out = this.context.pop(); - if (out === types$1.b_stat && this.curContext().token === "function") { - out = this.context.pop(); - } - this.exprAllowed = !out.isExpr; - }; + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } - types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; - }; + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; - }; + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } - types.parenL.updateContext = function(prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); - this.exprAllowed = true; - }; + return true; +}; - types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - }; - types._function.updateContext = types._class.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && - !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && - !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) - { this.context.push(types$1.f_expr); } - else - { this.context.push(types$1.f_stat); } - this.exprAllowed = false; - }; +/***/ }), - types.backQuote.updateContext = function() { - if (this.curContext() === types$1.q_tmpl) - { this.context.pop(); } - else - { this.context.push(types$1.q_tmpl); } - this.exprAllowed = false; - }; +/***/ 99038: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - types.star.updateContext = function(prevType) { - if (prevType === types._function) { - var index = this.context.length - 1; - if (this.context[index] === types$1.f_expr) - { this.context[index] = types$1.f_expr_gen; } - else - { this.context[index] = types$1.f_gen; } - } - this.exprAllowed = true; - }; +"use strict"; - types.name.updateContext = function(prevType) { - var allowed = false; - if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { - if (this.value === "of" && !this.exprAllowed || - this.value === "yield" && this.inGeneratorContext()) - { allowed = true; } - } - this.exprAllowed = allowed; - }; - // This file contains Unicode properties extracted from the ECMAScript - // specification. The lists are extracted like so: - // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) +var hasSymbols = __nccwpck_require__(57747); - // #table-binary-unicode-properties - var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; - var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; - var ecma11BinaryProperties = ecma10BinaryProperties; - var unicodeBinaryProperties = { - 9: ecma9BinaryProperties, - 10: ecma10BinaryProperties, - 11: ecma11BinaryProperties - }; +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; - // #table-unicode-general-category-values - var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; - // #table-unicode-script-values - var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; - var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; - var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; - var unicodeScriptValues = { - 9: ecma9ScriptValues, - 10: ecma10ScriptValues, - 11: ecma11ScriptValues - }; +/***/ }), - var data = {}; - function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) - } - }; - d.nonBinary.Script_Extensions = d.nonBinary.Script; +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - d.nonBinary.gc = d.nonBinary.General_Category; - d.nonBinary.sc = d.nonBinary.Script; - d.nonBinary.scx = d.nonBinary.Script_Extensions; - } - buildUnicodeData(9); - buildUnicodeData(10); - buildUnicodeData(11); +"use strict"; - var pp$8 = Parser.prototype; - var RegExpValidationState = function RegExpValidationState(parser) { - this.parser = parser; - this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); - this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion]; - this.source = ""; - this.flags = ""; - this.start = 0; - this.switchU = false; - this.switchN = false; - this.pos = 0; - this.lastIntValue = 0; - this.lastStringValue = ""; - this.lastAssertionIsQuantifiable = false; - this.numCapturingParens = 0; - this.maxBackReference = 0; - this.groupNames = []; - this.backReferenceNames = []; - }; +var bind = __nccwpck_require__(88334); - RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { - var unicode = flags.indexOf("u") !== -1; - this.start = start | 0; - this.source = pattern + ""; - this.flags = flags; - this.switchU = unicode && this.parser.options.ecmaVersion >= 6; - this.switchN = unicode && this.parser.options.ecmaVersion >= 9; - }; +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); - }; - // If u flag is given, this returns the code point at the index (it combines a surrogate pair). - // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). - RegExpValidationState.prototype.at = function at (i, forceU) { - if ( forceU === void 0 ) forceU = false; +/***/ }), - var s = this.source; - var l = s.length; - if (i >= l) { - return -1 +/***/ 23764: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - var c = s.charCodeAt(i); - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return c + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpProxyAgent = void 0; +const net = __importStar(__nccwpck_require__(41808)); +const tls = __importStar(__nccwpck_require__(24404)); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const events_1 = __nccwpck_require__(82361); +const agent_base_1 = __nccwpck_require__(70694); +const url_1 = __nccwpck_require__(57310); +const debug = (0, debug_1.default)('http-proxy-agent'); +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + */ +class HttpProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? 'https:' : 'http:'; + const hostname = req.getHeader('host') || 'localhost'; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + // Change the `http.ClientRequest` instance's "path" field + // to the absolute path of the URL that will be requested. + req.path = String(url); + // Inject the `Proxy-Authorization` header if necessary. + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } } - var next = s.charCodeAt(i + 1); - return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c - }; - - RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return l + async connect(req, opts) { + req._header = null; + if (!req.path.includes('://')) { + this.setRequestProps(req, opts); + } + // At this point, the http ClientRequest's internal `_header` field + // might have already been set. If this is the case then we'll need + // to re-generate the string since we just changed the `req.path`. + let first; + let endOfHeaders; + debug('Regenerating stored HTTP header string for request'); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug('Patching connection write() output buffer with updated header'); + first = req.outputData[0].data; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.outputData[0].data = + req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.outputData[0].data); + } + // Create a socket connection to the proxy server. + let socket; + if (this.proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = tls.connect(this.connectOpts); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + // Wait for the socket's `connect` event, so that this `callback()` + // function throws instead of the `http` request machinery. This is + // important for i.e. `PacProxyAgent` which determines a failed proxy + // connection via the `callback()` function throwing. + await (0, events_1.once)(socket, 'connect'); + return socket; } - var c = s.charCodeAt(i), next; - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || - (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { - return i + 1 +} +HttpProxyAgent.protocols = ['http', 'https']; +exports.HttpProxyAgent = HttpProxyAgent; +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } - return i + 2 - }; - - RegExpValidationState.prototype.current = function current (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.pos, forceU) - }; - - RegExpValidationState.prototype.lookahead = function lookahead (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.nextIndex(this.pos, forceU), forceU) - }; - - RegExpValidationState.prototype.advance = function advance (forceU) { - if ( forceU === void 0 ) forceU = false; - - this.pos = this.nextIndex(this.pos, forceU); - }; - - RegExpValidationState.prototype.eat = function eat (ch, forceU) { - if ( forceU === void 0 ) forceU = false; + return ret; +} +//# sourceMappingURL=index.js.map - if (this.current(forceU) === ch) { - this.advance(forceU); - return true - } - return false - }; +/***/ }), - function codePointToString(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) - } +/***/ 77219: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /** - * Validate the flags part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpFlags = function(state) { - var validFlags = state.validFlags; - var flags = state.flags; +"use strict"; - for (var i = 0; i < flags.length; i++) { - var flag = flags.charAt(i); - if (validFlags.indexOf(flag) === -1) { - this.raise(state.start, "Invalid regular expression flag"); - } - if (flags.indexOf(flag, i + 1) > -1) { - this.raise(state.start, "Duplicate regular expression flag"); - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - }; - - /** - * Validate the pattern part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpPattern = function(state) { - this.regexp_pattern(state); - - // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of - // parsing contains a |GroupName|, reparse with the goal symbol - // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* - // exception if _P_ did not conform to the grammar, if any elements of _P_ - // were not matched by the parse, or if any Early Error conditions exist. - if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { - state.switchN = true; - this.regexp_pattern(state); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpsProxyAgent = void 0; +const net = __importStar(__nccwpck_require__(41808)); +const tls = __importStar(__nccwpck_require__(24404)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +const debug_1 = __importDefault(__nccwpck_require__(6785)); +const agent_base_1 = __nccwpck_require__(70694); +const url_1 = __nccwpck_require__(57310); +const parse_proxy_response_1 = __nccwpck_require__(595); +const debug = (0, debug_1.default)('https-proxy-agent'); +const setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && + options.host && + !net.isIP(options.host)) { + return { + ...options, + servername: options.host, + }; } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern - pp$8.regexp_pattern = function(state) { - state.pos = 0; - state.lastIntValue = 0; - state.lastStringValue = ""; - state.lastAssertionIsQuantifiable = false; - state.numCapturingParens = 0; - state.maxBackReference = 0; - state.groupNames.length = 0; - state.backReferenceNames.length = 0; - - this.regexp_disjunction(state); - - if (state.pos !== state.source.length) { - // Make the same messages as V8. - if (state.eat(0x29 /* ) */)) { - state.raise("Unmatched ')'"); - } - if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { - state.raise("Lone quantifier brackets"); - } + return options; +}; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; } - if (state.maxBackReference > state.numCapturingParens) { - state.raise("Invalid escape"); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'), + socket, + }); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + (0, assert_1.default)(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; } - for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { - var name = list[i]; - - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } +} +HttpsProxyAgent.protocols = ['http', 'https']; +exports.HttpsProxyAgent = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } - }; + return ret; +} +//# sourceMappingURL=index.js.map - // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction - pp$8.regexp_disjunction = function(state) { - this.regexp_alternative(state); - while (state.eat(0x7C /* | */)) { - this.regexp_alternative(state); - } +/***/ }), - // Make the same message as V8. - if (this.regexp_eatQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - if (state.eat(0x7B /* { */)) { - state.raise("Lone quantifier brackets"); - } - }; +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative - pp$8.regexp_alternative = function(state) { - while (state.pos < state.source.length && this.regexp_eatTerm(state)) - { } - }; +"use strict"; - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term - pp$8.regexp_eatTerm = function(state) { - if (this.regexp_eatAssertion(state)) { - // Handle `QuantifiableAssertion Quantifier` alternative. - // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion - // is a QuantifiableAssertion. - if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { - // Make the same message as V8. - if (state.switchU) { - state.raise("Invalid quantifier"); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseProxyResponse = void 0; +const debug_1 = __importDefault(__nccwpck_require__(6785)); +const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); } - } - return true - } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } +/***/ }), - return false - }; +/***/ 90814: +/***/ ((module, exports, __nccwpck_require__) => { - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion - pp$8.regexp_eatAssertion = function(state) { - var start = state.pos; - state.lastAssertionIsQuantifiable = false; +/* eslint-env browser */ - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } +/** + * This is the web browser implementation of `debug()`. + */ - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - // Lookahead / Lookbehind - if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { - var lookbehind = false; - if (this.options.ecmaVersion >= 9) { - lookbehind = state.eat(0x3C /* < */); - } - if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { - this.regexp_disjunction(state); - if (!state.eat(0x29 /* ) */)) { - state.raise("Unterminated group"); - } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); - state.pos = start; - return false - }; +/** + * Colors. + */ - // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier - pp$8.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false - }; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix - pp$8.regexp_eatQuantifierPrefix = function(state, noError) { - return ( - state.eat(0x2A /* * */) || - state.eat(0x2B /* + */) || - state.eat(0x3F /* ? */) || - this.regexp_eatBracedQuantifier(state, noError) - ) - }; - pp$8.regexp_eatBracedQuantifier = function(state, noError) { - var start = state.pos; - if (state.eat(0x7B /* { */)) { - var min = 0, max = -1; - if (this.regexp_eatDecimalDigits(state)) { - min = state.lastIntValue; - if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { - max = state.lastIntValue; - } - if (state.eat(0x7D /* } */)) { - // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term - if (max !== -1 && max < min && !noError) { - state.raise("numbers out of order in {} quantifier"); - } - return true - } - } - if (state.switchU && !noError) { - state.raise("Incomplete quantifier"); - } - state.pos = start; - } - return false - }; +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom - pp$8.regexp_eatAtom = function(state) { - return ( - this.regexp_eatPatternCharacters(state) || - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) - ) - }; - pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { - var start = state.pos; - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatAtomEscape(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatUncapturingGroup = function(state) { - var start = state.pos; - if (state.eat(0x28 /* ( */)) { - if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - return true - } - state.raise("Unterminated group"); - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatCapturingGroup = function(state) { - if (state.eat(0x28 /* ( */)) { - if (this.options.ecmaVersion >= 9) { - this.regexp_groupSpecifier(state); - } else if (state.current() === 0x3F /* ? */) { - state.raise("Invalid group"); - } - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - state.numCapturingParens += 1; - return true - } - state.raise("Unterminated group"); - } - return false - }; + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom - pp$8.regexp_eatExtendedAtom = function(state) { - return ( - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) || - this.regexp_eatInvalidBracedQuantifier(state) || - this.regexp_eatExtendedPatternCharacter(state) - ) - }; + let m; - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier - pp$8.regexp_eatInvalidBracedQuantifier = function(state) { - if (this.regexp_eatBracedQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - return false - }; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + // eslint-disable-next-line no-return-assign + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} - // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter - pp$8.regexp_eatSyntaxCharacter = function(state) { - var ch = state.current(); - if (isSyntaxCharacter(ch)) { - state.lastIntValue = ch; - state.advance(); - return true - } - return false - }; - function isSyntaxCharacter(ch) { - return ( - ch === 0x24 /* $ */ || - ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || - ch === 0x2E /* . */ || - ch === 0x3F /* ? */ || - ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || - ch >= 0x7B /* { */ && ch <= 0x7D /* } */ - ) - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter - // But eat eager. - pp$8.regexp_eatPatternCharacters = function(state) { - var start = state.pos; - var ch = 0; - while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { - state.advance(); - } - return state.pos !== start - }; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter - pp$8.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false - }; + if (!this.useColors) { + return; + } - // GroupSpecifier :: - // [empty] - // `?` GroupName - pp$8.regexp_groupSpecifier = function(state) { - if (state.eat(0x3F /* ? */)) { - if (this.regexp_eatGroupName(state)) { - if (state.groupNames.indexOf(state.lastStringValue) !== -1) { - state.raise("Duplicate capture group name"); - } - state.groupNames.push(state.lastStringValue); - return - } - state.raise("Invalid group"); - } - }; + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - // GroupName :: - // `<` RegExpIdentifierName `>` - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatGroupName = function(state) { - state.lastStringValue = ""; - if (state.eat(0x3C /* < */)) { - if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { - return true - } - state.raise("Invalid capture group name"); - } - return false - }; + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - // RegExpIdentifierName :: - // RegExpIdentifierStart - // RegExpIdentifierName RegExpIdentifierPart - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatRegExpIdentifierName = function(state) { - state.lastStringValue = ""; - if (this.regexp_eatRegExpIdentifierStart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - while (this.regexp_eatRegExpIdentifierPart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - } - return true - } - return false - }; + args.splice(lastC, 0, c); +} - // RegExpIdentifierStart :: - // UnicodeIDStart - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - pp$8.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - state.pos = start; - return false - }; - function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - // RegExpIdentifierPart :: - // UnicodeIDContinue - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - // - // - pp$8.regexp_eatRegExpIdentifierPart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierPart(ch)) { - state.lastIntValue = ch; - return true - } +module.exports = __nccwpck_require__(76127)(exports); - state.pos = start; - return false - }; - function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ - } +const {formatters} = module.exports; - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape - pp$8.regexp_eatAtomEscape = function(state) { - if ( - this.regexp_eatBackReference(state) || - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) || - (state.switchN && this.regexp_eatKGroupName(state)) - ) { - return true - } - if (state.switchU) { - // Make the same message as V8. - if (state.current() === 0x63 /* c */) { - state.raise("Invalid unicode escape"); - } - state.raise("Invalid escape"); - } - return false - }; - pp$8.regexp_eatBackReference = function(state) { - var start = state.pos; - if (this.regexp_eatDecimalEscape(state)) { - var n = state.lastIntValue; - if (state.switchU) { - // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape - if (n > state.maxBackReference) { - state.maxBackReference = n; - } - return true - } - if (n <= state.numCapturingParens) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatKGroupName = function(state) { - if (state.eat(0x6B /* k */)) { - if (this.regexp_eatGroupName(state)) { - state.backReferenceNames.push(state.lastStringValue); - return true - } - state.raise("Invalid named reference"); - } - return false - }; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape - pp$8.regexp_eatCharacterEscape = function(state) { - return ( - this.regexp_eatControlEscape(state) || - this.regexp_eatCControlLetter(state) || - this.regexp_eatZero(state) || - this.regexp_eatHexEscapeSequence(state) || - this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || - (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || - this.regexp_eatIdentityEscape(state) - ) - }; - pp$8.regexp_eatCControlLetter = function(state) { - var start = state.pos; - if (state.eat(0x63 /* c */)) { - if (this.regexp_eatControlLetter(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatZero = function(state) { - if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { - state.lastIntValue = 0; - state.advance(); - return true - } - return false - }; +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape - pp$8.regexp_eatControlEscape = function(state) { - var ch = state.current(); - if (ch === 0x74 /* t */) { - state.lastIntValue = 0x09; /* \t */ - state.advance(); - return true - } - if (ch === 0x6E /* n */) { - state.lastIntValue = 0x0A; /* \n */ - state.advance(); - return true - } - if (ch === 0x76 /* v */) { - state.lastIntValue = 0x0B; /* \v */ - state.advance(); - return true - } - if (ch === 0x66 /* f */) { - state.lastIntValue = 0x0C; /* \f */ - state.advance(); - return true - } - if (ch === 0x72 /* r */) { - state.lastIntValue = 0x0D; /* \r */ - state.advance(); - return true - } - return false - }; - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter - pp$8.regexp_eatControlLetter = function(state) { - var ch = state.current(); - if (isControlLetter(ch)) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; - function isControlLetter(ch) { - return ( - (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || - (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) - ) - } +/***/ }), - // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence - pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { - if ( forceU === void 0 ) forceU = false; +/***/ 76127: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var start = state.pos; - var switchU = forceU || state.switchU; - if (state.eat(0x75 /* u */)) { - if (this.regexp_eatFixedHexDigits(state, 4)) { - var lead = state.lastIntValue; - if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { - var leadSurrogateEnd = state.pos; - if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { - var trail = state.lastIntValue; - if (trail >= 0xDC00 && trail <= 0xDFFF) { - state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - return true - } - } - state.pos = leadSurrogateEnd; - state.lastIntValue = lead; - } - return true - } - if ( - switchU && - state.eat(0x7B /* { */) && - this.regexp_eatHexDigits(state) && - state.eat(0x7D /* } */) && - isValidUnicode(state.lastIntValue) - ) { - return true - } - if (switchU) { - state.raise("Invalid unicode escape"); - } - state.pos = start; - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - return false - }; - function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF - } +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape - pp$8.regexp_eatIdentityEscape = function(state) { - if (state.switchU) { - if (this.regexp_eatSyntaxCharacter(state)) { - return true - } - if (state.eat(0x2F /* / */)) { - state.lastIntValue = 0x2F; /* / */ - return true - } - return false - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true - } + /** + * The currently active debug mode names, and names to skip. + */ - return false - }; + createDebug.names = []; + createDebug.skips = []; - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape - pp$8.regexp_eatDecimalEscape = function(state) { - state.lastIntValue = 0; - var ch = state.current(); - if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { - do { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) - return true - } - return false - }; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape - pp$8.regexp_eatCharacterClassEscape = function(state) { - var ch = state.current(); + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - if ( - state.switchU && - this.options.ecmaVersion >= 9 && - (ch === 0x50 /* P */ || ch === 0x70 /* p */) - ) { - state.lastIntValue = -1; - state.advance(); - if ( - state.eat(0x7B /* { */) && - this.regexp_eatUnicodePropertyValueExpression(state) && - state.eat(0x7D /* } */) - ) { - return true - } - state.raise("Invalid property name"); - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - return false - }; - function isCharacterClassEscape(ch) { - return ( - ch === 0x64 /* d */ || - ch === 0x44 /* D */ || - ch === 0x73 /* s */ || - ch === 0x53 /* S */ || - ch === 0x77 /* w */ || - ch === 0x57 /* W */ - ) - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - // UnicodePropertyValueExpression :: - // UnicodePropertyName `=` UnicodePropertyValue - // LoneUnicodePropertyNameOrValue - pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { - var start = state.pos; + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - // UnicodePropertyName `=` UnicodePropertyValue - if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { - var name = state.lastStringValue; - if (this.regexp_eatUnicodePropertyValue(state)) { - var value = state.lastStringValue; - this.regexp_validateUnicodePropertyNameAndValue(state, name, value); - return true - } - } - state.pos = start; + const self = debug; - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true - } - return false - }; - pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { - if (!has(state.unicodeProperties.nonBinary, name)) - { state.raise("Invalid property name"); } - if (!state.unicodeProperties.nonBinary[name].test(value)) - { state.raise("Invalid property value"); } - }; - pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { - if (!state.unicodeProperties.binary.test(nameOrValue)) - { state.raise("Invalid property name"); } - }; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - // UnicodePropertyName :: - // UnicodePropertyNameCharacters - pp$8.regexp_eatUnicodePropertyName = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyNameCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyNameCharacter(ch) { - return isControlLetter(ch) || ch === 0x5F /* _ */ - } + args[0] = createDebug.coerce(args[0]); - // UnicodePropertyValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatUnicodePropertyValue = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyValueCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyValueCharacter(ch) { - return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) - } + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - // LoneUnicodePropertyNameOrValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { - return this.regexp_eatUnicodePropertyValue(state) - }; + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass - pp$8.regexp_eatCharacterClass = function(state) { - if (state.eat(0x5B /* [ */)) { - state.eat(0x5E /* ^ */); - this.regexp_classRanges(state); - if (state.eat(0x5D /* ] */)) { - return true - } - // Unreachable since it threw "unterminated regular expression" error before. - state.raise("Unterminated character class"); - } - return false - }; + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash - pp$8.regexp_classRanges = function(state) { - while (this.regexp_eatClassAtom(state)) { - var left = state.lastIntValue; - if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { - var right = state.lastIntValue; - if (state.switchU && (left === -1 || right === -1)) { - state.raise("Invalid character class"); - } - if (left !== -1 && right !== -1 && left > right) { - state.raise("Range out of order in character class"); - } - } - } - }; + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash - pp$8.regexp_eatClassAtom = function(state) { - var start = state.pos; + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatClassEscape(state)) { - return true - } - if (state.switchU) { - // Make the same message as V8. - var ch$1 = state.current(); - if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { - state.raise("Invalid class escape"); - } - state.raise("Invalid escape"); - } - state.pos = start; - } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - var ch = state.current(); - if (ch !== 0x5D /* ] */) { - state.lastIntValue = ch; - state.advance(); - return true - } + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - return false - }; + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape - pp$8.regexp_eatClassEscape = function(state) { - var start = state.pos; + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } + return debug; + } - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) - }; + createDebug.names = []; + createDebug.skips = []; - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter - pp$8.regexp_eatClassControlLetter = function(state) { - var ch = state.current(); - if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(' ', ',') + .split(',') + .filter(Boolean); - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatHexEscapeSequence = function(state) { - var start = state.pos; - if (state.eat(0x78 /* x */)) { - if (this.regexp_eatFixedHexDigits(state, 2)) { - return true - } - if (state.switchU) { - state.raise("Invalid escape"); - } - state.pos = start; - } - return false - }; + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits - pp$8.regexp_eatDecimalDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isDecimalDigit(ch = state.current())) { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } - return state.pos !== start - }; - function isDecimalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ - } + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits - pp$8.regexp_eatHexDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isHexDigit(ch = state.current())) { - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return state.pos !== start - }; - function isHexDigit(ch) { - return ( - (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || - (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || - (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) - ) - } - function hexToInt(ch) { - if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { - return 10 + (ch - 0x41 /* A */) - } - if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { - return 10 + (ch - 0x61 /* a */) - } - return ch - 0x30 /* 0 */ - } + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { + // Match character or proceed with wildcard + if (template[templateIndex] === '*') { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; // Skip the '*' + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition + // Backtrack to the last '*' and try to match more characters + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; // No match + } + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence - // Allows only 0-377(octal) i.e. 0-255(decimal). - pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { - if (this.regexp_eatOctalDigit(state)) { - var n1 = state.lastIntValue; - if (this.regexp_eatOctalDigit(state)) { - var n2 = state.lastIntValue; - if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { - state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; - } else { - state.lastIntValue = n1 * 8 + n2; - } - } else { - state.lastIntValue = n1; - } - return true - } - return false - }; + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit - pp$8.regexp_eatOctalDigit = function(state) { - var ch = state.current(); - if (isOctalDigit(ch)) { - state.lastIntValue = ch - 0x30; /* 0 */ - state.advance(); - return true - } - state.lastIntValue = 0; - return false - }; - function isOctalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ - } + return templateIndex === template.length; + } - // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit - // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatFixedHexDigits = function(state, length) { - var start = state.pos; - state.lastIntValue = 0; - for (var i = 0; i < length; ++i) { - var ch = state.current(); - if (!isHexDigit(ch)) { - state.pos = start; - return false - } - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return true - }; + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - // Object type used to represent tokens. Note that normally, tokens - // simply exist as properties on the parser object. This is only - // used for the onToken callback and the external tokenizer. + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } - var Token = function Token(p) { - this.type = p.type; - this.value = p.value; - this.start = p.start; - this.end = p.end; - if (p.options.locations) - { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } - if (p.options.ranges) - { this.range = [p.start, p.end]; } - }; + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } - // ## Tokenizer + return false; + } - var pp$9 = Parser.prototype; + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - // Move to the next token + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - pp$9.next = function(ignoreEscapeSequenceInKeyword) { - if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) - { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } - if (this.options.onToken) - { this.options.onToken(new Token(this)); } + createDebug.enable(createDebug.load()); - this.lastTokEnd = this.end; - this.lastTokStart = this.start; - this.lastTokEndLoc = this.endLoc; - this.lastTokStartLoc = this.startLoc; - this.nextToken(); - }; + return createDebug; +} - pp$9.getToken = function() { - this.next(); - return new Token(this) - }; +module.exports = setup; - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - { pp$9[Symbol.iterator] = function() { - var this$1 = this; - return { - next: function () { - var token = this$1.getToken(); - return { - done: token.type === types.eof, - value: token - } - } - } - }; } +/***/ }), - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). +/***/ 6785: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - pp$9.curContext = function() { - return this.context[this.context.length - 1] - }; +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - // Read a single token, updating the parser object's token-related - // properties. +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(90814); +} else { + module.exports = __nccwpck_require__(49559); +} - pp$9.nextToken = function() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } - this.start = this.pos; - if (this.options.locations) { this.startLoc = this.curPosition(); } - if (this.pos >= this.input.length) { return this.finishToken(types.eof) } +/***/ }), - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } - }; +/***/ 49559: +/***/ ((module, exports, __nccwpck_require__) => { - pp$9.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - { return this.readWord() } +/** + * Module dependencies. + */ - return this.getTokenFromCode(code) - }; +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); - pp$9.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos); - if (code <= 0xd7ff || code >= 0xe000) { return code } - var next = this.input.charCodeAt(this.pos + 1); - return (code << 10) + next - 0x35fdc00 - }; +/** + * This is the Node.js implementation of `debug()`. + */ - pp$9.skipBlockComment = function() { - var startLoc = this.options.onComment && this.curPosition(); - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); - if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } - this.pos = end + 2; - if (this.options.locations) { - lineBreakG.lastIndex = start; - var match; - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this.curLine; - this.lineStart = match.index + match[0].length; - } - } - if (this.options.onComment) - { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()); } - }; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - pp$9.skipLineComment = function(startSkip) { - var start = this.pos; - var startLoc = this.options.onComment && this.curPosition(); - var ch = this.input.charCodeAt(this.pos += startSkip); - while (this.pos < this.input.length && !isNewLine(ch)) { - ch = this.input.charCodeAt(++this.pos); - } - if (this.options.onComment) - { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()); } - }; +/** + * Colors. + */ - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. +exports.colors = [6, 2, 3, 4, 5, 1]; - pp$9.skipSpace = function() { - loop: while (this.pos < this.input.length) { - var ch = this.input.charCodeAt(this.pos); - switch (ch) { - case 32: case 160: // ' ' - ++this.pos; - break - case 13: - if (this.input.charCodeAt(this.pos + 1) === 10) { - ++this.pos; - } - case 10: case 8232: case 8233: - ++this.pos; - if (this.options.locations) { - ++this.curLine; - this.lineStart = this.pos; - } - break - case 47: // '/' - switch (this.input.charCodeAt(this.pos + 1)) { - case 42: // '*' - this.skipBlockComment(); - break - case 47: - this.skipLineComment(2); - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.pos; - } else { - break loop - } - } - } - }; +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - pp$9.finishToken = function(type, val) { - this.end = this.pos; - if (this.options.locations) { this.endLoc = this.curPosition(); } - var prevType = this.type; - this.type = type; - this.value = val; +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - this.updateContext(prevType); - }; + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - // ### Token reading + obj[prop] = val; + return obj; +}, {}); - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - pp$9.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1); - if (next >= 48 && next <= 57) { return this.readNumber(true) } - var next2 = this.input.charCodeAt(this.pos + 2); - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3; - return this.finishToken(types.ellipsis) - } else { - ++this.pos; - return this.finishToken(types.dot) - } - }; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - pp$9.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1); - if (this.exprAllowed) { ++this.pos; return this.readRegexp() } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.slash, 1) - }; +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - pp$9.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - var tokentype = code === 42 ? types.star : types.modulo; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) - }; + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - pp$9.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (this.options.ecmaVersion >= 12) { - var next2 = this.input.charCodeAt(this.pos + 2); - if (next2 === 61) { return this.finishOp(types.assign, 3) } - } - return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) - }; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} - pp$9.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1); - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.bitwiseXOR, 1) - }; +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} - pp$9.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && - (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) - }; +/** + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. + */ - pp$9.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types.incDec, 2) } - } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.plusMin, 1) + }; - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } + pp$9.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(types.bitShift, size) } - } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `'); - }, - /** - * Visit a `YieldBlock`. - * - * This is necessary since we allow compiling a file with `yield`. - * - * @param {YieldBlock} block - * @api public - */ +/***/ }), - visitYieldBlock: function(block) {}, +/***/ 77193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ +"use strict"; - visitBlockComment: function(comment) { - if (!comment.buffer) return; - if (this.pp) this.prettyIndent(1, true); - this.buffer(''); - }, +const u = (__nccwpck_require__(9046).fromPromise) +const fs = __nccwpck_require__(48887) - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ +function pathExists (path) { + return fs.access(path).then(() => true).catch(() => false) +} - visitCode: function(code) { - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control +module.exports = { + pathExists: u(pathExists), + pathExistsSync: fs.existsSync +} - // Buffer code - if (code.buffer) { - var val = code.val.trim(); - val = 'null == (pug_interp = ' + val + ') ? "" : pug_interp'; - if (code.mustEscape !== false) - val = this.runtime('escape') + '(' + val + ')'; - this.bufferExpression(val); - } else { - this.buf.push(code.val); - } - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block, code); - if (!code.buffer) this.buf.push('}'); - } - }, +/***/ }), - /** - * Visit `Conditional`. - * - * @param {Conditional} cond - * @api public - */ +/***/ 65167: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - visitConditional: function(cond) { - var test = cond.test; - this.buf.push('if (' + test + ') {'); - this.visit(cond.consequent, cond); - this.buf.push('}'); - if (cond.alternate) { - if (cond.alternate.type === 'Conditional') { - this.buf.push('else'); - this.visitConditional(cond.alternate); - } else { - this.buf.push('else {'); - this.visit(cond.alternate, cond); - this.buf.push('}'); - } - } - }, +"use strict"; - /** - * Visit `While`. - * - * @param {While} loop - * @api public - */ - visitWhile: function(loop) { - var test = loop.test; - this.buf.push('while (' + test + ') {'); - this.visit(loop.block, loop); - this.buf.push('}'); - }, +const fs = __nccwpck_require__(71244) +const u = (__nccwpck_require__(9046).fromCallback) +const rimraf = __nccwpck_require__(45747) - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ +function remove (path, callback) { + // Node 14.14.0+ + if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback) + rimraf(path, callback) +} - visitEach: function(each) { - var indexVarName = each.key || 'pug_index' + this.eachCount; - this.eachCount++; +function removeSync (path) { + // Node 14.14.0+ + if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true }) + rimraf.sync(path) +} - this.buf.push( - '' + - '// iterate ' + - each.obj + - '\n' + - ';(function(){\n' + - ' var $$obj = ' + - each.obj + - ';\n' + - " if ('number' == typeof $$obj.length) {" - ); +module.exports = { + remove: u(remove), + removeSync +} - if (each.alternate) { - this.buf.push(' if ($$obj.length) {'); - } - this.buf.push( - '' + - ' for (var ' + - indexVarName + - ' = 0, $$l = $$obj.length; ' + - indexVarName + - ' < $$l; ' + - indexVarName + - '++) {\n' + - ' var ' + - each.val + - ' = $$obj[' + - indexVarName + - '];' - ); +/***/ }), - this.visit(each.block, each); +/***/ 45747: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.buf.push(' }'); +"use strict"; - if (each.alternate) { - this.buf.push(' } else {'); - this.visit(each.alternate, each); - this.buf.push(' }'); - } - this.buf.push( - '' + - ' } else {\n' + - ' var $$l = 0;\n' + - ' for (var ' + - indexVarName + - ' in $$obj) {\n' + - ' $$l++;\n' + - ' var ' + - each.val + - ' = $$obj[' + - indexVarName + - '];' - ); +const fs = __nccwpck_require__(71244) +const path = __nccwpck_require__(71017) +const assert = __nccwpck_require__(39491) - this.visit(each.block, each); +const isWindows = (process.platform === 'win32') - this.buf.push(' }'); - if (each.alternate) { - this.buf.push(' if ($$l === 0) {'); - this.visit(each.alternate, each); - this.buf.push(' }'); - } - this.buf.push(' }\n}).call(this);\n'); - }, +function defaults (options) { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) - visitEachOf: function(each) { - this.buf.push( - '' + - '// iterate ' + - each.obj + - '\n' + - 'for (const ' + - each.val + - ' of ' + - each.obj + - ') {\n' - ); + options.maxBusyTries = options.maxBusyTries || 3 +} - this.visit(each.block, each); +function rimraf (p, options, cb) { + let busyTries = 0 - this.buf.push('}\n'); - }, + if (typeof options === 'function') { + cb = options + options = {} + } - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - visitAttributes: function(attrs, attributeBlocks) { - if (attributeBlocks.length) { - if (attrs.length) { - var val = this.attrs(attrs); - attributeBlocks.unshift(val); - } - if (attributeBlocks.length > 1) { - this.bufferExpression( - this.runtime('attrs') + - '(' + - this.runtime('merge') + - '([' + - attributeBlocks.join(',') + - ']), ' + - stringify(this.terse) + - ')' - ); - } else { - this.bufferExpression( - this.runtime('attrs') + - '(' + - attributeBlocks[0] + - ', ' + - stringify(this.terse) + - ')' - ); + defaults(options) + + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && + busyTries < options.maxBusyTries) { + busyTries++ + const time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), time) } - } else if (attrs.length) { - this.attrs(attrs, true); + + // already gone + if (er.code === 'ENOENT') er = null } - }, - /** - * Compile attributes. - */ + cb(er) + }) +} - attrs: function(attrs, buffer) { - var res = compileAttrs(attrs, { - terse: this.terse, - format: buffer ? 'html' : 'object', - runtime: this.runtime.bind(this), - }); - if (buffer) { - this.bufferExpression(res); +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === 'ENOENT') { + return cb(null) } - return res; - }, - /** - * Compile attribute blocks. - */ + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === 'EPERM' && isWindows) { + return fixWinEPERM(p, options, er, cb) + } - attributeBlocks: function(attributeBlocks) { - return ( - attributeBlocks && - attributeBlocks.slice().map(function(attrBlock) { - return attrBlock.val; + if (st && st.isDirectory()) { + return rmdir(p, options, er, cb) + } + + options.unlink(p, er => { + if (er) { + if (er.code === 'ENOENT') { + return cb(null) + } + if (er.code === 'EPERM') { + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + } + if (er.code === 'EISDIR') { + return rmdir(p, options, er, cb) + } + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.chmod(p, 0o666, er2 => { + if (er2) { + cb(er2.code === 'ENOENT' ? null : er) + } else { + options.stat(p, (er3, stats) => { + if (er3) { + cb(er3.code === 'ENOENT' ? null : er) + } else if (stats.isDirectory()) { + rmdir(p, options, er, cb) + } else { + options.unlink(p, cb) + } }) - ); - }, -}; + } + }) +} -function tagCanInline(tag) { - function isInline(node) { - // Recurse if the node is a block - if (node.type === 'Block') return node.nodes.every(isInline); - // When there is a YieldBlock here, it is an indication that the file is - // expected to be included but is not. If this is the case, the block - // must be empty. - if (node.type === 'YieldBlock') return true; - return (node.type === 'Text' && !/\n/.test(node.val)) || node.isInline; +function fixWinEPERMSync (p, options, er) { + let stats + + assert(p) + assert(options) + + try { + options.chmodSync(p, 0o666) + } catch (er2) { + if (er2.code === 'ENOENT') { + return + } else { + throw er + } } - return tag.block.nodes.every(isInline); + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === 'ENOENT') { + return + } else { + throw er + } + } + + if (stats.isDirectory()) { + rmdirSync(p, options, er) + } else { + options.unlinkSync(p) + } } +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') -/***/ }), + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { + rmkids(p, options, cb) + } else if (er && er.code === 'ENOTDIR') { + cb(originalEr) + } else { + cb(er) + } + }) +} -/***/ 11449: -/***/ ((module) => { +function rmkids (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') -"use strict"; + options.readdir(p, (er, files) => { + if (er) return cb(er) + let n = files.length + let errState -module.exports = makeError; -function makeError(code, message, options) { - var line = options.line; - var column = options.column; - var filename = options.filename; - var src = options.src; - var fullMessage; - var location = line + (column ? ':' + column : ''); - if (src && line >= 1 && line <= src.split('\n').length) { - var lines = src.split('\n'); - var start = Math.max(line - 3, 0); - var end = Math.min(lines.length, line + 3); - // Error context - var context = lines - .slice(start, end) - .map(function(text, i) { - var curr = i + start + 1; - var preamble = (curr == line ? ' > ' : ' ') + curr + '| '; - var out = preamble + text; - if (curr === line && column > 0) { - out += '\n'; - out += Array(preamble.length + column).join('-') + '^'; + if (n === 0) return options.rmdir(p, cb) + + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) { + return + } + if (er) return cb(errState = er) + if (--n === 0) { + options.rmdir(p, cb) } - return out; }) - .join('\n'); - fullMessage = - (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message; - } else { - fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message; - } - var err = new Error(fullMessage); - err.code = 'PUG:' + code; - err.msg = message; - err.line = line; - err.column = column; - err.filename = filename; - err.src = src; - err.toJSON = function() { - return { - code: this.code, - msg: this.msg, - line: this.line, - column: this.column, - filename: this.filename, - }; - }; - return err; + }) + }) } +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + let st -/***/ }), + options = options || {} + defaults(options) -/***/ 69309: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + assert(p, 'rimraf: missing path') + assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') -"use strict"; + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === 'ENOENT') { + return + } + // Windows can EPERM on stat. Life is suffering. + if (er.code === 'EPERM' && isWindows) { + fixWinEPERMSync(p, options, er) + } + } -exports.runFilter = __nccwpck_require__(9498); -exports.handleFilters = __nccwpck_require__(77823); + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) { + rmdirSync(p, options, null) + } else { + options.unlinkSync(p) + } + } catch (er) { + if (er.code === 'ENOENT') { + return + } else if (er.code === 'EPERM') { + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + } else if (er.code !== 'EISDIR') { + throw er + } + rmdirSync(p, options, er) + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === 'ENOTDIR') { + throw originalEr + } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { + rmkidsSync(p, options) + } else if (er.code !== 'ENOENT') { + throw er + } + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) + + if (isWindows) { + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + const startTime = Date.now() + do { + try { + const ret = options.rmdirSync(p, options) + return ret + } catch {} + } while (Date.now() - startTime < 500) // give up after 500ms + } else { + const ret = options.rmdirSync(p, options) + return ret + } +} + +module.exports = rimraf +rimraf.sync = rimrafSync /***/ }), -/***/ 77823: +/***/ 93657: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var dirname = (__nccwpck_require__(71017).dirname); -var constantinople = __nccwpck_require__(40953); -var walk = __nccwpck_require__(60283); -var error = __nccwpck_require__(11449); -var runFilter = __nccwpck_require__(9498); +const fs = __nccwpck_require__(48887) +const path = __nccwpck_require__(71017) +const util = __nccwpck_require__(73837) -module.exports = handleFilters; -function handleFilters(ast, filters, options, filterAliases) { - options = options || {}; - walk( - ast, - function(node) { - var dir = node.filename ? dirname(node.filename) : null; - if (node.type === 'Filter') { - handleNestedFilters(node, filters, options, filterAliases); - var text = getBodyAsText(node); - var attrs = getAttributes(node, options); - attrs.filename = node.filename; - node.type = 'Text'; - node.val = filterWithFallback(node, text, attrs); - } else if (node.type === 'RawInclude' && node.filters.length) { - var firstFilter = node.filters.pop(); - var attrs = getAttributes(firstFilter, options); - var filename = (attrs.filename = node.file.fullPath); - node.type = 'Text'; - node.val = filterFileWithFallback( - firstFilter, - filename, - node.file, - attrs - ); - node.filters - .slice() - .reverse() - .forEach(function(filter) { - var attrs = getAttributes(filter, options); - attrs.filename = filename; - node.val = filterWithFallback(filter, node.val, attrs); - }); - node.filters = undefined; - node.file = undefined; - } +function getStats (src, dest, opts) { + const statFunc = opts.dereference + ? (file) => fs.stat(file, { bigint: true }) + : (file) => fs.lstat(file, { bigint: true }) + return Promise.all([ + statFunc(src), + statFunc(dest).catch(err => { + if (err.code === 'ENOENT') return null + throw err + }) + ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) +} - function filterWithFallback(filter, text, attrs, funcName) { - try { - var filterName = getFilterName(filter); - if (filters && filters[filterName]) { - return filters[filterName](text, attrs); - } else { - return runFilter(filterName, text, attrs, dir, funcName); - } - } catch (ex) { - if (ex.code === 'UNKNOWN_FILTER') { - throw error(ex.code, ex.message, filter); - } - throw ex; - } - } +function getStatsSync (src, dest, opts) { + let destStat + const statFunc = opts.dereference + ? (file) => fs.statSync(file, { bigint: true }) + : (file) => fs.lstatSync(file, { bigint: true }) + const srcStat = statFunc(src) + try { + destStat = statFunc(dest) + } catch (err) { + if (err.code === 'ENOENT') return { srcStat, destStat: null } + throw err + } + return { srcStat, destStat } +} - function filterFileWithFallback(filter, filename, file, attrs) { - var filterName = getFilterName(filter); - if (filters && filters[filterName]) { - if (filters[filterName].renderBuffer) { - return filters[filterName].renderBuffer(file.raw, attrs); - } else { - return filters[filterName](file.str, attrs); - } - } else { - return filterWithFallback(filter, filename, attrs, 'renderFile'); +function checkPaths (src, dest, funcName, opts, cb) { + util.callbackify(getStats)(src, dest, opts, (err, stats) => { + if (err) return cb(err) + const { srcStat, destStat } = stats + + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return cb(null, { srcStat, destStat, isChangingCase: true }) } + return cb(new Error('Source and destination must not be the same.')) } - }, - {includeDependencies: true} - ); - function getFilterName(filter) { - var filterName = filter.name; - if (filterAliases && filterAliases[filterName]) { - filterName = filterAliases[filterName]; - if (filterAliases[filterName]) { - throw error( - 'FILTER_ALISE_CHAIN', - 'The filter "' + - filter.name + - '" is an alias for "' + - filterName + - '", which is an alias for "' + - filterAliases[filterName] + - '". Pug does not support chains of filter aliases.', - filter - ); + if (srcStat.isDirectory() && !destStat.isDirectory()) { + return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) + } + if (!srcStat.isDirectory() && destStat.isDirectory()) { + return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)) } } - return filterName; - } - return ast; + + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + return cb(new Error(errMsg(src, dest, funcName))) + } + return cb(null, { srcStat, destStat }) + }) } -function handleNestedFilters(node, filters, options, filterAliases) { - if (node.block.nodes[0] && node.block.nodes[0].type === 'Filter') { - node.block.nodes[0] = handleFilters( - node.block, - filters, - options, - filterAliases - ).nodes[0]; +function checkPathsSync (src, dest, funcName, opts) { + const { srcStat, destStat } = getStatsSync(src, dest, opts) + + if (destStat) { + if (areIdentical(srcStat, destStat)) { + const srcBaseName = path.basename(src) + const destBaseName = path.basename(dest) + if (funcName === 'move' && + srcBaseName !== destBaseName && + srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { + return { srcStat, destStat, isChangingCase: true } + } + throw new Error('Source and destination must not be the same.') + } + if (srcStat.isDirectory() && !destStat.isDirectory()) { + throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) + } + if (!srcStat.isDirectory() && destStat.isDirectory()) { + throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) + } } -} -function getBodyAsText(node) { - return node.block.nodes - .map(function(node) { - return node.val; - }) - .join(''); + if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { + throw new Error(errMsg(src, dest, funcName)) + } + return { srcStat, destStat } } -function getAttributes(node, options) { - var attrs = {}; - node.attrs.forEach(function(attr) { - try { - attrs[attr.name] = - attr.val === true ? true : constantinople.toConstant(attr.val); - } catch (ex) { - if (/not constant/.test(ex.message)) { - throw error( - 'FILTER_OPTION_NOT_CONSTANT', - ex.message + - ' All filters are rendered compile-time so filter options must be constants.', - node - ); - } - throw ex; +// recursively check if dest parent is a subdirectory of src. +// It works for all file types including symlinks since it +// checks the src and dest inodes. It starts from the deepest +// parent and stops once it reaches the src parent or the root path. +function checkParentPaths (src, srcStat, dest, funcName, cb) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() + fs.stat(destParent, { bigint: true }, (err, destStat) => { + if (err) { + if (err.code === 'ENOENT') return cb() + return cb(err) } - }); - var opts = options[node.name] || {}; - Object.keys(opts).forEach(function(opt) { - if (!attrs.hasOwnProperty(opt)) { - attrs[opt] = opts[opt]; + if (areIdentical(srcStat, destStat)) { + return cb(new Error(errMsg(src, dest, funcName))) } - }); - return attrs; + return checkParentPaths(src, srcStat, destParent, funcName, cb) + }) +} + +function checkParentPathsSync (src, srcStat, dest, funcName) { + const srcParent = path.resolve(path.dirname(src)) + const destParent = path.resolve(path.dirname(dest)) + if (destParent === srcParent || destParent === path.parse(destParent).root) return + let destStat + try { + destStat = fs.statSync(destParent, { bigint: true }) + } catch (err) { + if (err.code === 'ENOENT') return + throw err + } + if (areIdentical(srcStat, destStat)) { + throw new Error(errMsg(src, dest, funcName)) + } + return checkParentPathsSync(src, srcStat, destParent, funcName) +} + +function areIdentical (srcStat, destStat) { + return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev +} + +// return true if dest is a subdir of src, otherwise false. +// It only checks the path strings. +function isSrcSubdir (src, dest) { + const srcArr = path.resolve(src).split(path.sep).filter(i => i) + const destArr = path.resolve(dest).split(path.sep).filter(i => i) + return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) +} + +function errMsg (src, dest, funcName) { + return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` +} + +module.exports = { + checkPaths, + checkPathsSync, + checkParentPaths, + checkParentPathsSync, + isSrcSubdir, + areIdentical } /***/ }), -/***/ 9498: +/***/ 73632: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var jstransformer = __nccwpck_require__(77369); -var resolve = __nccwpck_require__(81679); +const fs = __nccwpck_require__(71244) -module.exports = filter; +function utimesMillis (path, atime, mtime, callback) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + fs.open(path, 'r+', (err, fd) => { + if (err) return callback(err) + fs.futimes(fd, atime, mtime, futimesErr => { + fs.close(fd, closeErr => { + if (callback) callback(futimesErr || closeErr) + }) + }) + }) +} -function getMinifyTransformerName(outputFormat) { - switch (outputFormat) { - case 'js': - return 'uglify-js'; - case 'css': - return 'clean-css'; - } +function utimesMillisSync (path, atime, mtime) { + const fd = fs.openSync(path, 'r+') + fs.futimesSync(fd, atime, mtime) + return fs.closeSync(fd) } -function filter(name, str, options, currentDirectory, funcName) { - funcName = funcName || 'render'; - var trPath; - try { - try { - trPath = resolve.sync('jstransformer-' + name, { - basedir: currentDirectory || process.cwd(), - }); - } catch (ex) { - trPath = require.resolve('jstransformer-' + name); - } - } catch (ex) { - var err = new Error('unknown filter ":' + name + '"'); - err.code = 'UNKNOWN_FILTER'; - throw err; - } - var tr = jstransformer(require(trPath)); - // TODO: we may want to add a way for people to separately specify "locals" - var result = tr[funcName](str, options, options).body; - if (options && options.minify) { - var minifyTranformer = getMinifyTransformerName(tr.outputFormat); - if (minifyTranformer) { - try { - result = filter(minifyTranformer, result, null, currentDirectory); - } catch (ex) { - // better to fail to minify than output nothing - } - } - } - return result; +module.exports = { + utimesMillis, + utimesMillisSync } /***/ }), -/***/ 53230: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42898: +/***/ ((module) => { "use strict"; -var has = __nccwpck_require__(76339); - -function specifierIncluded(current, specifier) { - var nodeParts = current.split('.'); - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - - for (var i = 0; i < 3; ++i) { - var cur = parseInt(nodeParts[i] || 0, 10); - var ver = parseInt(versionParts[i] || 0, 10); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } - if (op === '>=') { - return cur >= ver; - } - return false; - } - return op === '>='; -} +module.exports = clone -function matchesRange(current, range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { - return false; - } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(current, specifiers[i])) { - return false; - } - } - return true; +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ } -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; - } +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node - : nodeVersion; + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); - } + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(current, specifierValue[i])) { - return true; - } - } - return false; - } - return matchesRange(current, specifierValue); + return copy } -var data = __nccwpck_require__(79849); - -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); -}; - /***/ }), -/***/ 81679: +/***/ 71244: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var async = __nccwpck_require__(37600); -async.core = __nccwpck_require__(4632); -async.isCore = __nccwpck_require__(16520); -async.sync = __nccwpck_require__(92966); - -module.exports = async; +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(33889) +var legacy = __nccwpck_require__(36910) +var clone = __nccwpck_require__(42898) +var util = __nccwpck_require__(73837) -/***/ }), +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol -/***/ 37600: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} -var fs = __nccwpck_require__(57147); -var getHomedir = __nccwpck_require__(58108); -var path = __nccwpck_require__(71017); -var caller = __nccwpck_require__(50907); -var nodeModulesPaths = __nccwpck_require__(4287); -var normalizeOptions = __nccwpck_require__(48315); -var isCore = __nccwpck_require__(53230); +function noop () {} -var realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} -var homedir = getHomedir(); -var defaultPaths = function () { - return [ - path.join(homedir, '.node_modules'), - path.join(homedir, '.node_libraries') - ]; -}; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } -var defaultIsFile = function isFile(file, cb) { - fs.stat(file, function (err, stat) { - if (!err) { - return cb(null, stat.isFile() || stat.isFIFO()); - } - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); - return cb(err); - }); -}; +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) -var defaultIsDir = function isDirectory(dir, cb) { - fs.stat(dir, function (err, stat) { + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue if (!err) { - return cb(null, stat.isDirectory()); + resetQueue() } - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); - return cb(err); - }); -}; - -var defaultRealpath = function realpath(x, cb) { - realpathFS(x, function (realpathErr, realPath) { - if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); - else cb(null, realpathErr ? x : realPath); - }); -}; -var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { - if (opts && opts.preserveSymlinks === false) { - realpath(x, cb); - } else { - cb(null, x); + if (typeof cb === 'function') + cb.apply(this, arguments) + }) } -}; -var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { - readFile(pkgfile, function (readFileErr, body) { - if (readFileErr) cb(readFileErr); - else { - try { - var pkg = JSON.parse(body); - cb(null, pkg); - } catch (jsonErr) { - cb(null); - } - } - }); -}; + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) -var getPackageCandidates = function getPackageCandidates(x, start, opts) { - var dirs = nodeModulesPaths(start, opts, x); - for (var i = 0; i < dirs.length; i++) { - dirs[i] = path.join(dirs[i], x); + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() } - return dirs; -}; -module.exports = function resolve(x, options, callback) { - var cb = callback; - var opts = options; - if (typeof options === 'function') { - cb = opts; - opts = {}; - } - if (typeof x !== 'string') { - var err = new TypeError('Path must be a string.'); - return process.nextTick(function () { - cb(err); - }); - } + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) - opts = normalizeOptions(x, opts); + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} - var isFile = opts.isFile || defaultIsFile; - var isDirectory = opts.isDirectory || defaultIsDir; - var readFile = opts.readFile || fs.readFile; - var realpath = opts.realpath || defaultRealpath; - var readPackage = opts.readPackage || defaultReadPackage; - if (opts.readFile && opts.readPackage) { - var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); - return process.nextTick(function () { - cb(conflictErr); - }); - } - var packageIterator = opts.packageIterator; +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} - var extensions = opts.extensions || ['.js']; - var includeCoreModules = opts.includeCoreModules !== false; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - opts.paths = opts.paths || defaultPaths(); +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = path.resolve(basedir); + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - maybeRealpath( - realpath, - absoluteStart, - opts, - function (err, realStart) { - if (err) cb(err); - else init(realStart); - } - ); + return go$readFile(path, options, cb) - var res; - function init(basedir) { - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - res = path.resolve(basedir, x); - if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; - if ((/\/$/).test(x) && res === basedir) { - loadAsDirectory(res, opts.package, onfile); - } else loadAsFile(res, opts.package, onfile); - } else if (includeCoreModules && isCore(x)) { - return cb(null, x); - } else loadNodeModules(x, basedir, function (err, n, pkg) { - if (err) cb(err); - else if (n) { - return maybeRealpath(realpath, n, opts, function (err, realN) { - if (err) { - cb(err); - } else { - cb(null, realN, pkg); - } - }); - } else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); - } - }); + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } + } - function onfile(err, m, pkg) { - if (err) cb(err); - else if (m) cb(null, m, pkg); - else loadAsDirectory(res, function (err, d, pkg) { - if (err) cb(err); - else if (d) { - maybeRealpath(realpath, d, opts, function (err, realD) { - if (err) { - cb(err); - } else { - cb(null, realD, pkg); - } - }); - } else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); - } - }); - } + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - function loadAsFile(x, thePackage, callback) { - var loadAsFilePackage = thePackage; - var cb = callback; - if (typeof loadAsFilePackage === 'function') { - cb = loadAsFilePackage; - loadAsFilePackage = undefined; - } + return go$writeFile(path, data, options, cb) - var exts = [''].concat(extensions); - load(exts, x, loadAsFilePackage); + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - function load(exts, x, loadPackage) { - if (exts.length === 0) return cb(null, undefined, loadPackage); - var file = x + exts[0]; + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - var pkg = loadPackage; - if (pkg) onpkg(null, pkg); - else loadpkg(path.dirname(file), onpkg); + return go$appendFile(path, data, options, cb) - function onpkg(err, pkg_, dir) { - pkg = pkg_; - if (err) return cb(err); - if (dir && pkg && opts.pathFilter) { - var rfile = path.relative(dir, file); - var rel = rfile.slice(0, rfile.length - exts[0].length); - var r = opts.pathFilter(pkg, x, rel); - if (r) return load( - [''].concat(extensions.slice()), - path.resolve(dir, r), - pkg - ); - } - isFile(file, onex); - } - function onex(err, ex) { - if (err) return cb(err); - if (ex) return cb(null, file, pkg); - load(exts.slice(1), x, pkg); - } + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) } + }) } + } - function loadpkg(dir, cb) { - if (dir === '' || dir === '/') return cb(null); - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return cb(null); + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + }) + } + } - maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { - if (unwrapErr) return loadpkg(path.dirname(dir), cb); - var pkgfile = path.join(pkgdir, 'package.json'); - isFile(pkgfile, function (err, ex) { - // on err, ex is false - if (!ex) return loadpkg(path.dirname(dir), cb); + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - readPackage(readFile, pkgfile, function (err, pkgParam) { - if (err) cb(err); + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } - var pkg = pkgParam; + return go$readdir(path, options, cb) - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); - } - cb(null, pkg, dir); - }); - }); - }); - } + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() - function loadAsDirectory(x, loadAsDirectoryPackage, callback) { - var cb = callback; - var fpkg = loadAsDirectoryPackage; - if (typeof fpkg === 'function') { - cb = fpkg; - fpkg = opts.package; + if (typeof cb === 'function') + cb.call(this, err, files) } + } + } + } - maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { - if (unwrapErr) return cb(unwrapErr); - var pkgfile = path.join(pkgdir, 'package.json'); - isFile(pkgfile, function (err, ex) { - if (err) return cb(err); - if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } - readPackage(readFile, pkgfile, function (err, pkgParam) { - if (err) return cb(err); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - var pkg = pkgParam; + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); - } + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - if (pkg && pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - return cb(mainError); - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - var dir = path.resolve(x, pkg.main); - loadAsDirectory(dir, pkg, function (err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - loadAsFile(path.join(x, 'index'), pkg, cb); - }); - }); - return; - } + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - loadAsFile(path.join(x, '/index'), pkg, cb); - }); - }); - }); - } + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - function processDirs(cb, dirs) { - if (dirs.length === 0) return cb(null, undefined); - var dir = dirs[0]; + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - isDirectory(path.dirname(dir), isdir); + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - function isdir(err, isdir) { - if (err) return cb(err); - if (!isdir) return processDirs(cb, dirs.slice(1)); - loadAsFile(dir, opts.package, onfile); - } + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - function onfile(err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - loadAsDirectory(dir, opts.package, ondir); - } + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } - function ondir(err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - processDirs(cb, dirs.slice(1)); - } - } - function loadNodeModules(x, start, cb) { - var thunk = function () { return getPackageCandidates(x, start, opts); }; - processDirs( - cb, - packageIterator ? packageIterator(x, start, thunk, opts) : thunk() - ); - } -}; + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null -/***/ }), + return go$open(path, flags, mode, cb) -/***/ 50907: -/***/ ((module) => { + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -module.exports = function () { - // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - var origPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = function (_, stack) { return stack; }; - var stack = (new Error()).stack; - Error.prepareStackTrace = origPrepareStackTrace; - return stack[2].getFileName(); -}; + return fs +} +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} -/***/ }), +// keep track of the timeout between retry() calls +var retryTimer -/***/ 4632: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} -"use strict"; +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + if (fs[gracefulQueue].length === 0) + return -var isCoreModule = __nccwpck_require__(53230); -var data = __nccwpck_require__(19495); + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] -var core = {}; -for (var mod in data) { // eslint-disable-line no-restricted-syntax - if (Object.prototype.hasOwnProperty.call(data, mod)) { - core[mod] = isCoreModule(mod); + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } } -module.exports = core; /***/ }), -/***/ 58108: +/***/ 36910: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var Stream = (__nccwpck_require__(12781).Stream) +module.exports = legacy -var os = __nccwpck_require__(22037); +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } -// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -module.exports = os.homedir || function homedir() { - var home = process.env.HOME; - var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; + Stream.call(this); - if (process.platform === 'win32') { - return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; - } + var self = this; - if (process.platform === 'darwin') { - return home || (user ? '/Users/' + user : null); - } + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - if (process.platform === 'linux') { - return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens - } + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - return home || null; -}; + options = options || {}; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } -/***/ }), + if (this.encoding) this.setEncoding(this.encoding); -/***/ 16520: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } -var isCoreModule = __nccwpck_require__(53230); + if (this.start > this.end) { + throw new Error('start must be <= end'); + } -module.exports = function isCore(x) { - return isCoreModule(x); -}; + this.pos = this.start; + } + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -/***/ }), + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -/***/ 4287: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } -var path = __nccwpck_require__(71017); -var parse = path.parse || __nccwpck_require__(5980); // eslint-disable-line global-require + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); -var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { - var prefix = '/'; - if ((/^([A-Za-z]:)/).test(absoluteStart)) { - prefix = ''; - } else if ((/^\\\\/).test(absoluteStart)) { - prefix = '\\\\'; - } + Stream.call(this); - var paths = [absoluteStart]; - var parsed = parse(absoluteStart); - while (parsed.dir !== paths[paths.length - 1]) { - paths.push(parsed.dir); - parsed = parse(parsed.dir); - } + this.path = path; + this.fd = null; + this.writable = true; - return paths.reduce(function (dirs, aPath) { - return dirs.concat(modules.map(function (moduleDir) { - return path.resolve(prefix, aPath, moduleDir); - })); - }, []); -}; + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; -module.exports = function nodeModulesPaths(start, opts, request) { - var modules = opts && opts.moduleDirectory - ? [].concat(opts.moduleDirectory) - : ['node_modules']; + options = options || {}; - if (opts && typeof opts.paths === 'function') { - return opts.paths( - request, - start, - function () { return getNodeModulesDirs(start, modules); }, - opts - ); + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - var dirs = getNodeModulesDirs(start, modules); - return opts && opts.paths ? dirs.concat(opts.paths) : dirs; -}; - - -/***/ }), + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } -/***/ 48315: -/***/ ((module) => { + this.pos = this.start; + } -module.exports = function (x, opts) { - /** - * This file is purposefully a passthrough. It's expected that third-party - * environments will override it at runtime in order to inject special logic - * into `resolve` (by manipulating the options). One such example is the PnP - * code path in Yarn. - */ + this.busy = false; + this._queue = []; - return opts || {}; -}; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} /***/ }), -/***/ 92966: +/***/ 33889: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var isCore = __nccwpck_require__(53230); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var getHomedir = __nccwpck_require__(58108); -var caller = __nccwpck_require__(50907); -var nodeModulesPaths = __nccwpck_require__(4287); -var normalizeOptions = __nccwpck_require__(48315); +var constants = __nccwpck_require__(22057) -var realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; +var origCwd = process.cwd +var cwd = null -var homedir = getHomedir(); -var defaultPaths = function () { - return [ - path.join(homedir, '.node_modules'), - path.join(homedir, '.node_libraries') - ]; -}; +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -var defaultIsFile = function isFile(file) { - try { - var stat = fs.statSync(file, { throwIfNoEntry: false }); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; - throw e; - } - return !!stat && (stat.isFile() || stat.isFIFO()); -}; +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} -var defaultIsDir = function isDirectory(dir) { - try { - var stat = fs.statSync(dir, { throwIfNoEntry: false }); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; - throw e; - } - return !!stat && stat.isDirectory(); -}; +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} -var defaultRealpathSync = function realpathSync(x) { - try { - return realpathFS(x); - } catch (realpathErr) { - if (realpathErr.code !== 'ENOENT') { - throw realpathErr; - } - } - return x; -}; +module.exports = patch -var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { - if (opts && opts.preserveSymlinks === false) { - return realpathSync(x); - } - return x; -}; +function patch (fs) { + // (re-)implement some things that are known busted or missing. -var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { - var body = readFileSync(pkgfile); - try { - var pkg = JSON.parse(body); - return pkg; - } catch (jsonErr) {} -}; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -var getPackageCandidates = function getPackageCandidates(x, start, opts) { - var dirs = nodeModulesPaths(start, opts, x); - for (var i = 0; i < dirs.length; i++) { - dirs[i] = path.join(dirs[i], x); - } - return dirs; -}; + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } -module.exports = function resolveSync(x, options) { - if (typeof x !== 'string') { - throw new TypeError('Path must be a string.'); - } - var opts = normalizeOptions(x, options); + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - var isFile = opts.isFile || defaultIsFile; - var readFileSync = opts.readFileSync || fs.readFileSync; - var isDirectory = opts.isDirectory || defaultIsDir; - var realpathSync = opts.realpathSync || defaultRealpathSync; - var readPackageSync = opts.readPackageSync || defaultReadPackageSync; - if (opts.readFileSync && opts.readPackageSync) { - throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); - } - var packageIterator = opts.packageIterator; + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - var extensions = opts.extensions || ['.js']; - var includeCoreModules = opts.includeCoreModules !== false; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - opts.paths = opts.paths || defaultPaths(); + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - var res = path.resolve(absoluteStart, x); - if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; - var m = loadAsFileSync(res) || loadAsDirectorySync(res); - if (m) return maybeRealpathSync(realpathSync, m, opts); - } else if (includeCoreModules && isCore(x)) { - return x; - } else { - var n = loadNodeModulesSync(x, absoluteStart); - if (n) return maybeRealpathSync(realpathSync, n, opts); + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } + fs.lchownSync = function () {} + } - var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - err.code = 'MODULE_NOT_FOUND'; - throw err; + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - function loadAsFileSync(x) { - var pkg = loadpkg(path.dirname(x)); + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } - if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { - var rfile = path.relative(pkg.dir, x); - var r = opts.pathFilter(pkg.pkg, x, rfile); - if (r) { - x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign - } + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } - if (isFile(x)) { - return x; - } + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) - for (var i = 0; i < extensions.length; i++) { - var file = x + extensions[i]; - if (isFile(file)) { - return file; - } + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue } + throw er + } } + }})(fs.readSync) - function loadpkg(dir) { - if (dir === '' || dir === '/') return; - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - if (!isFile(pkgfile)) { - return loadpkg(path.dirname(dir)); + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) } + } + return ret + } + } - var pkg = readPackageSync(readFileSync, pkgfile); + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - if (pkg && opts.packageFilter) { - // v2 will pass pkgfile - pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } } + return ret + } - return { pkg: pkg, dir: dir }; + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } + } - function loadAsDirectorySync(x) { - var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); - if (isFile(pkgfile)) { - try { - var pkg = readPackageSync(readFileSync, pkgfile); - } catch (e) {} + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - if (pkg && opts.packageFilter) { - // v2 will pass pkgfile - pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment - } + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - if (pkg && pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - throw mainError; - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - try { - var m = loadAsFileSync(path.resolve(x, pkg.main)); - if (m) return m; - var n = loadAsDirectorySync(path.resolve(x, pkg.main)); - if (n) return n; - } catch (e) {} - } - } - return loadAsFileSync(path.join(x, '/index')); + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } + } - function loadNodeModulesSync(x, start) { - var thunk = function () { return getPackageCandidates(x, start, opts); }; - var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - if (isDirectory(path.dirname(dir))) { - var m = loadAsFileSync(dir); - if (m) return m; - var n = loadAsDirectorySync(dir); - if (n) return n; - } + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) } -}; - - -/***/ }), - -/***/ 32428: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + } + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } -var assert = __nccwpck_require__(39491); -var isExpression = __nccwpck_require__(53448); -var characterParser = __nccwpck_require__(8937); -var error = __nccwpck_require__(11449); + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true -module.exports = lex; -module.exports.Lexer = Lexer; -function lex(str, options) { - var lexer = new Lexer(str, options); - return JSON.parse(JSON.stringify(lexer.getTokens())); -} + if (er.code === "ENOSYS") + return true -/** - * Initialize `Lexer` with the given `str`. - * - * @param {String} str - * @param {String} filename - * @api private - */ + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } -function Lexer(str, options) { - options = options || {}; - if (typeof str !== 'string') { - throw new Error( - 'Expected source code to be a string but got "' + typeof str + '"' - ); - } - if (typeof options !== 'object') { - throw new Error( - 'Expected "options" to be an object but got "' + typeof options + '"' - ); + return false } - //Strip any UTF-8 BOM off of the start of `str`, if it exists. - str = str.replace(/^\uFEFF/, ''); - this.input = str.replace(/\r\n|\r/g, '\n'); - this.originalInput = this.input; - this.filename = options.filename; - this.interpolated = options.interpolated || false; - this.lineno = options.startingLine || 1; - this.colno = options.startingColumn || 1; - this.plugins = options.plugins || []; - this.indentStack = [0]; - this.indentRe = null; - // If #{}, !{} or #[] syntax is allowed when adding text - this.interpolationAllowed = true; - this.whitespaceRe = /[ \n\t]/; - - this.tokens = []; - this.ended = false; } -/** - * Lexer prototype. - */ - -Lexer.prototype = { - constructor: Lexer, - error: function(code, message) { - var err = error(code, message, { - line: this.lineno, - column: this.colno, - filename: this.filename, - src: this.originalInput, - }); - throw err; - }, +/***/ }), - assert: function(value, message) { - if (!value) this.error('ASSERT_FAILED', message); - }, +/***/ 55388: +/***/ ((module) => { - isExpression: function(exp) { - return isExpression(exp, { - throw: true, - }); - }, +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ - assertExpression: function(exp, noThrow) { - //this verifies that a JavaScript expression is valid - try { - this.callLexerFunction('isExpression', exp); - return true; - } catch (ex) { - if (noThrow) return false; +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } - // not coming from acorn - if (!ex.loc) throw ex; + if (path === '\\' || path === '/') return '/'; - this.incrementLine(ex.loc.line - 1); - this.incrementColumn(ex.loc.column); - var msg = - 'Syntax Error: ' + ex.message.replace(/ \([0-9]+:[0-9]+\)$/, ''); - this.error('SYNTAX_ERROR', msg); - } - }, + var len = path.length; + if (len <= 1) return path; - assertNestingCorrect: function(exp) { - //this verifies that code is properly nested, but allows - //invalid JavaScript such as the contents of `attributes` - var res = characterParser(exp); - if (res.isNesting()) { - this.error( - 'INCORRECT_NESTING', - 'Nesting must match on expression `' + exp + '`' - ); + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; } - }, - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val) { - var res = { - type: type, - loc: { - start: { - line: this.lineno, - column: this.colno, - }, - filename: this.filename, - }, - }; - - if (val !== undefined) res.val = val; - - return res; - }, - - /** - * Set the token's `loc.end` value. - * - * @param {Object} tok - * @returns {Object} - * @api private - */ - - tokEnd: function(tok) { - tok.loc.end = { - line: this.lineno, - column: this.colno, - }; - return tok; - }, + } - /** - * Increment `this.lineno` and reset `this.colno`. - * - * @param {Number} increment - * @api private - */ + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; - incrementLine: function(increment) { - this.lineno += increment; - if (increment) this.colno = 1; - }, - /** - * Increment `this.colno`. - * - * @param {Number} increment - * @api private - */ +/***/ }), - incrementColumn: function(increment) { - this.colno += increment; - }, +/***/ 20502: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ +"use strict"; - consume: function(len) { - this.input = this.input.substr(len); - }, +const path = __nccwpck_require__(71017); +const pathKey = __nccwpck_require__(20539); - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ +const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; - scan: function(regexp, type) { - var captures; - if ((captures = regexp.exec(this.input))) { - var len = captures[0].length; - var val = captures[1]; - var diff = len - (val ? val.length : 0); - var tok = this.tok(type, val); - this.consume(len); - this.incrementColumn(diff); - return tok; - } - }, - scanEndOfLine: function(regexp, type) { - var captures; - if ((captures = regexp.exec(this.input))) { - var whitespaceLength = 0; - var whitespace; - var tok; - if ((whitespace = /^([ ]+)([^ ]*)/.exec(captures[0]))) { - whitespaceLength = whitespace[1].length; - this.incrementColumn(whitespaceLength); - } - var newInput = this.input.substr(captures[0].length); - if (newInput[0] === ':') { - this.input = newInput; - tok = this.tok(type, captures[1]); - this.incrementColumn(captures[0].length - whitespaceLength); - return tok; - } - if (/^[ \t]*(\n|$)/.test(newInput)) { - this.input = newInput.substr(/^[ \t]*/.exec(newInput)[0].length); - tok = this.tok(type, captures[1]); - this.incrementColumn(captures[0].length - whitespaceLength); - return tok; - } - } - }, + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; - /** - * Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters. - * - * Make sure that when calling this function, colno is at the character - * immediately before the beginning. - * - * @return {Number} - * @api private - */ + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } - bracketExpression: function(skip) { - skip = skip || 0; - var start = this.input[skip]; - assert( - start === '(' || start === '{' || start === '[', - 'The start character should be "(", "{" or "["' - ); - var end = characterParser.BRACKETS[start]; - var range; - try { - range = characterParser.parseUntil(this.input, end, {start: skip + 1}); - } catch (ex) { - if (ex.index !== undefined) { - var idx = ex.index; - // starting from this.input[skip] - var tmp = this.input.substr(skip).indexOf('\n'); - // starting from this.input[0] - var nextNewline = tmp + skip; - var ptr = 0; - while (idx > nextNewline && tmp !== -1) { - this.incrementLine(1); - idx -= nextNewline + 1; - ptr += nextNewline + 1; - tmp = nextNewline = this.input.substr(ptr).indexOf('\n'); - } + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); - this.incrementColumn(idx); - } - if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { - this.error( - 'NO_END_BRACKET', - 'The end of the string reached with no closing bracket ' + - end + - ' found.' - ); - } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { - this.error('BRACKET_MISMATCH', ex.message); - } - throw ex; - } - return range; - }, + return result.concat(options.path).join(path.delimiter); +}; - scanIndentation: function() { - var captures, re; +module.exports = npmRunPath; +// TODO: Remove this for the next major release +module.exports["default"] = npmRunPath; - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); +module.exports.env = options => { + options = { + env: process.env, + ...options + }; - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } + const env = {...options.env}; + const path = pathKey({env}); - // established - if (captures && captures[1].length) this.indentRe = re; - } + options.path = env[path]; + env[path] = module.exports(options); - return captures; - }, + return env; +}; - /** - * end-of-source. - */ - eos: function() { - if (this.input.length) return; - if (this.interpolated) { - this.error( - 'NO_END_BRACKET', - 'End of line was reached with no closing bracket for interpolation.' - ); - } - for (var i = 0; this.indentStack[i]; i++) { - this.tokens.push(this.tokEnd(this.tok('outdent'))); - } - this.tokens.push(this.tokEnd(this.tok('eos'))); - this.ended = true; - return true; - }, +/***/ }), - /** - * Blank line. - */ +/***/ 17426: +/***/ ((module) => { - blank: function() { - var captures; - if ((captures = /^\n[ \t]*\n/.exec(this.input))) { - this.consume(captures[0].length - 1); - this.incrementLine(1); - return true; - } - }, +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ - /** - * Comment. - */ - comment: function() { - var captures; - if ((captures = /^\/\/(-)?([^\n]*)/.exec(this.input))) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - this.interpolationAllowed = tok.buffer; - this.tokens.push(tok); - this.incrementColumn(captures[0].length); - this.tokEnd(tok); - this.callLexerFunction('pipelessText'); - return true; - } - }, +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; - /** - * Interpolated tag. - */ +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } - interpolation: function() { - if (/^#\{/.test(this.input)) { - var match = this.bracketExpression(1); - this.consume(match.end + 1); - var tok = this.tok('interpolation', match.src); - this.tokens.push(tok); - this.incrementColumn(2); // '#{' - this.assertExpression(match.src); + return Object(val); +} - var splitted = match.src.split('\n'); - var lines = splitted.length - 1; - this.incrementLine(lines); - this.incrementColumn(splitted[lines].length + 1); // + 1 → '}' - this.tokEnd(tok); - return true; - } - }, +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } - /** - * Tag. - */ + // Detect buggy property enumeration order in older V8 versions. - tag: function() { - var captures; + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } - if ((captures = /^(\w(?:[-:\w]*\w)?)/.exec(this.input))) { - var tok, - name = captures[1], - len = captures[0].length; - this.consume(len); - tok = this.tok('tag', name); - this.tokens.push(tok); - this.incrementColumn(len); - this.tokEnd(tok); - return true; - } - }, + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } - /** - * Filter. - */ + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } - filter: function(opts) { - var tok = this.scan(/^:([\w\-]+)/, 'filter'); - var inInclude = opts && opts.inInclude; - if (tok) { - this.tokens.push(tok); - this.incrementColumn(tok.val.length); - this.tokEnd(tok); - this.callLexerFunction('attrs'); - if (!inInclude) { - this.interpolationAllowed = false; - this.callLexerFunction('pipelessText'); - } - return true; - } - }, + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} - /** - * Doctype. - */ +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; - doctype: function() { - var node = this.scanEndOfLine(/^doctype *([^\n]*)/, 'doctype'); - if (node) { - this.tokens.push(this.tokEnd(node)); - return true; - } - }, + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); - /** - * Id. - */ + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } - id: function() { - var tok = this.scan(/^#([\w-]+)/, 'id'); - if (tok) { - this.tokens.push(tok); - this.incrementColumn(tok.val.length); - this.tokEnd(tok); - return true; - } - if (/^#/.test(this.input)) { - this.error( - 'INVALID_ID', - '"' + - /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + - '" is not a valid ID.' - ); - } - }, + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } - /** - * Class. - */ + return to; +}; - className: function() { - var tok = this.scan(/^\.([_a-z0-9\-]*[_a-z][_a-z0-9\-]*)/i, 'class'); - if (tok) { - this.tokens.push(tok); - this.incrementColumn(tok.val.length); - this.tokEnd(tok); - return true; - } - if (/^\.[_a-z0-9\-]+/i.test(this.input)) { - this.error( - 'INVALID_CLASS_NAME', - 'Class names must contain at least one letter or underscore.' - ); - } - if (/^\./.test(this.input)) { - this.error( - 'INVALID_CLASS_NAME', - '"' + - /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + - '" is not a valid class name. Class names can only contain "_", "-", a-z and 0-9, and must contain at least one of "_", or a-z' - ); - } - }, - /** - * Text. - */ - endInterpolation: function() { - if (this.interpolated && this.input[0] === ']') { - this.input = this.input.substr(1); - this.ended = true; - return true; - } - }, - addText: function(type, value, prefix, escaped) { - var tok; - if (value + prefix === '') return; - prefix = prefix || ''; - escaped = escaped || 0; - var indexOfEnd = this.interpolated ? value.indexOf(']') : -1; - var indexOfStart = this.interpolationAllowed ? value.indexOf('#[') : -1; - var indexOfEscaped = this.interpolationAllowed ? value.indexOf('\\#[') : -1; - var matchOfStringInterp = /(\\)?([#!]){((?:.|\n)*)$/.exec(value); - var indexOfStringInterp = - this.interpolationAllowed && matchOfStringInterp - ? matchOfStringInterp.index - : Infinity; +/***/ }), - if (indexOfEnd === -1) indexOfEnd = Infinity; - if (indexOfStart === -1) indexOfStart = Infinity; - if (indexOfEscaped === -1) indexOfEscaped = Infinity; +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - indexOfEscaped !== Infinity && - indexOfEscaped < indexOfEnd && - indexOfEscaped < indexOfStart && - indexOfEscaped < indexOfStringInterp - ) { - prefix = prefix + value.substring(0, indexOfEscaped) + '#['; - return this.addText( - type, - value.substring(indexOfEscaped + 3), - prefix, - escaped + 1 - ); - } - if ( - indexOfStart !== Infinity && - indexOfStart < indexOfEnd && - indexOfStart < indexOfEscaped && - indexOfStart < indexOfStringInterp - ) { - tok = this.tok(type, prefix + value.substring(0, indexOfStart)); - this.incrementColumn(prefix.length + indexOfStart + escaped); - this.tokens.push(this.tokEnd(tok)); - tok = this.tok('start-pug-interpolation'); - this.incrementColumn(2); - this.tokens.push(this.tokEnd(tok)); - var child = new this.constructor(value.substr(indexOfStart + 2), { - filename: this.filename, - interpolated: true, - startingLine: this.lineno, - startingColumn: this.colno, - plugins: this.plugins, - }); - var interpolated; - try { - interpolated = child.getTokens(); - } catch (ex) { - if (ex.code && /^PUG:/.test(ex.code)) { - this.colno = ex.column; - this.error(ex.code.substr(4), ex.msg); - } - throw ex; - } - this.colno = child.colno; - this.tokens = this.tokens.concat(interpolated); - tok = this.tok('end-pug-interpolation'); - this.incrementColumn(1); - this.tokens.push(this.tokEnd(tok)); - this.addText(type, child.input); - return; - } - if ( - indexOfEnd !== Infinity && - indexOfEnd < indexOfStart && - indexOfEnd < indexOfEscaped && - indexOfEnd < indexOfStringInterp - ) { - if (prefix + value.substring(0, indexOfEnd)) { - this.addText(type, value.substring(0, indexOfEnd), prefix); - } - this.ended = true; - this.input = value.substr(value.indexOf(']') + 1) + this.input; - return; - } - if (indexOfStringInterp !== Infinity) { - if (matchOfStringInterp[1]) { - prefix = - prefix + - value.substring(0, indexOfStringInterp) + - matchOfStringInterp[2] + - '{'; - return this.addText( - type, - value.substring(indexOfStringInterp + 3), - prefix, - escaped + 1 - ); - } - var before = value.substr(0, indexOfStringInterp); - if (prefix || before) { - before = prefix + before; - tok = this.tok(type, before); - this.incrementColumn(before.length + escaped); - this.tokens.push(this.tokEnd(tok)); - } +var wrappy = __nccwpck_require__(62940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) - var rest = matchOfStringInterp[3]; - var range; - tok = this.tok('interpolated-code'); - this.incrementColumn(2); - try { - range = characterParser.parseUntil(rest, '}'); - } catch (ex) { - if (ex.index !== undefined) { - this.incrementColumn(ex.index); - } - if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { - this.error( - 'NO_END_BRACKET', - 'End of line was reached with no closing bracket for interpolation.' - ); - } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { - this.error('BRACKET_MISMATCH', ex.message); - } else { - throw ex; - } - } - tok.mustEscape = matchOfStringInterp[2] === '#'; - tok.buffer = true; - tok.val = range.src; - this.assertExpression(range.src); +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) - if (range.end + 1 < rest.length) { - rest = rest.substr(range.end + 1); - this.incrementColumn(range.end + 1); - this.tokens.push(this.tokEnd(tok)); - this.addText(type, rest); - } else { - this.incrementColumn(rest.length); - this.tokens.push(this.tokEnd(tok)); - } - return; - } + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - value = prefix + value; - tok = this.tok(type, value); - this.incrementColumn(value.length + escaped); - this.tokens.push(this.tokEnd(tok)); - }, +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} - text: function() { - var tok = - this.scan(/^(?:\| ?| )([^\n]+)/, 'text') || - this.scan(/^( )/, 'text') || - this.scan(/^\|( ?)/, 'text'); - if (tok) { - this.addText('text', tok.val); - return true; - } - }, +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - textHtml: function() { - var tok = this.scan(/^(<[^\n]*)/, 'text-html'); - if (tok) { - this.addText('text-html', tok.val); - return true; - } - }, - /** - * Dot. - */ +/***/ }), - dot: function() { - var tok; - if ((tok = this.scanEndOfLine(/^\./, 'dot'))) { - this.tokens.push(this.tokEnd(tok)); - this.callLexerFunction('pipelessText'); - return true; - } - }, +/***/ 89082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Extends. - */ +"use strict"; - extends: function() { - var tok = this.scan(/^extends?(?= |$|\n)/, 'extends'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - if (!this.callLexerFunction('path')) { - this.error('NO_EXTENDS_PATH', 'missing path for extends'); - } - return true; - } - if (this.scan(/^extends?\b/)) { - this.error('MALFORMED_EXTENDS', 'malformed extends'); - } - }, +const mimicFn = __nccwpck_require__(76047); - /** - * Block prepend. - */ +const calledFunctions = new WeakMap(); - prepend: function() { - var captures; - if ((captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input))) { - var name = captures[1].trim(); - var comment = ''; - if (name.indexOf('//') !== -1) { - comment = - '//' + - name - .split('//') - .slice(1) - .join('//'); - name = name.split('//')[0].trim(); - } - if (!name) return; - var tok = this.tok('block', name); - var len = captures[0].length - comment.length; - while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; - this.incrementColumn(len); - tok.mode = 'prepend'; - this.tokens.push(this.tokEnd(tok)); - this.consume(captures[0].length - comment.length); - this.incrementColumn(captures[0].length - comment.length - len); - return true; - } - }, +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } - /** - * Block append. - */ + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; - append: function() { - var captures; - if ((captures = /^(?:block +)?append +([^\n]+)/.exec(this.input))) { - var name = captures[1].trim(); - var comment = ''; - if (name.indexOf('//') !== -1) { - comment = - '//' + - name - .split('//') - .slice(1) - .join('//'); - name = name.split('//')[0].trim(); - } - if (!name) return; - var tok = this.tok('block', name); - var len = captures[0].length - comment.length; - while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; - this.incrementColumn(len); - tok.mode = 'append'; - this.tokens.push(this.tokEnd(tok)); - this.consume(captures[0].length - comment.length); - this.incrementColumn(captures[0].length - comment.length - len); - return true; - } - }, + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); - /** - * Block. - */ + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } - block: function() { - var captures; - if ((captures = /^block +([^\n]+)/.exec(this.input))) { - var name = captures[1].trim(); - var comment = ''; - if (name.indexOf('//') !== -1) { - comment = - '//' + - name - .split('//') - .slice(1) - .join('//'); - name = name.split('//')[0].trim(); - } - if (!name) return; - var tok = this.tok('block', name); - var len = captures[0].length - comment.length; - while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; - this.incrementColumn(len); - tok.mode = 'replace'; - this.tokens.push(this.tokEnd(tok)); - this.consume(captures[0].length - comment.length); - this.incrementColumn(captures[0].length - comment.length - len); - return true; - } - }, + return returnValue; + }; - /** - * Mixin Block. - */ + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); - mixinBlock: function() { - var tok; - if ((tok = this.scanEndOfLine(/^block/, 'mixin-block'))) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, + return onetime; +}; - /** - * Yield. - */ +module.exports = onetime; +// TODO: Remove this for the next major release +module.exports["default"] = onetime; - yield: function() { - var tok = this.scanEndOfLine(/^yield/, 'yield'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +module.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } - /** - * Include. - */ + return calledFunctions.get(function_); +}; - include: function() { - var tok = this.scan(/^include(?=:| |$|\n)/, 'include'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - while (this.callLexerFunction('filter', {inInclude: true})); - if (!this.callLexerFunction('path')) { - if (/^[^ \n]+/.test(this.input)) { - // if there is more text - this.fail(); - } else { - // if not - this.error('NO_INCLUDE_PATH', 'missing path for include'); - } - } - return true; - } - if (this.scan(/^include\b/)) { - this.error('MALFORMED_INCLUDE', 'malformed include'); - } - }, - /** - * Path - */ +/***/ }), - path: function() { - var tok = this.scanEndOfLine(/^ ([^\n]+)/, 'path'); - if (tok && (tok.val = tok.val.trim())) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +/***/ 20539: +/***/ ((module) => { - /** - * Case. - */ +"use strict"; - case: function() { - var tok = this.scanEndOfLine(/^case +([^\n]+)/, 'case'); - if (tok) { - this.incrementColumn(-tok.val.length); - this.assertExpression(tok.val); - this.incrementColumn(tok.val.length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - if (this.scan(/^case\b/)) { - this.error('NO_CASE_EXPRESSION', 'missing expression for case'); - } - }, - /** - * When. - */ +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; - when: function() { - var tok = this.scanEndOfLine(/^when +([^:\n]+)/, 'when'); - if (tok) { - var parser = characterParser(tok.val); - while (parser.isNesting() || parser.isString()) { - var rest = /:([^:\n]+)/.exec(this.input); - if (!rest) break; + if (platform !== 'win32') { + return 'PATH'; + } - tok.val += rest[0]; - this.consume(rest[0].length); - this.incrementColumn(rest[0].length); - parser = characterParser(tok.val); - } + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; - this.incrementColumn(-tok.val.length); - this.assertExpression(tok.val); - this.incrementColumn(tok.val.length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - if (this.scan(/^when\b/)) { - this.error('NO_WHEN_EXPRESSION', 'missing expression for when'); - } - }, +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports["default"] = pathKey; - /** - * Default. - */ - default: function() { - var tok = this.scanEndOfLine(/^default/, 'default'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - if (this.scan(/^default\b/)) { - this.error( - 'DEFAULT_WITH_EXPRESSION', - 'default should not have an expression' - ); - } - }, +/***/ }), - /** - * Call mixin. - */ +/***/ 5980: +/***/ ((module) => { - call: function() { - var tok, captures, increment; - if ((captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input))) { - // try to consume simple or interpolated call - if (captures[3]) { - // simple call - increment = captures[0].length; - this.consume(increment); - tok = this.tok('call', captures[3]); - } else { - // interpolated call - var match = this.bracketExpression(2 + captures[1].length); - increment = match.end + 1; - this.consume(increment); - this.assertExpression(match.src); - tok = this.tok('call', '#{' + match.src + '}'); - } +"use strict"; - this.incrementColumn(increment); - tok.args = null; - // Check for args (not attributes) - if ((captures = /^ *\(/.exec(this.input))) { - var range = this.bracketExpression(captures[0].length - 1); - if (!/^\s*[-\w]+ *=/.test(range.src)) { - // not attributes - this.incrementColumn(1); - this.consume(range.end + 1); - tok.args = range.src; - this.assertExpression('[' + tok.args + ']'); - for (var i = 0; i <= tok.args.length; i++) { - if (tok.args[i] === '\n') { - this.incrementLine(1); - } else { - this.incrementColumn(1); - } - } - } - } - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +var isWindows = process.platform === 'win32'; - /** - * Mixin. - */ +// Regex to split a windows path into into [dir, root, basename, name, ext] +var splitWindowsRe = + /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; - mixin: function() { - var captures; - if ((captures = /^mixin +([-\w]+)(?: *\((.*)\))? */.exec(this.input))) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2] || null; - this.incrementColumn(captures[0].length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +var win32 = {}; - /** - * Conditional. - */ +function win32SplitPath(filename) { + return splitWindowsRe.exec(filename).slice(1); +} - conditional: function() { - var captures; - if ((captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input))) { - this.consume(captures[0].length); - var type = captures[1].replace(/ /g, '-'); - var js = captures[2] && captures[2].trim(); - // type can be "if", "else-if" and "else" - var tok = this.tok(type, js); - this.incrementColumn(captures[0].length - js.length); +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[1], + dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3] + }; +}; - switch (type) { - case 'if': - case 'else-if': - this.assertExpression(js); - break; - case 'unless': - this.assertExpression(js); - tok.val = '!(' + js + ')'; - tok.type = 'if'; - break; - case 'else': - if (js) { - this.error( - 'ELSE_CONDITION', - '`else` cannot have a condition, perhaps you meant `else if`' - ); - } - break; - } - this.incrementColumn(js.length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, - /** - * While. - */ - while: function() { - var captures, tok; - if ((captures = /^while +([^\n]+)/.exec(this.input))) { - this.consume(captures[0].length); - this.assertExpression(captures[1]); - tok = this.tok('while', captures[1]); - this.incrementColumn(captures[0].length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - if (this.scan(/^while\b/)) { - this.error('NO_WHILE_EXPRESSION', 'missing expression for while'); - } - }, +// Split a filename into [dir, root, basename, name, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; +var posix = {}; - /** - * Each. - */ - each: function() { - var captures; - if ( - (captures = /^(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec( - this.input - )) - ) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || null; - this.incrementColumn(captures[0].length - captures[3].length); - this.assertExpression(captures[3]); - tok.code = captures[3]; - this.incrementColumn(captures[3].length); - this.tokens.push(this.tokEnd(tok)); - return true; - } - const name = /^each\b/.exec(this.input) ? 'each' : 'for'; - if (this.scan(/^(?:each|for)\b/)) { - this.error( - 'MALFORMED_EACH', - 'This `' + - name + - '` has a syntax error. `' + - name + - '` statements should be of the form: `' + - name + - ' VARIABLE_NAME of JS_EXPRESSION`' - ); - } - if ( - (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +in +([^\n]+)/.exec( - this.input - )) - ) { - this.error( - 'MALFORMED_EACH', - 'Pug each and for should no longer be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.' - ); - } - }, +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); +} - /** - * EachOf. - */ - eachOf: function() { - var captures; - if ((captures = /^(?:each|for) (.*?) of *([^\n]+)/.exec(this.input))) { - this.consume(captures[0].length); - var tok = this.tok('eachOf', captures[1]); - tok.value = captures[1]; - this.incrementColumn(captures[0].length - captures[2].length); - this.assertExpression(captures[2]); - tok.code = captures[2]; - this.incrementColumn(captures[2].length); - this.tokens.push(this.tokEnd(tok)); +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[1], + dir: allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3], + }; +}; - if ( - !( - /^[a-zA-Z_$][\w$]*$/.test(tok.value.trim()) || - /^\[ *[a-zA-Z_$][\w$]* *\, *[a-zA-Z_$][\w$]* *\]$/.test( - tok.value.trim() - ) - ) - ) { - this.error( - 'MALFORMED_EACH_OF_LVAL', - 'The value variable for each must either be a valid identifier (e.g. `item`) or a pair of identifiers in square brackets (e.g. `[key, value]`).' - ); - } - return true; - } - if ( - (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +of +([^\n]+)/.exec( - this.input - )) - ) { - this.error( - 'MALFORMED_EACH', - 'Pug each and for should not be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.' - ); - } - }, +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; - /** - * Code. - */ +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; - code: function() { - var captures; - if ((captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input))) { - var flags = captures[1]; - var code = captures[2]; - var shortened = 0; - if (this.interpolated) { - var parsed; - try { - parsed = characterParser.parseUntil(code, ']'); - } catch (err) { - if (err.index !== undefined) { - this.incrementColumn(captures[0].length - code.length + err.index); - } - if (err.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { - this.error( - 'NO_END_BRACKET', - 'End of line was reached with no closing bracket for interpolation.' - ); - } else if (err.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { - this.error('BRACKET_MISMATCH', err.message); - } else { - throw err; - } - } - shortened = code.length - parsed.end; - code = parsed.src; - } - var consumed = captures[0].length - shortened; - this.consume(consumed); - var tok = this.tok('code', code); - tok.mustEscape = flags.charAt(0) === '='; - tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '='; - // p #[!= abc] hey - // ^ original colno - // -------------- captures[0] - // -------- captures[2] - // ------ captures[0] - captures[2] - // ^ after colno +/***/ }), - // = abc - // ^ original colno - // ------- captures[0] - // --- captures[2] - // ---- captures[0] - captures[2] - // ^ after colno - this.incrementColumn(captures[0].length - captures[2].length); - if (tok.buffer) this.assertExpression(code); - this.tokens.push(tok); +/***/ 78569: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // p #[!= abc] hey - // ^ original colno - // ----- shortened - // --- code - // ^ after colno +"use strict"; - // = abc - // ^ original colno - // shortened - // --- code - // ^ after colno - this.incrementColumn(code.length); - this.tokEnd(tok); - return true; - } - }, - /** - * Block code. - */ - blockCode: function() { - var tok; - if ((tok = this.scanEndOfLine(/^-/, 'blockcode'))) { - this.tokens.push(this.tokEnd(tok)); - this.interpolationAllowed = false; - this.callLexerFunction('pipelessText'); - return true; - } - }, +module.exports = __nccwpck_require__(33322); - /** - * Attribute Name. - */ - attribute: function(str) { - var quote = ''; - var quoteRe = /['"]/; - var key = ''; - var i; - // consume all whitespace before the key - for (i = 0; i < str.length; i++) { - if (!this.whitespaceRe.test(str[i])) break; - if (str[i] === '\n') { - this.incrementLine(1); - } else { - this.incrementColumn(1); - } - } +/***/ }), - if (i === str.length) { - return ''; - } +/***/ 16099: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var tok = this.tok('attribute'); +"use strict"; - // quote? - if (quoteRe.test(str[i])) { - quote = str[i]; - this.incrementColumn(1); - i++; - } - // start looping through the key - for (; i < str.length; i++) { - if (quote) { - if (str[i] === quote) { - this.incrementColumn(1); - i++; - break; - } - } else { - if ( - this.whitespaceRe.test(str[i]) || - str[i] === '!' || - str[i] === '=' || - str[i] === ',' - ) { - break; - } - } +const path = __nccwpck_require__(71017); +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; - key += str[i]; +/** + * Posix glob regex + */ - if (str[i] === '\n') { - this.incrementLine(1); - } else { - this.incrementColumn(1); - } - } +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; - tok.name = key; +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; - var valueResponse = this.attributeValue(str.substr(i)); +/** + * Windows glob regex + */ - if (valueResponse.val) { - tok.val = valueResponse.val; - tok.mustEscape = valueResponse.mustEscape; - } else { - // was a boolean attribute (ex: `input(disabled)`) - tok.val = true; - tok.mustEscape = true; - } +const WINDOWS_CHARS = { + ...POSIX_CHARS, - str = valueResponse.remainingSource; + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; - this.tokens.push(this.tokEnd(tok)); +/** + * POSIX Bracket Regex + */ - for (i = 0; i < str.length; i++) { - if (!this.whitespaceRe.test(str[i])) { - break; - } - if (str[i] === '\n') { - this.incrementLine(1); - } else { - this.incrementColumn(1); - } - } +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; - if (str[i] === ',') { - this.incrementColumn(1); - i++; - } +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, - return str.substr(i); + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' }, - /** - * Attribute Value. - */ - attributeValue: function(str) { - var quoteRe = /['"]/; - var val = ''; - var done, i, x; - var escapeAttr = true; - var state = characterParser.defaultState(); - var col = this.colno; - var line = this.lineno; + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ - // consume all whitespace before the equals sign - for (i = 0; i < str.length; i++) { - if (!this.whitespaceRe.test(str[i])) break; - if (str[i] === '\n') { - line++; - col = 1; - } else { - col++; - } - } + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ - if (i === str.length) { - return {remainingSource: str}; - } + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ - if (str[i] === '!') { - escapeAttr = false; - col++; - i++; - if (str[i] !== '=') - this.error( - 'INVALID_KEY_CHARACTER', - 'Unexpected character ' + str[i] + ' expected `=`' - ); - } + CHAR_ASTERISK: 42, /* * */ - if (str[i] !== '=') { - // check for anti-pattern `div("foo"bar)` - if (i === 0 && str && !this.whitespaceRe.test(str[0]) && str[0] !== ',') { - this.error( - 'INVALID_KEY_CHARACTER', - 'Unexpected character ' + str[0] + ' expected `=`' - ); - } else { - return {remainingSource: str}; - } - } + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ - this.lineno = line; - this.colno = col + 1; - i++; + SEP: path.sep, - // consume all whitespace before the value - for (; i < str.length; i++) { - if (!this.whitespaceRe.test(str[i])) break; - if (str[i] === '\n') { - this.incrementLine(1); - } else { - this.incrementColumn(1); - } - } + /** + * Create EXTGLOB_CHARS + */ - line = this.lineno; - col = this.colno; + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, - // start looping through the value - for (; i < str.length; i++) { - // if the character is in a string or in parentheses/brackets/braces - if (!(state.isNesting() || state.isString())) { - if (this.whitespaceRe.test(str[i])) { - done = false; + /** + * Create GLOB_CHARS + */ - // find the first non-whitespace character - for (x = i; x < str.length; x++) { - if (!this.whitespaceRe.test(str[x])) { - // if it is a JavaScript punctuator, then assume that it is - // a part of the value - const isNotPunctuator = !characterParser.isPunctuator(str[x]); - const isQuote = quoteRe.test(str[x]); - const isColon = str[x] === ':'; - const isSpreadOperator = - str[x] + str[x + 1] + str[x + 2] === '...'; - if ( - (isNotPunctuator || isQuote || isColon || isSpreadOperator) && - this.assertExpression(val, true) - ) { - done = true; - } - break; - } - } + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; - // if everything else is whitespace, return now so last attribute - // does not include trailing whitespace - if (done || x === str.length) { - break; - } - } - // if there's no whitespace and the character is not ',', the - // attribute did not end. - if (str[i] === ',' && this.assertExpression(val, true)) { - break; - } - } +/***/ }), + +/***/ 92139: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + - state = characterParser.parseChar(str[i], state); - val += str[i]; +const constants = __nccwpck_require__(16099); +const utils = __nccwpck_require__(30479); - if (str[i] === '\n') { - line++; - col = 1; - } else { - col++; - } - } +/** + * Constants + */ - this.assertExpression(val); +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; - this.lineno = line; - this.colno = col; +/** + * Helpers + */ - return {val: val, mustEscape: escapeAttr, remainingSource: str.substr(i)}; - }, +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } - /** - * Attributes. - */ + args.sort(); + const value = `[${args.join('-')}]`; - attrs: function() { - var tok; + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } - if ('(' == this.input.charAt(0)) { - tok = this.tok('start-attributes'); - var index = this.bracketExpression().end; - var str = this.input.substr(1, index - 1); + return value; +}; - this.incrementColumn(1); - this.tokens.push(this.tokEnd(tok)); - this.assertNestingCorrect(str); - this.consume(index + 1); +/** + * Create the message for a syntax error + */ - while (str) { - str = this.attribute(str); - } +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; - tok = this.tok('end-attributes'); - this.incrementColumn(1); - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ - /** - * &attributes block - */ - attributesBlock: function() { - if (/^&attributes\b/.test(this.input)) { - var consumed = 11; - this.consume(consumed); - var tok = this.tok('&attributes'); - this.incrementColumn(consumed); - var args = this.bracketExpression(); - consumed = args.end + 1; - this.consume(consumed); - tok.val = args.src; - this.incrementColumn(consumed); - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } - /** - * Indent | Outdent | Newline. - */ + input = REPLACEMENTS[input] || input; - indent: function() { - var captures = this.scanIndentation(); - var tok; + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - if (captures) { - var indents = captures[1].length; + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } - this.incrementLine(1); - this.consume(indents + 1); + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; - if (' ' == this.input[0] || '\t' == this.input[0]) { - this.error( - 'INVALID_INDENTATION', - 'Invalid indentation, you can use tabs or spaces but not both' - ); - } + const capture = opts.capture ? '' : '?:'; + const win32 = utils.isWindows(options); - // blank line - if ('\n' == this.input[0]) { - this.interpolationAllowed = true; - return this.tokEnd(this.tok('newline')); - } + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); - // outdent - if (indents < this.indentStack[0]) { - var outdent_count = 0; - while (this.indentStack[0] > indents) { - if (this.indentStack[1] < indents) { - this.error( - 'INCONSISTENT_INDENTATION', - 'Inconsistent indentation. Expecting either ' + - this.indentStack[1] + - ' or ' + - this.indentStack[0] + - ' spaces/tabs.' - ); - } - outdent_count++; - this.indentStack.shift(); - } - while (outdent_count--) { - this.colno = 1; - tok = this.tok('outdent'); - this.colno = this.indentStack[0] + 1; - this.tokens.push(this.tokEnd(tok)); - } - // indent - } else if (indents && indents != this.indentStack[0]) { - tok = this.tok('indent', indents); - this.colno = 1 + indents; - this.tokens.push(this.tokEnd(tok)); - this.indentStack.unshift(indents); - // newline - } else { - tok = this.tok('newline'); - this.colno = 1 + Math.min(this.indentStack[0] || 0, indents); - this.tokens.push(this.tokEnd(tok)); - } + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; - this.interpolationAllowed = true; - return true; - } - }, + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; - pipelessText: function pipelessText(indents) { - while (this.callLexerFunction('blank')); + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; - var captures = this.scanIndentation(); + if (opts.capture) { + star = `(${star})`; + } - indents = indents || (captures && captures[1].length); - if (indents > this.indentStack[0]) { - this.tokens.push(this.tokEnd(this.tok('start-pipeless-text'))); - var tokens = []; - var token_indent = []; - var isMatch; - // Index in this.input. Can't use this.consume because we might need to - // retry lexing the block. - var stringPtr = 0; - do { - // text has `\n` as a prefix - var i = this.input.substr(stringPtr + 1).indexOf('\n'); - if (-1 == i) i = this.input.length - stringPtr - 1; - var str = this.input.substr(stringPtr + 1, i); - var lineCaptures = this.indentRe.exec('\n' + str); - var lineIndents = lineCaptures && lineCaptures[1].length; - isMatch = lineIndents >= indents; - token_indent.push(isMatch); - isMatch = isMatch || !str.trim(); - if (isMatch) { - // consume test along with `\n` prefix if match - stringPtr += str.length + 1; - tokens.push(str.substr(indents)); - } else if (lineIndents > this.indentStack[0]) { - // line is indented less than the first line but is still indented - // need to retry lexing the text block - this.tokens.pop(); - return pipelessText.call(this, lineCaptures[1].length); - } - } while (this.input.length - stringPtr && isMatch); - this.consume(stringPtr); - while (this.input.length === 0 && tokens[tokens.length - 1] === '') - tokens.pop(); - tokens.forEach( - function(token, i) { - var tok; - this.incrementLine(1); - if (i !== 0) tok = this.tok('newline'); - if (token_indent[i]) this.incrementColumn(indents); - if (tok) this.tokens.push(this.tokEnd(tok)); - this.addText('text', token); - }.bind(this) - ); - this.tokens.push(this.tokEnd(this.tok('end-pipeless-text'))); - return true; - } - }, + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } - /** - * Slash. - */ + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; - slash: function() { - var tok = this.scan(/^\//, 'slash'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, + input = utils.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; /** - * ':' + * Tokenizing helpers */ - colon: function() { - var tok = this.scan(/^: +/, ':'); - if (tok) { - this.tokens.push(this.tokEnd(tok)); - return true; - } - }, + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; - fail: function() { - this.error( - 'UNEXPECTED_TEXT', - 'unexpected text "' + this.input.substr(0, 5) + '"' - ); - }, + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; - callLexerFunction: function(func) { - var rest = []; - for (var i = 1; i < arguments.length; i++) { - rest.push(arguments[i]); + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; } - var pluginArgs = [this].concat(rest); - for (var i = 0; i < this.plugins.length; i++) { - var plugin = this.plugins[i]; - if (plugin[func] && plugin[func].apply(plugin, pluginArgs)) { - return true; - } + + if (count % 2 === 0) { + return false; } - return this[func].apply(this, rest); - }, - /** - * Move to the next token - * - * @api private - */ + state.negated = true; + state.start++; + return true; + }; - advance: function() { - return ( - this.callLexerFunction('blank') || - this.callLexerFunction('eos') || - this.callLexerFunction('endInterpolation') || - this.callLexerFunction('yield') || - this.callLexerFunction('doctype') || - this.callLexerFunction('interpolation') || - this.callLexerFunction('case') || - this.callLexerFunction('when') || - this.callLexerFunction('default') || - this.callLexerFunction('extends') || - this.callLexerFunction('append') || - this.callLexerFunction('prepend') || - this.callLexerFunction('block') || - this.callLexerFunction('mixinBlock') || - this.callLexerFunction('include') || - this.callLexerFunction('mixin') || - this.callLexerFunction('call') || - this.callLexerFunction('conditional') || - this.callLexerFunction('eachOf') || - this.callLexerFunction('each') || - this.callLexerFunction('while') || - this.callLexerFunction('tag') || - this.callLexerFunction('filter') || - this.callLexerFunction('blockCode') || - this.callLexerFunction('code') || - this.callLexerFunction('id') || - this.callLexerFunction('dot') || - this.callLexerFunction('className') || - this.callLexerFunction('attrs') || - this.callLexerFunction('attributesBlock') || - this.callLexerFunction('indent') || - this.callLexerFunction('text') || - this.callLexerFunction('textHtml') || - this.callLexerFunction('comment') || - this.callLexerFunction('slash') || - this.callLexerFunction('colon') || - this.fail() - ); - }, + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; /** - * Return an array of tokens for the current file - * - * @returns {Array.} - * @api public + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. */ - getTokens: function() { - while (!this.ended) { - this.callLexerFunction('advance'); + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } } - return this.tokens; - }, -}; + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } -/***/ }), + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } -/***/ 63234: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; -"use strict"; + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; -var assert = __nccwpck_require__(39491); -var walk = __nccwpck_require__(60283); + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; -function error() { - throw (__nccwpck_require__(11449).apply)(null, arguments); -} + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; -module.exports = link; -function link(ast) { - assert( - ast.type === 'Block', - 'The top level element should always be a block' - ); - var extendsNode = null; - if (ast.nodes.length) { - var hasExtends = ast.nodes[0].type === 'Extends'; - checkExtendPosition(ast, hasExtends); - if (hasExtends) { - extendsNode = ast.nodes.shift(); - } - } - ast = applyIncludes(ast); - ast.declaredBlocks = findDeclaredBlocks(ast); - if (extendsNode) { - var mixins = []; - var expectedBlocks = []; - ast.nodes.forEach(function addNode(node) { - if (node.type === 'NamedBlock') { - expectedBlocks.push(node); - } else if (node.type === 'Block') { - node.nodes.forEach(addNode); - } else if (node.type === 'Mixin' && node.call === false) { - mixins.push(node); - } else { - error( - 'UNEXPECTED_NODES_IN_EXTENDING_ROOT', - 'Only named blocks and mixins can appear at the top level of an extending template', - node - ); + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); } - }); - var parent = link(extendsNode.file.ast); - extend(parent.declaredBlocks, ast); - var foundBlockNames = []; - walk(parent, function(node) { - if (node.type === 'NamedBlock') { - foundBlockNames.push(node.name); + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; } - }); - expectedBlocks.forEach(function(expectedBlock) { - if (foundBlockNames.indexOf(expectedBlock.name) === -1) { - error( - 'UNEXPECTED_BLOCK', - 'Unexpected block ' + expectedBlock.name, - expectedBlock - ); + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; } - }); - Object.keys(ast.declaredBlocks).forEach(function(name) { - parent.declaredBlocks[name] = ast.declaredBlocks[name]; - }); - parent.nodes = mixins.concat(parent.nodes); - parent.hasExtends = true; - return parent; - } - return ast; -} -function findDeclaredBlocks(ast) /*: {[name: string]: Array}*/ { - var definitions = {}; - walk(ast, function before(node) { - if (node.type === 'NamedBlock' && node.mode === 'replace') { - definitions[node.name] = definitions[node.name] || []; - definitions[node.name].push(node); + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } } - }); - return definitions; -} -function flattenParentBlocks(parentBlocks, accumulator) { - accumulator = accumulator || []; - parentBlocks.forEach(function(parentBlock) { - if (parentBlock.parents) { - flattenParentBlocks(parentBlock.parents, accumulator); - } - accumulator.push(parentBlock); - }); - return accumulator; -} + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; -function extend(parentBlocks, ast) { - var stack = {}; - walk( - ast, - function before(node) { - if (node.type === 'NamedBlock') { - if (stack[node.name] === node.name) { - return (node.ignore = true); + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } - stack[node.name] = node.name; - var parentBlockList = parentBlocks[node.name] - ? flattenParentBlocks(parentBlocks[node.name]) - : []; - if (parentBlockList.length) { - node.parents = parentBlockList; - parentBlockList.forEach(function(parentBlock) { - switch (node.mode) { - case 'append': - parentBlock.nodes = parentBlock.nodes.concat(node.nodes); - break; - case 'prepend': - parentBlock.nodes = node.nodes.concat(parentBlock.nodes); - break; - case 'replace': - parentBlock.nodes = node.nodes; - break; - } - }); + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } + return QMARK.repeat(chars.length); } - }, - function after(node) { - if (node.type === 'NamedBlock' && !node.ignore) { - delete stack[node.name]; - } - } - ); -} -function applyIncludes(ast, child) { - return walk( - ast, - function before(node, replace) { - if (node.type === 'RawInclude') { - replace({type: 'Text', val: node.file.str.replace(/\r/g, '')}); + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); } - }, - function after(node, replace) { - if (node.type === 'Include') { - var childAST = link(node.file.ast); - if (childAST.hasExtends) { - childAST = removeBlocks(childAST); + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); } - replace(applyYield(childAST, node.block)); + return star; } - } - ); -} -function removeBlocks(ast) { - return walk(ast, function(node, replace) { - if (node.type === 'NamedBlock') { - replace({ - type: 'Block', - nodes: node.nodes, - }); - } - }); -} + return esc ? m : `\\${m}`; + }); -function applyYield(ast, block) { - if (!block || !block.nodes.length) return ast; - var replaced = false; - ast = walk(ast, null, function(node, replace) { - if (node.type === 'YieldBlock') { - replaced = true; - node.type = 'Block'; - node.nodes = [block]; - } - }); - function defaultYieldLocation(node) { - var res = node; - for (var i = 0; i < node.nodes.length; i++) { - if (node.nodes[i].textOnly) continue; - if (node.nodes[i].type === 'Block') { - res = defaultYieldLocation(node.nodes[i]); - } else if (node.nodes[i].block && node.nodes[i].block.nodes.length) { - res = defaultYieldLocation(node.nodes[i].block); + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); } } - return res; - } - if (!replaced) { - // todo: probably should deprecate this with a warning - defaultYieldLocation(ast).nodes.push(block); + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils.wrapOutput(output, state, options); + return state; } - return ast; -} -function checkExtendPosition(ast, hasExtends) { - var legitExtendsReached = false; - walk(ast, function(node) { - if (node.type === 'Extends') { - if (hasExtends && !legitExtendsReached) { - legitExtendsReached = true; - } else { - error( - 'EXTENDS_NOT_FIRST', - 'Declaration of template inheritance ("extends") should be the first thing in the file. There can only be one extends statement per file.', - node - ); - } + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; } - }); -} + /** + * Escaped characters + */ -/***/ }), + if (value === '\\') { + const next = peek(); -/***/ 44254: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (next === '/' && opts.bash !== true) { + continue; + } -"use strict"; + if (next === '.' || next === ';') { + continue; + } + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var walk = __nccwpck_require__(60283); -var assign = __nccwpck_require__(17426); + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; -module.exports = load; -function load(ast, options) { - options = getOptions(options); - // clone the ast - ast = JSON.parse(JSON.stringify(ast)); - return walk(ast, function(node) { - if (node.str === undefined) { - if ( - node.type === 'Include' || - node.type === 'RawInclude' || - node.type === 'Extends' - ) { - var file = node.file; - if (file.type !== 'FileReference') { - throw new Error('Expected file.type to be "FileReference"'); - } - var path, str, raw; - try { - path = options.resolve(file.path, file.filename, options); - file.fullPath = path; - raw = options.read(path, options); - str = raw.toString('utf8'); - } catch (ex) { - ex.message += '\n at ' + node.filename + ' line ' + node.line; - throw ex; - } - file.str = str; - file.raw = raw; - if (node.type === 'Extends' || node.type === 'Include') { - file.ast = load.string( - str, - assign({}, options, { - filename: path, - }) - ); + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; } } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } } - }); -} -load.string = function loadString(src, options) { - options = assign(getOptions(options), { - src: src, - }); - var tokens = options.lex(src, options); - var ast = options.parse(tokens, options); - return load(ast, options); -}; -load.file = function loadFile(filename, options) { - options = assign(getOptions(options), { - filename: filename, - }); - var str = options.read(filename).toString('utf8'); - return load.string(str, options); -}; + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ -load.resolve = function resolve(filename, source, options) { - filename = filename.trim(); - if (filename[0] !== '/' && !source) - throw new Error( - 'the "filename" option is required to use includes and extends with "relative" paths' - ); + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; - if (filename[0] === '/' && !options.basedir) - throw new Error( - 'the "basedir" option is required to use includes and extends with "absolute" paths' - ); + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); - filename = path.join( - filename[0] === '/' ? options.basedir : path.dirname(source.trim()), - filename - ); + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } - return filename; -}; -load.read = function read(filename, options) { - return fs.readFileSync(filename); -}; + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } -load.validateOptions = function validateOptions(options) { - /* istanbul ignore if */ - if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } - /* istanbul ignore if */ - if (typeof options.lex !== 'function') { - throw new TypeError('options.lex must be a function'); - } - /* istanbul ignore if */ - if (typeof options.parse !== 'function') { - throw new TypeError('options.parse must be a function'); - } - /* istanbul ignore if */ - if (options.resolve && typeof options.resolve !== 'function') { - throw new TypeError('options.resolve must be a function'); - } - /* istanbul ignore if */ - if (options.read && typeof options.read !== 'function') { - throw new TypeError('options.read must be a function'); - } -}; + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } -function getOptions(options) { - load.validateOptions(options); - return assign( - { - resolve: load.resolve, - read: load.read, - }, - options - ); -} + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + prev.value += value; + append({ value }); + continue; + } -/***/ }), + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ -/***/ 40558: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } -"use strict"; + /** + * Double quotes + */ + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } -var assert = __nccwpck_require__(39491); -var TokenStream = __nccwpck_require__(68758); -var error = __nccwpck_require__(11449); -var inlineTags = __nccwpck_require__(33470); + /** + * Parentheses + */ -module.exports = parse; -module.exports.Parser = Parser; -function parse(tokens, options) { - var parser = new Parser(tokens, options); - var ast = parser.parse(); - return JSON.parse(JSON.stringify(ast)); -} + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } -function Parser(tokens, options) { - options = options || {}; - if (!Array.isArray(tokens)) { - throw new Error( - 'Expected tokens to be an Array but got "' + typeof tokens + '"' - ); - } - if (typeof options !== 'object') { - throw new Error( - 'Expected "options" to be an object but got "' + typeof options + '"' - ); - } - this.tokens = new TokenStream(tokens); - this.filename = options.filename; - this.src = options.src; - this.inMixin = 0; - this.plugins = options.plugins || []; -} + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } -/** - * Parser prototype. - */ + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } -Parser.prototype = { - /** - * Save original constructor - */ + /** + * Square brackets + */ - constructor: Parser, + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } - error: function(code, message, token) { - var err = error(code, message, { - line: token.loc.start.line, - column: token.loc.start.column, - filename: this.filename, - src: this.src, - }); - throw err; - }, + value = `\\${value}`; + } else { + increment('brackets'); + } - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ + push({ type: 'bracket', value }); + continue; + } - advance: function() { - return this.tokens.advance(); - }, + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ + push({ type: 'text', value, output: `\\${value}` }); + continue; + } - peek: function() { - return this.tokens.peek(); - }, + decrement('brackets'); - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } - lookahead: function(n) { - return this.tokens.lookahead(n); - }, + prev.value += value; + append({ value }); - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } - parse: function() { - var block = this.emptyBlock(0); + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else if ('text-html' == this.peek().type) { - block.nodes = block.nodes.concat(this.parseTextHtml()); - } else { - var expr = this.parseExpr(); - if (expr) { - if (expr.type === 'Block') { - block.nodes = block.nodes.concat(expr.nodes); - } else { - block.nodes.push(expr); - } - } + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; } - return block; - }, + /** + * Braces + */ - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ + if (value === '{' && opts.nobrace !== true) { + increment('braces'); - expect: function(type) { - if (this.peek().type === type) { - return this.advance(); - } else { - this.error( - 'INVALID_TOKEN', - 'expected "' + type + '", but got "' + this.peek().type + '"', - this.peek() - ); + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; } - }, - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ + if (value === '}') { + const brace = braces[braces.length - 1]; - accept: function(type) { - if (this.peek().type === type) { - return this.advance(); - } - }, + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } - initBlock: function(line, nodes) { - /* istanbul ignore if */ - if ((line | 0) !== line) throw new Error('`line` is not an integer'); - /* istanbul ignore if */ - if (!Array.isArray(nodes)) throw new Error('`nodes` is not an array'); - return { - type: 'Block', - nodes: nodes, - line: line, - filename: this.filename, - }; - }, + let output = ')'; - emptyBlock: function(line) { - return this.initBlock(line, []); - }, + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; - runPlugin: function(context, tok) { - var rest = [this]; - for (var i = 2; i < arguments.length; i++) { - rest.push(arguments[i]); - } - var pluginContext; - for (var i = 0; i < this.plugins.length; i++) { - var plugin = this.plugins[i]; - if (plugin[context] && plugin[context][tok.type]) { - if (pluginContext) - throw new Error( - 'Multiple plugin handlers found for context ' + - JSON.stringify(context) + - ', token type ' + - JSON.stringify(tok.type) - ); - pluginContext = plugin[context]; + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; } - } - if (pluginContext) - return pluginContext[tok.type].apply(pluginContext, rest); - }, - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | text-html - * | dot - * | each - * | code - * | yield - * | id - * | class - * | interpolation - */ + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } - parseExpr: function() { - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'mixin-block': - return this.parseMixinBlock(); - case 'case': - return this.parseCase(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - case 'interpolated-code': - case 'start-pug-interpolation': - return this.parseText({block: true}); - case 'text-html': - return this.initBlock(this.peek().loc.start.line, this.parseTextHtml()); - case 'dot': - return this.parseDot(); - case 'each': - return this.parseEach(); - case 'eachOf': - return this.parseEachOf(); - case 'code': - return this.parseCode(); - case 'blockcode': - return this.parseBlockCode(); - case 'if': - return this.parseConditional(); - case 'while': - return this.parseWhile(); - case 'call': - return this.parseCall(); - case 'interpolation': - return this.parseInterpolation(); - case 'yield': - return this.parseYield(); - case 'id': - case 'class': - if (!this.peek().loc.start) debugger; - this.tokens.defer({ - type: 'tag', - val: 'div', - loc: this.peek().loc, - filename: this.filename, - }); - return this.parseExpr(); - default: - var pluginResult = this.runPlugin('expressionTokens', this.peek()); - if (pluginResult) return pluginResult; - this.error( - 'INVALID_TOKEN', - 'unexpected token "' + this.peek().type + '"', - this.peek() - ); + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; } - }, - - parseDot: function() { - this.advance(); - return this.parseTextBlock(); - }, - /** - * Text - */ + /** + * Pipes + */ - parseText: function(options) { - var tags = []; - var lineno = this.peek().loc.start.line; - var nextTok = this.peek(); - loop: while (true) { - switch (nextTok.type) { - case 'text': - var tok = this.advance(); - tags.push({ - type: 'Text', - val: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - case 'interpolated-code': - var tok = this.advance(); - tags.push({ - type: 'Code', - val: tok.val, - buffer: tok.buffer, - mustEscape: tok.mustEscape !== false, - isInline: true, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - case 'newline': - if (!options || !options.block) break loop; - var tok = this.advance(); - var nextType = this.peek().type; - if (nextType === 'text' || nextType === 'interpolated-code') { - tags.push({ - type: 'Text', - val: '\n', - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - } - break; - case 'start-pug-interpolation': - this.advance(); - tags.push(this.parseExpr()); - this.expect('end-pug-interpolation'); - break; - default: - var pluginResult = this.runPlugin('textTokens', nextTok, tags); - if (pluginResult) break; - break loop; + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; } - nextTok = this.peek(); + push({ type: 'text', value }); + continue; } - if (tags.length === 1) return tags[0]; - else return this.initBlock(lineno, tags); - }, - parseTextHtml: function() { - var nodes = []; - var currentNode = null; - loop: while (true) { - switch (this.peek().type) { - case 'text-html': - var text = this.advance(); - if (!currentNode) { - currentNode = { - type: 'Text', - val: text.val, - filename: this.filename, - line: text.loc.start.line, - column: text.loc.start.column, - isHtml: true, - }; - nodes.push(currentNode); - } else { - currentNode.val += '\n' + text.val; - } - break; - case 'indent': - var block = this.block(); - block.nodes.forEach(function(node) { - if (node.isHtml) { - if (!currentNode) { - currentNode = node; - nodes.push(currentNode); - } else { - currentNode.val += '\n' + node.val; - } - } else { - currentNode = null; - nodes.push(node); - } - }); - break; - case 'code': - currentNode = null; - nodes.push(this.parseCode(true)); - break; - case 'newline': - this.advance(); - break; - default: - break loop; + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; } + + push({ type: 'comma', value, output }); + continue; } - return nodes; - }, - /** - * ':' expr - * | block - */ + /** + * Slashes + */ - parseBlockExpansion: function() { - var tok = this.accept(':'); - if (tok) { - var expr = this.parseExpr(); - return expr.type === 'Block' - ? expr - : this.initBlock(tok.loc.start.line, [expr]); - } else { - return this.block(); + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; } - }, - /** - * case - */ + /** + * Dots + */ - parseCase: function() { - var tok = this.expect('case'); - var node = { - type: 'Case', - expr: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } - var block = this.emptyBlock(tok.loc.start.line + 1); - this.expect('indent'); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'comment': - case 'newline': - this.advance(); - break; - case 'when': - block.nodes.push(this.parseWhen()); - break; - case 'default': - block.nodes.push(this.parseDefault()); - break; - default: - var pluginResult = this.runPlugin('caseTokens', this.peek(), block); - if (pluginResult) break; - this.error( - 'INVALID_TOKEN', - 'Unexpected token "' + - this.peek().type + - '", expected "when", "default" or "newline"', - this.peek() - ); + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; } - this.expect('outdent'); - node.block = block; + /** + * Question marks + */ - return node; - }, + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } - /** - * when - */ + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; - parseWhen: function() { - var tok = this.expect('when'); - if (this.peek().type !== 'newline') { - return { - type: 'When', - expr: tok.val, - block: this.parseBlockExpansion(), - debug: false, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - } else { - return { - type: 'When', - expr: tok.val, - debug: false, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - } - }, + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } - /** - * default - */ + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } - parseDefault: function() { - var tok = this.expect('default'); - return { - type: 'When', - expr: 'default', - block: this.parseBlockExpansion(), - debug: false, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + push({ type: 'text', value, output }); + continue; + } - /** - * code - */ + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } - parseCode: function(noBlock) { - var tok = this.expect('code'); - assert( - typeof tok.mustEscape === 'boolean', - 'Please update to the newest version of pug-lexer.' - ); - var node = { - type: 'Code', - val: tok.val, - buffer: tok.buffer, - mustEscape: tok.mustEscape !== false, - isInline: !!noBlock, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - // todo: why is this here? It seems like a hacky workaround - if (node.val.match(/^ *else/)) node.debug = false; + push({ type: 'qmark', value, output: QMARK }); + continue; + } - if (noBlock) return node; + /** + * Exclamation + */ - var block; + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } - // handle block - block = 'indent' == this.peek().type; - if (block) { - if (tok.buffer) { - this.error( - 'BLOCK_IN_BUFFERED_CODE', - 'Buffered code cannot have a block attached to it', - this.peek() - ); + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; } - node.block = this.block(); } - return node; - }, - parseConditional: function() { - var tok = this.expect('if'); - var node = { - type: 'Conditional', - test: tok.val, - consequent: this.emptyBlock(tok.loc.start.line), - alternate: null, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + /** + * Plus + */ - // handle block - if ('indent' == this.peek().type) { - node.consequent = this.block(); - } + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } - var currentNode = node; - while (true) { - if (this.peek().type === 'newline') { - this.expect('newline'); - } else if (this.peek().type === 'else-if') { - tok = this.expect('else-if'); - currentNode = currentNode.alternate = { - type: 'Conditional', - test: tok.val, - consequent: this.emptyBlock(tok.loc.start.line), - alternate: null, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - if ('indent' == this.peek().type) { - currentNode.consequent = this.block(); - } - } else if (this.peek().type === 'else') { - this.expect('else'); - if (this.peek().type === 'indent') { - currentNode.alternate = this.block(); - } - break; - } else { - break; + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; } - return node; - }, - parseWhile: function() { - var tok = this.expect('while'); - var node = { - type: 'While', - test: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + /** + * Plain text + */ - // handle block - if ('indent' == this.peek().type) { - node.block = this.block(); - } else { - node.block = this.emptyBlock(tok.loc.start.line); + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; } - return node; - }, + /** + * Plain text + */ - /** - * block code - */ + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } - parseBlockCode: function() { - var tok = this.expect('blockcode'); - var line = tok.loc.start.line; - var column = tok.loc.start.column; - var body = this.peek(); - var text = ''; - if (body.type === 'start-pipeless-text') { - this.advance(); - while (this.peek().type !== 'end-pipeless-text') { - tok = this.advance(); - switch (tok.type) { - case 'text': - text += tok.val; - break; - case 'newline': - text += '\n'; - break; - default: - var pluginResult = this.runPlugin('blockCodeTokens', tok, tok); - if (pluginResult) { - text += pluginResult; - break; - } - this.error( - 'INVALID_TOKEN', - 'Unexpected token type: ' + tok.type, - tok - ); - } + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; } - this.advance(); - } - return { - type: 'Code', - val: text, - buffer: false, - mustEscape: false, - isInline: false, - line: line, - column: column, - filename: this.filename, - }; - }, - /** - * comment - */ - parseComment: function() { - var tok = this.expect('comment'); - var block; - if ((block = this.parseTextBlock())) { - return { - type: 'BlockComment', - val: tok.val, - block: block, - buffer: tok.buffer, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - } else { - return { - type: 'Comment', - val: tok.val, - buffer: tok.buffer, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + push({ type: 'text', value }); + continue; } - }, - - /** - * doctype - */ - parseDoctype: function() { - var tok = this.expect('doctype'); - return { - type: 'Doctype', - val: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + /** + * Stars + */ - parseIncludeFilter: function() { - var tok = this.expect('filter'); - var attrs = []; + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } - if (this.peek().type === 'start-attributes') { - attrs = this.attrs(); + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; } - return { - type: 'IncludeFilter', - name: tok.val, - attrs: attrs, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } - /** - * filter attrs? text-block - */ + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); - parseFilter: function() { - var tok = this.expect('filter'); - var block, - attrs = []; + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } - if (this.peek().type === 'start-attributes') { - attrs = this.attrs(); - } + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } - if (this.peek().type === 'text') { - var textToken = this.advance(); - block = this.initBlock(textToken.loc.start.line, [ - { - type: 'Text', - val: textToken.val, - line: textToken.loc.start.line, - column: textToken.loc.start.column, - filename: this.filename, - }, - ]); - } else if (this.peek().type === 'filter') { - block = this.initBlock(tok.loc.start.line, [this.parseFilter()]); - } else { - block = this.parseTextBlock() || this.emptyBlock(tok.loc.start.line); - } + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } - return { - type: 'Filter', - name: tok.val, - block: block, - attrs: attrs, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } - /** - * each block - */ + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; - parseEach: function() { - var tok = this.expect('each'); - var node = { - type: 'Each', - obj: tok.code, - val: tok.val, - key: tok.key, - block: this.block(), - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - if (this.peek().type == 'else') { - this.advance(); - node.alternate = this.block(); - } - return node; - }, + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } - parseEachOf: function() { - var tok = this.expect('eachOf'); - var node = { - type: 'EachOf', - obj: tok.code, - val: tok.val, - block: this.block(), - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - return node; - }, - /** - * 'extends' name - */ + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; - parseExtends: function() { - var tok = this.expect('extends'); - var path = this.expect('path'); - return { - type: 'Extends', - file: { - type: 'FileReference', - path: path.val.trim(), - line: path.loc.start.line, - column: path.loc.start.column, - filename: this.filename, - }, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; - /** - * 'block' name block - */ + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; - parseBlock: function() { - var tok = this.expect('block'); + state.output += prior.output + prev.output; + state.globstar = true; - var node = - 'indent' == this.peek().type - ? this.block() - : this.emptyBlock(tok.loc.start.line); - node.type = 'NamedBlock'; - node.name = tok.val.trim(); - node.mode = tok.mode; - node.line = tok.loc.start.line; - node.column = tok.loc.start.column; + consume(value + advance()); - return node; - }, + push({ type: 'slash', value: '/', output: '' }); + continue; + } - parseMixinBlock: function() { - var tok = this.expect('mixin-block'); - if (!this.inMixin) { - this.error( - 'BLOCK_OUTISDE_MIXIN', - 'Anonymous blocks are not allowed unless they are part of a mixin.', - tok - ); + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; } - return { - type: 'MixinBlock', - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, - parseYield: function() { - var tok = this.expect('yield'); - return { - type: 'YieldBlock', - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - }, + const token = { type: 'star', value, output: star }; - /** - * include block? - */ + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } - parseInclude: function() { - var tok = this.expect('include'); - var node = { - type: 'Include', - file: { - type: 'FileReference', - filename: this.filename, - }, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - var filters = []; - while (this.peek().type === 'filter') { - filters.push(this.parseIncludeFilter()); + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; } - var path = this.expect('path'); - node.file.path = path.val.trim(); - node.file.line = path.loc.start.line; - node.file.column = path.loc.start.column; + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; - if ( - (/\.jade$/.test(node.file.path) || /\.pug$/.test(node.file.path)) && - !filters.length - ) { - node.block = - 'indent' == this.peek().type - ? this.block() - : this.emptyBlock(tok.loc.start.line); - if (/\.jade$/.test(node.file.path)) { - console.warn( - this.filename + - ', line ' + - tok.loc.start.line + - ':\nThe .jade extension is deprecated, use .pug for "' + - node.file.path + - '".' - ); + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; } - } else { - node.type = 'RawInclude'; - node.filters = filters; - if (this.peek().type === 'indent') { - this.error( - 'RAW_INCLUDE_BLOCK', - 'Raw inclusion cannot contain a block', - this.peek() - ); + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; } } - return node; - }, - /** - * call ident block - */ + push(token); + } - parseCall: function() { - var tok = this.expect('call'); - var name = tok.val; - var args = tok.args; - var mixin = { - type: 'Mixin', - name: name, - args: args, - block: this.emptyBlock(tok.loc.start.line), - call: true, - attrs: [], - attributeBlocks: [], - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } - this.tag(mixin); - if (mixin.code) { - mixin.block.nodes.push(mixin.code); - delete mixin.code; - } - if (mixin.block.nodes.length === 0) mixin.block = null; - return mixin; - }, + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } - /** - * mixin block - */ + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } - parseMixin: function() { - var tok = this.expect('mixin'); - var name = tok.val; - var args = tok.args; + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } - if ('indent' == this.peek().type) { - this.inMixin++; - var mixin = { - type: 'Mixin', - name: name, - args: args, - block: this.block(), - call: false, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; - this.inMixin--; - return mixin; - } else { - this.error( - 'MIXIN_WITHOUT_BODY', - 'Mixin ' + name + ' declared without body', - tok - ); - } - }, + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; - /** - * indent (text | newline)* outdent - */ + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; - parseTextBlock: function() { - var tok = this.accept('start-pipeless-text'); - if (!tok) return; - var block = this.emptyBlock(tok.loc.start.line); - while (this.peek().type !== 'end-pipeless-text') { - var tok = this.advance(); - switch (tok.type) { - case 'text': - block.nodes.push({ - type: 'Text', - val: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - case 'newline': - block.nodes.push({ - type: 'Text', - val: '\n', - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - case 'start-pug-interpolation': - block.nodes.push(this.parseExpr()); - this.expect('end-pug-interpolation'); - break; - case 'interpolated-code': - block.nodes.push({ - type: 'Code', - val: tok.val, - buffer: tok.buffer, - mustEscape: tok.mustEscape !== false, - isInline: true, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - default: - var pluginResult = this.runPlugin('textBlockTokens', tok, block, tok); - if (pluginResult) break; - this.error( - 'INVALID_TOKEN', - 'Unexpected token type: ' + tok.type, - tok - ); + if (token.suffix) { + state.output += token.suffix; } } - this.advance(); - return block; - }, + } - /** - * indent expr* outdent - */ + return state; +}; - block: function() { - var tok = this.expect('indent'); - var block = this.emptyBlock(tok.loc.start.line); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else if ('text-html' == this.peek().type) { - block.nodes = block.nodes.concat(this.parseTextHtml()); - } else { - var expr = this.parseExpr(); - if (expr.type === 'Block') { - block.nodes = block.nodes.concat(expr.nodes); - } else { - block.nodes.push(expr); - } - } - } - this.expect('outdent'); - return block; - }, +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ - /** - * interpolation (attrs | class | id)* (text | code | ':')? newline* block? - */ +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } - parseInterpolation: function() { - var tok = this.advance(); - var tag = { - type: 'InterpolatedTag', - expr: tok.val, - selfClosing: false, - block: this.emptyBlock(tok.loc.start.line), - attrs: [], - attributeBlocks: [], - isInline: false, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); - return this.tag(tag, {selfClosingAllowed: true}); - }, + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; - parseTag: function() { - var tok = this.advance(); - var tag = { - type: 'Tag', - name: tok.val, - selfClosing: false, - block: this.emptyBlock(tok.loc.start.line), - attrs: [], - attributeBlocks: [], - isInline: inlineTags.indexOf(tok.val) !== -1, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }; + if (opts.capture) { + star = `(${star})`; + } - return this.tag(tag, {selfClosingAllowed: true}); - }, + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; - /** - * Parse tag. - */ + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; - tag: function(tag, options) { - var seenAttrs = false; - var attributeNames = []; - var selfClosingAllowed = options && options.selfClosingAllowed; - // (attrs | class | id)* - out: while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - if (tok.type === 'id') { - if (attributeNames.indexOf('id') !== -1) { - this.error( - 'DUPLICATE_ID', - 'Duplicate attribute "id" is not allowed.', - tok - ); - } - attributeNames.push('id'); - } - tag.attrs.push({ - name: tok.type, - val: "'" + tok.val + "'", - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - mustEscape: false, - }); - continue; - case 'start-attributes': - if (seenAttrs) { - console.warn( - this.filename + - ', line ' + - this.peek().loc.start.line + - ':\nYou should not have pug tags with multiple attributes.' - ); - } - seenAttrs = true; - tag.attrs = tag.attrs.concat(this.attrs(attributeNames)); - continue; - case '&attributes': - var tok = this.advance(); - tag.attributeBlocks.push({ - type: 'AttributeBlock', - val: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - }); - break; - default: - var pluginResult = this.runPlugin( - 'tagAttributeTokens', - this.peek(), - tag, - attributeNames - ); - if (pluginResult) break; - break out; - } - } + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; - // check immediate '.' - if ('dot' == this.peek().type) { - tag.textOnly = true; - this.advance(); - } + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - case 'interpolated-code': - var text = this.parseText(); - if (text.type === 'Block') { - tag.block.nodes.push.apply(tag.block.nodes, text.nodes); - } else { - tag.block.nodes.push(text); - } - break; - case 'code': - tag.block.nodes.push(this.parseCode(true)); - break; - case ':': - this.advance(); - var expr = this.parseExpr(); - tag.block = - expr.type === 'Block' ? expr : this.initBlock(tag.line, [expr]); - break; - case 'newline': - case 'indent': - case 'outdent': - case 'eos': - case 'start-pipeless-text': - case 'end-pug-interpolation': - break; - case 'slash': - if (selfClosingAllowed) { - this.advance(); - tag.selfClosing = true; - break; - } - default: - var pluginResult = this.runPlugin( - 'tagTokens', - this.peek(), - tag, - options - ); - if (pluginResult) break; - this.error( - 'INVALID_TOKEN', - 'Unexpected token `' + - this.peek().type + - '` expected `text`, `interpolated-code`, `code`, `:`' + - (selfClosingAllowed ? ', `slash`' : '') + - ', `newline` or `eos`', - this.peek() - ); - } + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; - // newline* - while ('newline' == this.peek().type) this.advance(); + case '**': + return nodot + globstar(opts); - // block? - if (tag.textOnly) { - tag.block = this.parseTextBlock() || this.emptyBlock(tag.line); - } else if ('indent' == this.peek().type) { - var block = this.block(); - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.nodes.push(block.nodes[i]); - } - } + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - return tag; - }, + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - attrs: function(attributeNames) { - this.expect('start-attributes'); + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - var attrs = []; - var tok = this.advance(); - while (tok.type === 'attribute') { - if (tok.name !== 'class' && attributeNames) { - if (attributeNames.indexOf(tok.name) !== -1) { - this.error( - 'DUPLICATE_ATTRIBUTE', - 'Duplicate attribute "' + tok.name + '" is not allowed.', - tok - ); - } - attributeNames.push(tok.name); + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; } - attrs.push({ - name: tok.name, - val: tok.val, - line: tok.loc.start.line, - column: tok.loc.start.column, - filename: this.filename, - mustEscape: tok.mustEscape !== false, - }); - tok = this.advance(); } - this.tokens.defer(tok); - this.expect('end-attributes'); - return attrs; - }, + }; + + const output = utils.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; }; +module.exports = parse; + /***/ }), -/***/ 33470: -/***/ ((module) => { +/***/ 33322: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = [ - 'a', - 'abbr', - 'acronym', - 'b', - 'br', - 'code', - 'em', - 'font', - 'i', - 'img', - 'ins', - 'kbd', - 'map', - 'samp', - 'small', - 'span', - 'strong', - 'sub', - 'sup', -]; - +const path = __nccwpck_require__(71017); +const scan = __nccwpck_require__(32429); +const parse = __nccwpck_require__(92139); +const utils = __nccwpck_require__(30479); +const constants = __nccwpck_require__(16099); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); -/***/ }), +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ -/***/ 37364: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } -"use strict"; + const isState = isObject(glob) && glob.tokens && glob.input; + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } -var fs = __nccwpck_require__(57147); -var dependencies = __nccwpck_require__(41222); -var internals = __nccwpck_require__(373); -var sources = __nccwpck_require__(21003); + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); -module.exports = build; + const state = regex.state; + delete regex.state; -function build(functions) { - var fns = []; - functions = functions.filter(function(fn) { - return !internals[fn]; - }); - for (var i = 0; i < functions.length; i++) { - if (fns.indexOf(functions[i]) === -1) { - fns.push(functions[i]); - functions.push.apply(functions, dependencies[functions[i]]); - } + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } - return fns - .sort() - .map(function(name) { - return sources[name]; - }) - .join('\n'); -} + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; -/***/ }), + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } -/***/ 27596: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } -"use strict"; + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + if (returnState) { + matcher.state = state; + } -var pug_has_own_property = Object.prototype.hasOwnProperty; + return matcher; +}; /** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public */ -exports.merge = pug_merge; -function pug_merge(a, b) { - if (arguments.length === 1) { - var attrs = a[0]; - for (var i = 1; i < a.length; i++) { - attrs = pug_merge(attrs, a[i]); - } - return attrs; +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); } - for (var key in b) { - if (key === 'class') { - var valA = a[key] || []; - a[key] = (Array.isArray(valA) ? valA : [valA]).concat(b[key] || []); - } else if (key === 'style') { - var valA = pug_style(a[key]); - valA = valA && valA[valA.length - 1] !== ';' ? valA + ';' : valA; - var valB = pug_style(b[key]); - valB = valB && valB[valB.length - 1] !== ';' ? valB + ';' : valB; - a[key] = valA + valB; + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); } else { - a[key] = b[key]; + match = regex.exec(output); } } - return a; -} + return { isMatch: Boolean(match), match, output }; +}; /** - * Process array, object, or string as a string of classes delimited by a space. - * - * If `val` is an array, all members of it and its subarrays are counted as - * classes. If `escaping` is an array, then whether or not the item in `val` is - * escaped depends on the corresponding item in `escaping`. If `escaping` is - * not an array, no escaping is done. + * Match the basename of a filepath. * - * If `val` is an object, all the keys whose value is truthy are counted as - * classes. No escaping is done. + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. * - * If `val` is a string, it is counted as a class. No escaping is done. + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); * - * @param {(Array.|Object.|string)} val - * @param {?Array.} escaping - * @return {String} + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public */ -exports.classes = pug_classes; -function pug_classes_array(val, escaping) { - var classString = '', - className, - padding = '', - escapeEnabled = Array.isArray(escaping); - for (var i = 0; i < val.length; i++) { - className = pug_classes(val[i]); - if (!className) continue; - escapeEnabled && escaping[i] && (className = pug_escape(className)); - classString = classString + padding + className; - padding = ' '; - } - return classString; -} -function pug_classes_object(val) { - var classString = '', - padding = ''; - for (var key in val) { - if (key && val[key] && pug_has_own_property.call(val, key)) { - classString = classString + padding + key; - padding = ' '; - } - } - return classString; -} -function pug_classes(val, escaping) { - if (Array.isArray(val)) { - return pug_classes_array(val, escaping); - } else if (val && typeof val === 'object') { - return pug_classes_object(val); - } else { - return val || ''; - } -} + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** - * Convert object or string to a string of CSS styles delimited by a semicolon. + * Parse a glob pattern to create the source string for a regular + * expression. * - * @param {(Object.|string)} val - * @return {String} + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public */ -exports.style = pug_style; -function pug_style(val) { - if (!val) return ''; - if (typeof val === 'object') { - var out = ''; - for (var style in val) { - /* istanbul ignore else */ - if (pug_has_own_property.call(val, style)) { - out = out + style + ':' + val[style] + ';'; - } - } - return out; - } else { - return val + ''; - } -} +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; /** - * Render the given attribute. + * Scan a glob pattern to separate the pattern into segments. * - * @param {String} key - * @param {String} val - * @param {Boolean} escaped - * @param {Boolean} terse - * @return {String} + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public */ -exports.attr = pug_attr; -function pug_attr(key, val, escaped, terse) { - if ( - val === false || - val == null || - (!val && (key === 'class' || key === 'style')) - ) { - return ''; - } - if (val === true) { - return ' ' + (terse ? key : key + '="' + key + '"'); - } - var type = typeof val; - if ( - (type === 'object' || type === 'function') && - typeof val.toJSON === 'function' - ) { - val = val.toJSON(); - } - if (typeof val !== 'string') { - val = JSON.stringify(val); - if (!escaped && val.indexOf('"') !== -1) { - return ' ' + key + "='" + val.replace(/'/g, ''') + "'"; - } - } - if (escaped) val = pug_escape(val); - return ' ' + key + '="' + val + '"'; -} + +picomatch.scan = (input, options) => scan(input, options); /** - * Render the given attributes object. + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. * - * @param {Object} obj - * @param {Object} terse whether to use HTML5 terse boolean attributes - * @return {String} + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public */ -exports.attrs = pug_attrs; -function pug_attrs(obj, terse) { - var attrs = ''; - for (var key in obj) { - if (pug_has_own_property.call(obj, key)) { - var val = obj[key]; +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } - if ('class' === key) { - val = pug_classes(val); - attrs = pug_attr(key, val, false, terse) + attrs; - continue; - } - if ('style' === key) { - val = pug_style(val); - } - attrs += pug_attr(key, val, false, terse); - } + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; } - return attrs; -} + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; /** - * Escape the given string of `html`. + * Create a regular expression from a parsed glob pattern. * - * @param {String} html - * @return {String} - * @api private + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public */ -var pug_match_html = /["&<>]/; -exports.escape = pug_escape; -function pug_escape(_html) { - var html = '' + _html; - var regexResult = pug_match_html.exec(html); - if (!regexResult) return _html; +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } - var result = ''; - var i, lastIndex, escape; - for (i = regexResult.index, lastIndex = 0; i < html.length; i++) { - switch (html.charCodeAt(i)) { - case 34: - escape = '"'; - break; - case 38: - escape = '&'; - break; - case 60: - escape = '<'; - break; - case 62: - escape = '>'; - break; - default: - continue; - } - if (lastIndex !== i) result += html.substring(lastIndex, i); - lastIndex = i + 1; - result += escape; + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); } - if (lastIndex !== i) return result + html.substring(lastIndex, i); - else return result; -} + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; /** - * Re-throw the given `err` in context to the - * the pug in `filename` at the given `lineno`. + * Create a regular expression from the given regex source string. * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @param {String} str original source - * @api private + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public */ -exports.rethrow = pug_rethrow; -function pug_rethrow(err, filename, lineno, str) { - if (!(err instanceof Error)) throw err; - if ((typeof window != 'undefined' || !filename) && !str) { - err.message += ' on line ' + lineno; - throw err; - } - var context, lines, start, end; +picomatch.toRegex = (source, options) => { try { - str = str || (__nccwpck_require__(57147).readFileSync)(filename, {encoding: 'utf8'}); - context = 3; - lines = str.split('\n'); - start = Math.max(lineno - context, 0); - end = Math.min(lines.length, lineno + context); - } catch (ex) { - err.message += - ' - could not read from ' + filename + ' (' + ex.message + ')'; - pug_rethrow(err, null, lineno); - return; + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; } +}; - // Error context - context = lines - .slice(start, end) - .map(function(line, i) { - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') + curr + '| ' + line; - }) - .join('\n'); - - // Alter exception message - err.path = filename; - try { - err.message = - (filename || 'Pug') + - ':' + - lineno + - '\n' + - context + - '\n\n' + - err.message; - } catch (e) {} - throw err; -} - +/** + * Picomatch constants. + * @return {Object} + */ -/***/ }), +picomatch.constants = constants; -/***/ 41222: -/***/ ((module) => { +/** + * Expose "picomatch" + */ -module.exports = { - "has_own_property": [], - "merge": [ - "style" - ], - "classes_array": [ - "classes", - "escape" - ], - "classes_object": [ - "has_own_property" - ], - "classes": [ - "classes_array", - "classes_object" - ], - "style": [ - "has_own_property" - ], - "attr": [ - "escape" - ], - "attrs": [ - "attr", - "classes", - "has_own_property", - "style" - ], - "match_html": [], - "escape": [ - "match_html" - ], - "rethrow": [] -} +module.exports = picomatch; /***/ }), -/***/ 373: -/***/ ((module) => { +/***/ 32429: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = { - "dependencies": true, - "internals": true, - "has_own_property": true, - "classes_array": true, - "classes_object": true, - "match_html": true -} +"use strict"; -/***/ }), +const utils = __nccwpck_require__(30479); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = __nccwpck_require__(16099); -/***/ 21003: -/***/ ((module) => { +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; -module.exports = { - "has_own_property": "var pug_has_own_property=Object.prototype.hasOwnProperty;", - "merge": "function pug_merge(e,r){if(1===arguments.length){for(var t=e[0],g=1;g]/;", - "escape": "function pug_escape(e){var a=\"\"+e,t=pug_match_html.exec(a);if(!t)return e;var r,c,n,s=\"\";for(r=t.index,c=0;r \":\" \")+t+\"| \"+e}).join(\"\\n\"),e.path=n;try{e.message=(n||\"Pug\")+\":\"+r+\"\\n\"+o+\"\\n\\n\"+e.message}catch(e){}throw e}" -} +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ -/***/ }), +const scan = (input, options) => { + const opts = options || {}; -/***/ 60010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; -var runtime = __nccwpck_require__(27596); + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; -module.exports = wrap; -function wrap(template, templateName) { - templateName = templateName || 'template'; - return Function( - 'pug', - template + '\n' + 'return ' + templateName + ';' - )(runtime); -} + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + while (index < length) { + code = advance(); + let next; -/***/ }), + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); -/***/ 45413: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } -"use strict"; + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } -var error = __nccwpck_require__(11449); + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } -module.exports = stripComments; + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; -function unexpectedToken(type, occasion, filename, line) { - var msg = '`' + type + '` encountered when ' + occasion; - throw error('UNEXPECTED_TOKEN', msg, {filename: filename, line: line}); -} + if (scanToEnd === true) { + continue; + } -function stripComments(input, options) { - options = options || {}; + break; + } - // Default: strip unbuffered comments and leave buffered ones alone - var stripUnbuffered = options.stripUnbuffered !== false; - var stripBuffered = options.stripBuffered === true; - var filename = options.filename; + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; - var out = []; - // If we have encountered a comment token and are not sure if we have gotten - // out of the comment or not - var inComment = false; - // If we are sure that we are in a block comment and all tokens except - // `end-pipeless-text` should be ignored - var inPipelessText = false; + if (scanToEnd === true) { + continue; + } - return input.filter(function(tok) { - switch (tok.type) { - case 'comment': - if (inComment) { - unexpectedToken( - 'comment', - 'already in a comment', - filename, - tok.line - ); - } else { - inComment = tok.buffer ? stripBuffered : stripUnbuffered; - return !inComment; - } - case 'start-pipeless-text': - if (!inComment) return true; - if (inPipelessText) { - unexpectedToken( - 'start-pipeless-text', - 'already in pipeless text mode', - filename, - tok.line - ); + break; } - inPipelessText = true; - return false; - case 'end-pipeless-text': - if (!inComment) return true; - if (!inPipelessText) { - unexpectedToken( - 'end-pipeless-text', - 'not in pipeless text mode', - filename, - tok.line - ); + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } } - inPipelessText = false; - inComment = false; - return false; - // There might be a `text` right after `comment` but before - // `start-pipeless-text`. Treat it accordingly. - case 'text': - return !inComment; - default: - if (inPipelessText) return false; - inComment = false; - return true; + } + + if (scanToEnd === true) { + continue; + } + + break; } - }); -} + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; -/***/ }), + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } -/***/ 60283: -/***/ ((module) => { + lastIndex = index + 1; + continue; + } -"use strict"; + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } -module.exports = walkAST; -function walkAST(ast, before, after, options) { - if (after && typeof after === 'object' && typeof options === 'undefined') { - options = after; - after = null; - } - options = options || {includeDependencies: false}; - var parents = (options.parents = options.parents || []); + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } - var replace = function replace(replacement) { - if (Array.isArray(replacement) && !replace.arrayAllowed) { - throw new Error( - 'replace() can only be called with an array if the last parent is a Block or NamedBlock' - ); + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } } - ast = replacement; - }; - replace.arrayAllowed = - parents[0] && - (/^(Named)?Block$/.test(parents[0].type) || - (parents[0].type === 'RawInclude' && ast.type === 'IncludeFilter')); - if (before) { - var result = before(ast, replace); - if (result === false) { - return ast; - } else if (Array.isArray(ast)) { - // return right here to skip after() call on array - return walkAndMergeNodes(ast); + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; } - } - parents.unshift(ast); + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; - switch (ast.type) { - case 'NamedBlock': - case 'Block': - ast.nodes = walkAndMergeNodes(ast.nodes); - break; - case 'Case': - case 'Filter': - case 'Mixin': - case 'Tag': - case 'InterpolatedTag': - case 'When': - case 'Code': - case 'While': - if (ast.block) { - ast.block = walkAST(ast.block, before, after, options); + if (scanToEnd === true) { + continue; } break; - case 'Each': - if (ast.block) { - ast.block = walkAST(ast.block, before, after, options); - } - if (ast.alternate) { - ast.alternate = walkAST(ast.alternate, before, after, options); + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } } - break; - case 'EachOf': - if (ast.block) { - ast.block = walkAST(ast.block, before, after, options); + + if (scanToEnd === true) { + continue; } + break; - case 'Conditional': - if (ast.consequent) { - ast.consequent = walkAST(ast.consequent, before, after, options); - } - if (ast.alternate) { - ast.alternate = walkAST(ast.alternate, before, after, options); + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; } break; - case 'Include': - walkAST(ast.block, before, after, options); - walkAST(ast.file, before, after, options); - break; - case 'Extends': - walkAST(ast.file, before, after, options); - break; - case 'RawInclude': - ast.filters = walkAndMergeNodes(ast.filters); - walkAST(ast.file, before, after, options); - break; - case 'Attrs': - case 'BlockComment': - case 'Comment': - case 'Doctype': - case 'IncludeFilter': - case 'MixinBlock': - case 'YieldBlock': - case 'Text': - break; - case 'FileReference': - if (options.includeDependencies && ast.ast) { - walkAST(ast.ast, before, after, options); + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; } + break; - default: - throw new Error('Unexpected node type ' + ast.type); - break; + } } - parents.shift(); + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } - after && after(ast, replace); - return ast; + let base = str; + let prefix = ''; + let glob = ''; - function walkAndMergeNodes(nodes) { - return nodes.reduce(function(nodes, node) { - var result = walkAST(node, before, after, options); - if (Array.isArray(result)) { - return nodes.concat(result); - } else { - return nodes.concat([result]); - } - }, []); + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; } -} + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } -/***/ }), + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } -/***/ 40316: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); -"use strict"; + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; -/*! - * Pug - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } -/** - * Module dependencies. - */ + if (opts.parts === true || opts.tokens === true) { + let prevIndex; -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var lex = __nccwpck_require__(32428); -var stripComments = __nccwpck_require__(45413); -var parse = __nccwpck_require__(40558); -var load = __nccwpck_require__(44254); -var filters = __nccwpck_require__(69309); -var link = __nccwpck_require__(63234); -var generateCode = __nccwpck_require__(90331); -var runtime = __nccwpck_require__(27596); -var runtimeWrap = __nccwpck_require__(60010); + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } -/** - * Name for detection - */ + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); -exports.name = 'Pug'; + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } -/** - * Pug runtime helpers. - */ + state.slashes = slashes; + state.parts = parts; + } -exports.runtime = runtime; + return state; +}; -/** - * Template function cache. - */ +module.exports = scan; -exports.cache = {}; -function applyPlugins(value, options, plugins, name) { - return plugins.reduce(function(value, plugin) { - return plugin[name] ? plugin[name](value, options) : value; - }, value); -} +/***/ }), -function findReplacementFunc(plugins, name) { - var eligiblePlugins = plugins.filter(function(plugin) { - return plugin[name]; - }); +/***/ 30479: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (eligiblePlugins.length > 1) { - throw new Error('Two or more plugins all implement ' + name + ' method.'); - } else if (eligiblePlugins.length) { - return eligiblePlugins[0][name].bind(eligiblePlugins[0]); - } - return null; -} +"use strict"; -/** - * Object for global custom filters. Note that you can also just pass a `filters` - * option to any other method. - */ -exports.filters = {}; -/** - * Compile the given `str` of pug and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {Object} - * @api private - */ +const path = __nccwpck_require__(71017); +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = __nccwpck_require__(16099); -function compileBody(str, options) { - var debug_sources = {}; - debug_sources[options.filename] = str; - var dependencies = []; - var plugins = options.plugins || []; - var ast = load.string(str, { - filename: options.filename, - basedir: options.basedir, - lex: function(str, options) { - var lexOptions = {}; - Object.keys(options).forEach(function(key) { - lexOptions[key] = options[key]; - }); - lexOptions.plugins = plugins - .filter(function(plugin) { - return !!plugin.lex; - }) - .map(function(plugin) { - return plugin.lex; - }); - var contents = applyPlugins( - str, - {filename: options.filename}, - plugins, - 'preLex' - ); - return applyPlugins( - lex(contents, lexOptions), - options, - plugins, - 'postLex' - ); - }, - parse: function(tokens, options) { - tokens = tokens.map(function(token) { - if (token.type === 'path' && path.extname(token.val) === '') { - return { - type: 'path', - loc: token.loc, - val: token.val + '.pug', - }; - } - return token; - }); - tokens = stripComments(tokens, options); - tokens = applyPlugins(tokens, options, plugins, 'preParse'); - var parseOptions = {}; - Object.keys(options).forEach(function(key) { - parseOptions[key] = options[key]; - }); - parseOptions.plugins = plugins - .filter(function(plugin) { - return !!plugin.parse; - }) - .map(function(plugin) { - return plugin.parse; - }); +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); - return applyPlugins( - applyPlugins( - parse(tokens, parseOptions), - options, - plugins, - 'postParse' - ), - options, - plugins, - 'preLoad' - ); - }, - resolve: function(filename, source, loadOptions) { - var replacementFunc = findReplacementFunc(plugins, 'resolve'); - if (replacementFunc) { - return replacementFunc(filename, source, options); - } +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; - return load.resolve(filename, source, loadOptions); - }, - read: function(filename, loadOptions) { - dependencies.push(filename); +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; - var contents; +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; - var replacementFunc = findReplacementFunc(plugins, 'read'); - if (replacementFunc) { - contents = replacementFunc(filename, options); - } else { - contents = load.read(filename, loadOptions); - } +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; - debug_sources[filename] = Buffer.isBuffer(contents) - ? contents.toString('utf8') - : contents; - return contents; - }, - }); - ast = applyPlugins(ast, options, plugins, 'postLoad'); - ast = applyPlugins(ast, options, plugins, 'preFilters'); +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; - var filtersSet = {}; - Object.keys(exports.filters).forEach(function(key) { - filtersSet[key] = exports.filters[key]; - }); - if (options.filters) { - Object.keys(options.filters).forEach(function(key) { - filtersSet[key] = options.filters[key]; - }); +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; } - ast = filters.handleFilters( - ast, - filtersSet, - options.filterOptions, - options.filterAliases - ); + return output; +}; - ast = applyPlugins(ast, options, plugins, 'postFilters'); - ast = applyPlugins(ast, options, plugins, 'preLink'); - ast = link(ast); - ast = applyPlugins(ast, options, plugins, 'postLink'); - // Compile - ast = applyPlugins(ast, options, plugins, 'preCodeGen'); - var js = (findReplacementFunc(plugins, 'generateCode') || generateCode)(ast, { - pretty: options.pretty, - compileDebug: options.compileDebug, - doctype: options.doctype, - inlineRuntimeFunctions: options.inlineRuntimeFunctions, - globals: options.globals, - self: options.self, - includeSources: options.includeSources ? debug_sources : false, - templateName: options.templateName, - }); - js = applyPlugins(js, options, plugins, 'postCodeGen'); +/***/ }), - // Debug compiler - if (options.debug) { - console.error( - '\nCompiled Function:\n\n\u001b[90m%s\u001b[0m', - js.replace(/^/gm, ' ') - ); - } +/***/ 47810: +/***/ ((module) => { - return {body: js, dependencies: dependencies}; +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process } -/** - * Get the template from a string or a file, either compiled on-the-fly or - * read from cache (if enabled), and cache the template if needed. - * - * If `str` is not set, the file specified in `options.filename` will be read. - * - * If `options.cache` is true, this function reads the file from - * `options.filename` so it must be set prior to calling this function. - * - * @param {Object} options - * @param {String=} str - * @return {Function} - * @api private - */ -function handleTemplateCache(options, str) { - var key = options.filename; - if (options.cache && exports.cache[key]) { - return exports.cache[key]; - } else { - if (str === undefined) str = fs.readFileSync(options.filename, 'utf8'); - var templ = exports.compile(str, options); - if (options.cache) exports.cache[key] = templ; - return templ; +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); } } -/** - * Compile a `Function` representation of the given pug `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled - template, when it is explicitly `true`, the source code is included in - the compiled template for better accuracy. - * - `filename` used to improve errors when `compileDebug` is not `false` and to resolve imports/extends - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ -exports.compile = function(str, options) { - var options = options || {}; - str = String(str); +/***/ }), - var parsed = compileBody(str, { - compileDebug: options.compileDebug !== false, - filename: options.filename, - basedir: options.basedir, - pretty: options.pretty, - doctype: options.doctype, - inlineRuntimeFunctions: options.inlineRuntimeFunctions, - globals: options.globals, - self: options.self, - includeSources: options.compileDebug === true, - debug: options.debug, - templateName: 'template', - filters: options.filters, - filterOptions: options.filterOptions, - filterAliases: options.filterAliases, - plugins: options.plugins, - }); +/***/ 45676: +/***/ ((module) => { + +// for now just expose the builtin process global from node.js +module.exports = global.process; - var res = options.inlineRuntimeFunctions - ? new Function('', parsed.body + ';return template;')() - : runtimeWrap(parsed.body); - res.dependencies = parsed.dependencies; +/***/ }), - return res; -}; +/***/ 47096: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Compile a JavaScript source representation of the given pug `str`. - * - * Options: - * - * - `compileDebug` When it is `true`, the source code is included in - * the compiled template for better error messages. - * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends - * - `name` the name of the resulting function (defaults to "template") - * - `module` when it is explicitly `true`, the source code include export module syntax - * - * @param {String} str - * @param {Options} options - * @return {Object} - * @api public - */ +"use strict"; -exports.compileClientWithDependenciesTracked = function(str, options) { - var options = options || {}; - str = String(str); - var parsed = compileBody(str, { - compileDebug: options.compileDebug, - filename: options.filename, - basedir: options.basedir, - pretty: options.pretty, - doctype: options.doctype, - inlineRuntimeFunctions: options.inlineRuntimeFunctions !== false, - globals: options.globals, - self: options.self, - includeSources: options.compileDebug, - debug: options.debug, - templateName: options.name || 'template', - filters: options.filters, - filterOptions: options.filterOptions, - filterAliases: options.filterAliases, - plugins: options.plugins, - }); +module.exports = __nccwpck_require__(15836) - var body = parsed.body; - if (options.module) { - if (options.inlineRuntimeFunctions === false) { - body = 'var pug = require("pug-runtime");' + body; - } - body += ' module.exports = ' + (options.name || 'template') + ';'; - } +/***/ }), - return {body: body, dependencies: parsed.dependencies}; -}; +/***/ 48874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Compile a JavaScript source representation of the given pug `str`. - * - * Options: - * - * - `compileDebug` When it is `true`, the source code is included in - * the compiled template for better error messages. - * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends - * - `name` the name of the resulting function (defaults to "template") - * - * @param {String} str - * @param {Options} options - * @return {String} - * @api public - */ -exports.compileClient = function(str, options) { - return exports.compileClientWithDependenciesTracked(str, options).body; -}; +"use strict"; -/** - * Compile a `Function` representation of the given pug file. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled - template, when it is explicitly `true`, the source code is included in - the compiled template for better accuracy. - * - * @param {String} path - * @param {Options} options - * @return {Function} - * @api public - */ -exports.compileFile = function(path, options) { - options = options || {}; - options.filename = path; - return handleTemplateCache(options); -}; -/** - * Render the given `str` of pug. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function|undefined} fn - * @returns {String} - * @api public - */ +var asap = __nccwpck_require__(83691); -exports.render = function(str, options, fn) { - // support callback API - if ('function' == typeof options) { - (fn = options), (options = undefined); +function noop() {} + +// States: +// +// 0 - pending +// 1 - fulfilled with _value +// 2 - rejected with _value +// 3 - adopted the state of another promise, _value +// +// once the state is no longer pending (0) it is immutable + +// All `_` prefixed properties will be reduced to `_{random number}` +// at build time to obfuscate them and discourage their use. +// We don't use symbols or Object.defineProperty to fully hide them +// because the performance isn't good enough. + + +// to avoid using try/catch inside critical functions, we +// extract them to here. +var LAST_ERROR = null; +var IS_ERROR = {}; +function getThen(obj) { + try { + return obj.then; + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; } - if (typeof fn === 'function') { - var res; - try { - res = exports.render(str, options); - } catch (ex) { - return fn(ex); - } - return fn(null, res); +} + +function tryCallOne(fn, a) { + try { + return fn(a); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; } +} +function tryCallTwo(fn, a, b) { + try { + fn(a, b); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} - options = options || {}; +module.exports = Promise; - // cache requires .filename - if (options.cache && !options.filename) { - throw new Error('the "filename" option is required for caching'); +function Promise(fn) { + if (typeof this !== 'object') { + throw new TypeError('Promises must be constructed via new'); + } + if (typeof fn !== 'function') { + throw new TypeError('Promise constructor\'s argument is not a function'); } + this._40 = 0; + this._65 = 0; + this._55 = null; + this._72 = null; + if (fn === noop) return; + doResolve(fn, this); +} +Promise._37 = null; +Promise._87 = null; +Promise._61 = noop; - return handleTemplateCache(options, str)(options); +Promise.prototype.then = function(onFulfilled, onRejected) { + if (this.constructor !== Promise) { + return safeThen(this, onFulfilled, onRejected); + } + var res = new Promise(noop); + handle(this, new Handler(onFulfilled, onRejected, res)); + return res; }; -/** - * Render a Pug file at the given `path`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function|undefined} fn - * @returns {String} - * @api public - */ +function safeThen(self, onFulfilled, onRejected) { + return new self.constructor(function (resolve, reject) { + var res = new Promise(noop); + res.then(resolve, reject); + handle(self, new Handler(onFulfilled, onRejected, res)); + }); +} +function handle(self, deferred) { + while (self._65 === 3) { + self = self._55; + } + if (Promise._37) { + Promise._37(self); + } + if (self._65 === 0) { + if (self._40 === 0) { + self._40 = 1; + self._72 = deferred; + return; + } + if (self._40 === 1) { + self._40 = 2; + self._72 = [self._72, deferred]; + return; + } + self._72.push(deferred); + return; + } + handleResolved(self, deferred); +} -exports.renderFile = function(path, options, fn) { - // support callback API - if ('function' == typeof options) { - (fn = options), (options = undefined); +function handleResolved(self, deferred) { + asap(function() { + var cb = self._65 === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + if (self._65 === 1) { + resolve(deferred.promise, self._55); + } else { + reject(deferred.promise, self._55); + } + return; + } + var ret = tryCallOne(cb, self._55); + if (ret === IS_ERROR) { + reject(deferred.promise, LAST_ERROR); + } else { + resolve(deferred.promise, ret); + } + }); +} +function resolve(self, newValue) { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) { + return reject( + self, + new TypeError('A promise cannot be resolved with itself.') + ); } - if (typeof fn === 'function') { - var res; - try { - res = exports.renderFile(path, options); - } catch (ex) { - return fn(ex); + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = getThen(newValue); + if (then === IS_ERROR) { + return reject(self, LAST_ERROR); + } + if ( + then === self.then && + newValue instanceof Promise + ) { + self._65 = 3; + self._55 = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(then.bind(newValue), self); + return; } - return fn(null, res); } + self._65 = 1; + self._55 = newValue; + finale(self); +} - options = options || {}; +function reject(self, newValue) { + self._65 = 2; + self._55 = newValue; + if (Promise._87) { + Promise._87(self, newValue); + } + finale(self); +} +function finale(self) { + if (self._40 === 1) { + handle(self, self._72); + self._72 = null; + } + if (self._40 === 2) { + for (var i = 0; i < self._72.length; i++) { + handle(self, self._72[i]); + } + self._72 = null; + } +} - options.filename = path; - return handleTemplateCache(options)(options); -}; +function Handler(onFulfilled, onRejected, promise){ + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; +} /** - * Compile a Pug file at the given `path` for use on the client. + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. * - * @param {String} path - * @param {Object} options - * @returns {String} - * @api public + * Makes no guarantees about asynchrony. */ +function doResolve(fn, promise) { + var done = false; + var res = tryCallTwo(fn, function (value) { + if (done) return; + done = true; + resolve(promise, value); + }, function (reason) { + if (done) return; + done = true; + reject(promise, reason); + }); + if (!done && res === IS_ERROR) { + done = true; + reject(promise, LAST_ERROR); + } +} -exports.compileFileClient = function(path, options) { - var key = path + ':client'; - options = options || {}; - options.filename = path; +/***/ }), - if (options.cache && exports.cache[key]) { - return exports.cache[key]; - } +/***/ 85222: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var str = fs.readFileSync(options.filename, 'utf8'); - var out = exports.compileClient(str, options); - if (options.cache) exports.cache[key] = out; - return out; -}; +"use strict"; -/** - * Express support. - */ -exports.__express = function(path, options, fn) { - if ( - options.compileDebug == undefined && - process.env.NODE_ENV === 'production' - ) { - options.compileDebug = false; - } - exports.renderFile(path, options, fn); +var Promise = __nccwpck_require__(48874); + +module.exports = Promise; +Promise.prototype.done = function (onFulfilled, onRejected) { + var self = arguments.length ? this.then.apply(this, arguments) : this; + self.then(null, function (err) { + setTimeout(function () { + throw err; + }, 0); + }); }; /***/ }), -/***/ 18341: +/***/ 47492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(81205) -var fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes +"use strict"; -var noop = function () {} -var ancient = /^v?\.0/.test(process.version) -var isFn = function (fn) { - return typeof fn === 'function' -} +//This file contains the ES6 extensions to the core Promises/A+ API -var isFS = function (stream) { - if (!ancient) return false // newer node version do not need to care about fs is a special way - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} +var Promise = __nccwpck_require__(48874); -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) +module.exports = Promise; + +/* Static Functions */ + +var TRUE = valuePromise(true); +var FALSE = valuePromise(false); +var NULL = valuePromise(null); +var UNDEFINED = valuePromise(undefined); +var ZERO = valuePromise(0); +var EMPTYSTRING = valuePromise(''); + +function valuePromise(value) { + var p = new Promise(Promise._61); + p._65 = 1; + p._55 = value; + return p; } +Promise.resolve = function (value) { + if (value instanceof Promise) return value; -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + if (value === null) return NULL; + if (value === undefined) return UNDEFINED; + if (value === true) return TRUE; + if (value === false) return FALSE; + if (value === 0) return ZERO; + if (value === '') return EMPTYSTRING; - var closed = false - stream.on('close', function () { - closed = true - }) + if (typeof value === 'object' || typeof value === 'function') { + try { + var then = value.then; + if (typeof then === 'function') { + return new Promise(then.bind(value)); + } + } catch (ex) { + return new Promise(function (resolve, reject) { + reject(ex); + }); + } + } + return valuePromise(value); +}; - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) +Promise.all = function (arr) { + var args = Array.prototype.slice.call(arr); - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + return new Promise(function (resolve, reject) { + if (args.length === 0) return resolve([]); + var remaining = args.length; + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + if (val instanceof Promise && val.then === Promise.prototype.then) { + while (val._65 === 3) { + val = val._55; + } + if (val._65 === 1) return res(i, val._55); + if (val._65 === 2) reject(val._55); + val.then(function (val) { + res(i, val); + }, reject); + return; + } else { + var then = val.then; + if (typeof then === 'function') { + var p = new Promise(then.bind(val)); + p.then(function (val) { + res(i, val); + }, reject); + return; + } + } + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); +}; - if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want +Promise.reject = function (value) { + return new Promise(function (resolve, reject) { + reject(value); + }); +}; - if (isFn(stream.destroy)) return stream.destroy() +Promise.race = function (values) { + return new Promise(function (resolve, reject) { + values.forEach(function(value){ + Promise.resolve(value).then(resolve, reject); + }); + }); +}; - callback(err || new Error('stream was destroyed')) - } -} +/* Prototype Methods */ -var call = function (fn) { - fn() -} +Promise.prototype['catch'] = function (onRejected) { + return this.then(null, onRejected); +}; -var pipe = function (from, to) { - return from.pipe(to) -} -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop +/***/ }), - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') +/***/ 93963: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) +"use strict"; - return streams.reduce(pipe) -} -module.exports = pump +var Promise = __nccwpck_require__(48874); + +module.exports = Promise; +Promise.prototype['finally'] = function (f) { + return this.then(function (value) { + return Promise.resolve(f()).then(function () { + return value; + }); + }, function (err) { + return Promise.resolve(f()).then(function () { + throw err; + }); + }); +}; /***/ }), -/***/ 89795: -/***/ ((module) => { +/***/ 15836: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*! queue-microtask. MIT License. Feross Aboukhadijeh */ -let promise +"use strict"; -module.exports = typeof queueMicrotask === 'function' - ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) - // reuse resolved promise, and allocate it lazily - : cb => (promise || (promise = Promise.resolve())) - .then(cb) - .catch(err => setTimeout(() => { throw err }, 0)) + +module.exports = __nccwpck_require__(48874); +__nccwpck_require__(85222); +__nccwpck_require__(93963); +__nccwpck_require__(47492); +__nccwpck_require__(92090); +__nccwpck_require__(72995); /***/ }), -/***/ 80289: +/***/ 92090: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { SymbolDispose } = __nccwpck_require__(89629) -const { AbortError, codes } = __nccwpck_require__(80529) -const { isNodeStream, isWebStream, kControllerErrorFunction } = __nccwpck_require__(27981) -const eos = __nccwpck_require__(76080) -const { ERR_INVALID_ARG_TYPE } = codes -let addAbortListener +// This file contains then/promise specific extensions that are only useful +// for node.js interop -// This method is inlined here for readable-stream -// It also does not allow for signal to not exist on the stream -// https://github.com/nodejs/node/pull/36061#discussion_r533718029 -const validateAbortSignal = (signal, name) => { - if (typeof signal !== 'object' || !('aborted' in signal)) { - throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) +var Promise = __nccwpck_require__(48874); +var asap = __nccwpck_require__(87943); + +module.exports = Promise; + +/* Static Functions */ + +Promise.denodeify = function (fn, argumentCount) { + if ( + typeof argumentCount === 'number' && argumentCount !== Infinity + ) { + return denodeifyWithCount(fn, argumentCount); + } else { + return denodeifyWithoutCount(fn); } -} -module.exports.addAbortSignal = function addAbortSignal(signal, stream) { - validateAbortSignal(signal, 'signal') - if (!isNodeStream(stream) && !isWebStream(stream)) { - throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) +}; + +var callbackFn = ( + 'function (err, res) {' + + 'if (err) { rj(err); } else { rs(res); }' + + '}' +); +function denodeifyWithCount(fn, argumentCount) { + var args = []; + for (var i = 0; i < argumentCount; i++) { + args.push('a' + i); } - return module.exports.addAbortSignalNoValidate(signal, stream) + var body = [ + 'return function (' + args.join(',') + ') {', + 'var self = this;', + 'return new Promise(function (rs, rj) {', + 'var res = fn.call(', + ['self'].concat(args).concat([callbackFn]).join(','), + ');', + 'if (res &&', + '(typeof res === "object" || typeof res === "function") &&', + 'typeof res.then === "function"', + ') {rs(res);}', + '});', + '};' + ].join(''); + return Function(['Promise', 'fn'], body)(Promise, fn); } -module.exports.addAbortSignalNoValidate = function (signal, stream) { - if (typeof signal !== 'object' || !('aborted' in signal)) { - return stream +function denodeifyWithoutCount(fn) { + var fnLength = Math.max(fn.length - 1, 3); + var args = []; + for (var i = 0; i < fnLength; i++) { + args.push('a' + i); } - const onAbort = isNodeStream(stream) - ? () => { - stream.destroy( - new AbortError(undefined, { - cause: signal.reason - }) - ) - } - : () => { - stream[kControllerErrorFunction]( - new AbortError(undefined, { - cause: signal.reason - }) - ) + var body = [ + 'return function (' + args.join(',') + ') {', + 'var self = this;', + 'var args;', + 'var argLength = arguments.length;', + 'if (arguments.length > ' + fnLength + ') {', + 'args = new Array(arguments.length + 1);', + 'for (var i = 0; i < arguments.length; i++) {', + 'args[i] = arguments[i];', + '}', + '}', + 'return new Promise(function (rs, rj) {', + 'var cb = ' + callbackFn + ';', + 'var res;', + 'switch (argLength) {', + args.concat(['extra']).map(function (_, index) { + return ( + 'case ' + (index) + ':' + + 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' + + 'break;' + ); + }).join(''), + 'default:', + 'args[argLength] = cb;', + 'res = fn.apply(self, args);', + '}', + + 'if (res &&', + '(typeof res === "object" || typeof res === "function") &&', + 'typeof res.then === "function"', + ') {rs(res);}', + '});', + '};' + ].join(''); + + return Function( + ['Promise', 'fn'], + body + )(Promise, fn); +} + +Promise.nodeify = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + var callback = + typeof args[args.length - 1] === 'function' ? args.pop() : null; + var ctx = this; + try { + return fn.apply(this, arguments).nodeify(callback, ctx); + } catch (ex) { + if (callback === null || typeof callback == 'undefined') { + return new Promise(function (resolve, reject) { + reject(ex); + }); + } else { + asap(function () { + callback.call(ctx, ex); + }) } - if (signal.aborted) { - onAbort() - } else { - addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) - const disposable = addAbortListener(signal, onAbort) - eos(stream, disposable[SymbolDispose]) + } } - return stream -} +}; + +Promise.prototype.nodeify = function (callback, ctx) { + if (typeof callback != 'function') return this; + + this.then(function (value) { + asap(function () { + callback.call(ctx, null, value); + }); + }, function (err) { + asap(function () { + callback.call(ctx, err); + }); + }); +}; /***/ }), -/***/ 52746: +/***/ 72995: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = __nccwpck_require__(89629) -const { Buffer } = __nccwpck_require__(14300) -const { inspect } = __nccwpck_require__(46959) -module.exports = class BufferList { - constructor() { - this.head = null - this.tail = null - this.length = 0 - } - push(v) { - const entry = { - data: v, - next: null +var Promise = __nccwpck_require__(48874); + +module.exports = Promise; +Promise.enableSynchronous = function () { + Promise.prototype.isPending = function() { + return this.getState() == 0; + }; + + Promise.prototype.isFulfilled = function() { + return this.getState() == 1; + }; + + Promise.prototype.isRejected = function() { + return this.getState() == 2; + }; + + Promise.prototype.getValue = function () { + if (this._65 === 3) { + return this._55.getValue(); } - if (this.length > 0) this.tail.next = entry - else this.head = entry - this.tail = entry - ++this.length - } - unshift(v) { - const entry = { - data: v, - next: this.head + + if (!this.isFulfilled()) { + throw new Error('Cannot get a value of an unfulfilled promise.'); } - if (this.length === 0) this.tail = entry - this.head = entry - ++this.length - } - shift() { - if (this.length === 0) return - const ret = this.head.data - if (this.length === 1) this.head = this.tail = null - else this.head = this.head.next - --this.length - return ret - } - clear() { - this.head = this.tail = null - this.length = 0 - } - join(s) { - if (this.length === 0) return '' - let p = this.head - let ret = '' + p.data - while ((p = p.next) !== null) ret += s + p.data - return ret - } - concat(n) { - if (this.length === 0) return Buffer.alloc(0) - const ret = Buffer.allocUnsafe(n >>> 0) - let p = this.head - let i = 0 - while (p) { - TypedArrayPrototypeSet(ret, p.data, i) - i += p.data.length - p = p.next + + return this._55; + }; + + Promise.prototype.getReason = function () { + if (this._65 === 3) { + return this._55.getReason(); } - return ret - } - // Consumes a specified amount of bytes or characters from the buffered data. - consume(n, hasStrings) { - const data = this.head.data - if (n < data.length) { - // `slice` is the same for buffers and strings. - const slice = data.slice(0, n) - this.head.data = data.slice(n) - return slice + if (!this.isRejected()) { + throw new Error('Cannot get a rejection reason of a non-rejected promise.'); } - if (n === data.length) { - // First chunk is a perfect match. - return this.shift() + + return this._55; + }; + + Promise.prototype.getState = function () { + if (this._65 === 3) { + return this._55.getState(); } - // Result spans more than one buffer. - return hasStrings ? this._getString(n) : this._getBuffer(n) - } - first() { - return this.head.data - } - *[SymbolIterator]() { - for (let p = this.head; p; p = p.next) { - yield p.data + if (this._65 === -1 || this._65 === -2) { + return 0; } - } - - // Consumes a specified amount of characters from the buffered data. - _getString(n) { - let ret = '' - let p = this.head - let c = 0 - do { - const str = p.data - if (n > str.length) { - ret += str - n -= str.length - } else { - if (n === str.length) { - ret += str - ++c - if (p.next) this.head = p.next - else this.head = this.tail = null - } else { - ret += StringPrototypeSlice(str, 0, n) - this.head = p - p.data = StringPrototypeSlice(str, n) - } - break - } - ++c - } while ((p = p.next) !== null) - this.length -= c - return ret - } - // Consumes a specified amount of bytes from the buffered data. - _getBuffer(n) { - const ret = Buffer.allocUnsafe(n) - const retLen = n - let p = this.head - let c = 0 - do { - const buf = p.data - if (n > buf.length) { - TypedArrayPrototypeSet(ret, buf, retLen - n) - n -= buf.length - } else { - if (n === buf.length) { - TypedArrayPrototypeSet(ret, buf, retLen - n) - ++c - if (p.next) this.head = p.next - else this.head = this.tail = null - } else { - TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) - this.head = p - p.data = buf.slice(n) - } - break - } - ++c - } while ((p = p.next) !== null) - this.length -= c - return ret - } + return this._65; + }; +}; - // Make sure the linked list only shows the minimal necessary information. - [Symbol.for('nodejs.util.inspect.custom')](_, options) { - return inspect(this, { - ...options, - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - }) - } -} +Promise.disableSynchronous = function() { + Promise.prototype.isPending = undefined; + Promise.prototype.isFulfilled = undefined; + Promise.prototype.isRejected = undefined; + Promise.prototype.getValue = undefined; + Promise.prototype.getReason = undefined; + Promise.prototype.getState = undefined; +}; /***/ }), -/***/ 63129: +/***/ 11322: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { pipeline } = __nccwpck_require__(76989) -const Duplex = __nccwpck_require__(72613) -const { destroyer } = __nccwpck_require__(97049) -const { - isNodeStream, - isReadable, - isWritable, - isWebStream, - isTransformStream, - isWritableStream, - isReadableStream -} = __nccwpck_require__(27981) -const { - AbortError, - codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } -} = __nccwpck_require__(80529) -const eos = __nccwpck_require__(76080) -module.exports = function compose(...streams) { - if (streams.length === 0) { - throw new ERR_MISSING_ARGS('streams') - } - if (streams.length === 1) { - return Duplex.from(streams[0]) - } - const orgStreams = [...streams] - if (typeof streams[0] === 'function') { - streams[0] = Duplex.from(streams[0]) - } - if (typeof streams[streams.length - 1] === 'function') { - const idx = streams.length - 1 - streams[idx] = Duplex.from(streams[idx]) - } - for (let n = 0; n < streams.length; ++n) { - if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { - // TODO(ronag): Add checks for non streams. - continue - } - if ( - n < streams.length - 1 && - !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) - ) { - throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') - } - if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { - throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') - } - } - let ondrain - let onfinish - let onreadable - let onclose - let d - function onfinished(err) { - const cb = onclose - onclose = null - if (cb) { - cb(err) - } else if (err) { - d.destroy(err) - } else if (!readable && !writable) { - d.destroy() - } - } - const head = streams[0] - const tail = pipeline(streams, onfinished) - const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) - const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) +var assert = __nccwpck_require__(39491); +var constantinople = __nccwpck_require__(40953); +var runtime = __nccwpck_require__(27596); +var stringify = __nccwpck_require__(94878); + +function isConstant(src) { + return constantinople(src, {pug: runtime, pug_interp: undefined}); +} +function toConstant(src) { + return constantinople.toConstant(src, {pug: runtime, pug_interp: undefined}); +} - // TODO(ronag): Avoid double buffering. - // Implement Writable/Readable/Duplex traits. - // See, https://github.com/nodejs/node/pull/33515. - d = new Duplex({ - // TODO (ronag): highWaterMark? - writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), - readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), - writable, - readable - }) - if (writable) { - if (isNodeStream(head)) { - d._write = function (chunk, encoding, callback) { - if (head.write(chunk, encoding)) { - callback() +module.exports = compileAttrs; +/** + * options: + * - terse + * - runtime + * - format ('html' || 'object') + */ +function compileAttrs(attrs, options) { + assert(Array.isArray(attrs), 'Attrs should be an array'); + assert( + attrs.every(function(attr) { + return ( + attr && + typeof attr === 'object' && + typeof attr.name === 'string' && + (typeof attr.val === 'string' || typeof attr.val === 'boolean') && + typeof attr.mustEscape === 'boolean' + ); + }), + 'All attributes should be supplied as an object of the form {name, val, mustEscape}' + ); + assert(options && typeof options === 'object', 'Options should be an object'); + assert( + typeof options.terse === 'boolean', + 'Options.terse should be a boolean' + ); + assert( + typeof options.runtime === 'function', + 'Options.runtime should be a function that takes a runtime function name and returns the source code that will evaluate to that function at runtime' + ); + assert( + options.format === 'html' || options.format === 'object', + 'Options.format should be "html" or "object"' + ); + + var buf = []; + var classes = []; + var classEscaping = []; + + function addAttribute(key, val, mustEscape, buf) { + if (isConstant(val)) { + if (options.format === 'html') { + var str = stringify( + runtime.attr(key, toConstant(val), mustEscape, options.terse) + ); + var last = buf[buf.length - 1]; + if (last && last[last.length - 1] === str[0]) { + buf[buf.length - 1] = last.substr(0, last.length - 1) + str.substr(1); } else { - ondrain = callback - } - } - d._final = function (callback) { - head.end() - onfinish = callback - } - head.on('drain', function () { - if (ondrain) { - const cb = ondrain - ondrain = null - cb() + buf.push(str); } - }) - } else if (isWebStream(head)) { - const writable = isTransformStream(head) ? head.writable : head - const writer = writable.getWriter() - d._write = async function (chunk, encoding, callback) { - try { - await writer.ready - writer.write(chunk).catch(() => {}) - callback() - } catch (err) { - callback(err) + } else { + val = toConstant(val); + if (mustEscape) { + val = runtime.escape(val); } + buf.push(stringify(key) + ': ' + stringify(val)); } - d._final = async function (callback) { - try { - await writer.ready - writer.close().catch(() => {}) - onfinish = callback - } catch (err) { - callback(err) + } else { + if (options.format === 'html') { + buf.push( + options.runtime('attr') + + '("' + + key + + '", ' + + val + + ', ' + + stringify(mustEscape) + + ', ' + + stringify(options.terse) + + ')' + ); + } else { + if (mustEscape) { + val = options.runtime('escape') + '(' + val + ')'; } + buf.push(stringify(key) + ': ' + val); } } - const toRead = isTransformStream(tail) ? tail.readable : tail - eos(toRead, () => { - if (onfinish) { - const cb = onfinish - onfinish = null - cb() - } - }) } - if (readable) { - if (isNodeStream(tail)) { - tail.on('readable', function () { - if (onreadable) { - const cb = onreadable - onreadable = null - cb() - } - }) - tail.on('end', function () { - d.push(null) - }) - d._read = function () { - while (true) { - const buf = tail.read() - if (buf === null) { - onreadable = d._read - return - } - if (!d.push(buf)) { - return - } - } - } - } else if (isWebStream(tail)) { - const readable = isTransformStream(tail) ? tail.readable : tail - const reader = readable.getReader() - d._read = async function () { - while (true) { - try { - const { value, done } = await reader.read() - if (!d.push(value)) { - return - } - if (done) { - d.push(null) - return - } - } catch { - return - } + + attrs.forEach(function(attr) { + var key = attr.name; + var val = attr.val; + var mustEscape = attr.mustEscape; + + if (key === 'class') { + classes.push(val); + classEscaping.push(mustEscape); + } else { + if (key === 'style') { + if (isConstant(val)) { + val = stringify(runtime.style(toConstant(val))); + } else { + val = options.runtime('style') + '(' + val + ')'; } } + addAttribute(key, val, mustEscape, buf); } - } - d._destroy = function (err, callback) { - if (!err && onclose !== null) { - err = new AbortError() - } - onreadable = null - ondrain = null - onfinish = null - if (onclose === null) { - callback(err) + }); + var classesBuf = []; + if (classes.length) { + if (classes.every(isConstant)) { + addAttribute( + 'class', + stringify(runtime.classes(classes.map(toConstant), classEscaping)), + false, + classesBuf + ); } else { - onclose = callback - if (isNodeStream(tail)) { - destroyer(tail, err) - } + classes = classes.map(function(cls, i) { + if (isConstant(cls)) { + cls = stringify( + classEscaping[i] ? runtime.escape(toConstant(cls)) : toConstant(cls) + ); + classEscaping[i] = false; + } + return cls; + }); + addAttribute( + 'class', + options.runtime('classes') + + '([' + + classes.join(',') + + '], ' + + stringify(classEscaping) + + ')', + false, + classesBuf + ); } } - return d + buf = classesBuf.concat(buf); + if (options.format === 'html') return buf.length ? buf.join('+') : '""'; + else return '{' + buf.join(',') + '}'; } /***/ }), -/***/ 97049: +/***/ 90331: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* replacement start */ - -const process = __nccwpck_require__(45676) +var doctypes = __nccwpck_require__(3194); +var makeError = __nccwpck_require__(66198); +var buildRuntime = __nccwpck_require__(37364); +var runtime = __nccwpck_require__(27596); +var compileAttrs = __nccwpck_require__(11322); +var selfClosing = __nccwpck_require__(97529); +var constantinople = __nccwpck_require__(40953); +var stringify = __nccwpck_require__(94878); +var addWith = __nccwpck_require__(78904); -/* replacement end */ +// This is used to prevent pretty printing inside certain tags +var WHITE_SPACE_SENSITIVE_TAGS = { + pre: true, + textarea: true, +}; -const { - aggregateTwoErrors, - codes: { ERR_MULTIPLE_CALLBACK }, - AbortError -} = __nccwpck_require__(80529) -const { Symbol } = __nccwpck_require__(89629) -const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = __nccwpck_require__(27981) -const kDestroy = Symbol('kDestroy') -const kConstruct = Symbol('kConstruct') -function checkError(err, w, r) { - if (err) { - // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 - err.stack // eslint-disable-line no-unused-expressions +var INTERNAL_VARIABLES = [ + 'pug', + 'pug_mixins', + 'pug_interp', + 'pug_debug_filename', + 'pug_debug_line', + 'pug_debug_sources', + 'pug_html', +]; - if (w && !w.errored) { - w.errored = err - } - if (r && !r.errored) { - r.errored = err - } - } +module.exports = generateCode; +module.exports.CodeGenerator = Compiler; +function generateCode(ast, options) { + return new Compiler(ast, options).compile(); } -// Backwards compat. cb() is undocumented and unused in core but -// unfortunately might be used by modules. -function destroy(err, cb) { - const r = this._readableState - const w = this._writableState - // With duplex streams we use the writable side for state. - const s = w || r - if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { - if (typeof cb === 'function') { - cb() - } - return this - } - - // We set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - checkError(err, w, r) - if (w) { - w.destroyed = true - } - if (r) { - r.destroyed = true - } - - // If still constructing then defer calling _destroy. - if (!s.constructed) { - this.once(kDestroy, function (er) { - _destroy(this, aggregateTwoErrors(er, err), cb) - }) - } else { - _destroy(this, err, cb) - } - return this +function isConstant(src) { + return constantinople(src, {pug: runtime, pug_interp: undefined}); } -function _destroy(self, err, cb) { - let called = false - function onDestroy(err) { - if (called) { - return - } - called = true - const r = self._readableState - const w = self._writableState - checkError(err, w, r) - if (w) { - w.closed = true - } - if (r) { - r.closed = true - } - if (typeof cb === 'function') { - cb(err) - } - if (err) { - process.nextTick(emitErrorCloseNT, self, err) - } else { - process.nextTick(emitCloseNT, self) - } - } - try { - self._destroy(err || null, onDestroy) - } catch (err) { - onDestroy(err) - } +function toConstant(src) { + return constantinople.toConstant(src, {pug: runtime, pug_interp: undefined}); } -function emitErrorCloseNT(self, err) { - emitErrorNT(self, err) - emitCloseNT(self) + +function isIdentifier(name) { + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name); } -function emitCloseNT(self) { - const r = self._readableState - const w = self._writableState - if (w) { - w.closeEmitted = true - } - if (r) { - r.closeEmitted = true - } - if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { - self.emit('close') + +/** + * Initialize `Compiler` with the given `node`. + * + * @param {Node} node + * @param {Object} options + * @api public + */ + +function Compiler(node, options) { + this.options = options = options || {}; + this.node = node; + this.bufferedConcatenationCount = 0; + this.hasCompiledDoctype = false; + this.hasCompiledTag = false; + this.pp = options.pretty || false; + if (this.pp && typeof this.pp !== 'string') { + this.pp = ' '; } -} -function emitErrorNT(self, err) { - const r = self._readableState - const w = self._writableState - if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { - return + if (this.pp && !/^\s+$/.test(this.pp)) { + throw new Error( + 'The pretty parameter should either be a boolean or whitespace only string' + ); } - if (w) { - w.errorEmitted = true + if (this.options.templateName && !isIdentifier(this.options.templateName)) { + throw new Error( + 'The templateName parameter must be a valid JavaScript identifier if specified.' + ); } - if (r) { - r.errorEmitted = true + if ( + this.doctype && + (this.doctype.includes('<') || this.doctype.includes('>')) + ) { + throw new Error('Doctype can not contain "<" or ">"'); } - self.emit('error', err) -} -function undestroy() { - const r = this._readableState - const w = this._writableState - if (r) { - r.constructed = true - r.closed = false - r.closeEmitted = false - r.destroyed = false - r.errored = null - r.errorEmitted = false - r.reading = false - r.ended = r.readable === false - r.endEmitted = r.readable === false + if (this.options.globals && !this.options.globals.every(isIdentifier)) { + throw new Error( + 'The globals option must be an array of valid JavaScript identifiers if specified.' + ); } - if (w) { - w.constructed = true - w.destroyed = false - w.closed = false - w.closeEmitted = false - w.errored = null - w.errorEmitted = false - w.finalCalled = false - w.prefinished = false - w.ended = w.writable === false - w.ending = w.writable === false - w.finished = w.writable === false + + this.debug = false !== options.compileDebug; + this.indents = 0; + this.parentIndents = 0; + this.terse = false; + this.mixins = {}; + this.dynamicMixins = false; + this.eachCount = 0; + if (options.doctype) this.setDoctype(options.doctype); + this.runtimeFunctionsUsed = []; + this.inlineRuntimeFunctions = options.inlineRuntimeFunctions || false; + if (this.debug && this.inlineRuntimeFunctions) { + this.runtimeFunctionsUsed.push('rethrow'); } } -function errorOrDestroy(stream, err, sync) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - const r = stream._readableState - const w = stream._writableState - if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { - return this - } - if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) - stream.destroy(err) - else if (err) { - // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 - err.stack // eslint-disable-line no-unused-expressions +/** + * Compiler prototype. + */ - if (w && !w.errored) { - w.errored = err - } - if (r && !r.errored) { - r.errored = err - } - if (sync) { - process.nextTick(emitErrorNT, stream, err) +Compiler.prototype = { + runtime: function(name) { + if (this.inlineRuntimeFunctions) { + this.runtimeFunctionsUsed.push(name); + return 'pug_' + name; } else { - emitErrorNT(stream, err) - } - } -} -function construct(stream, cb) { - if (typeof stream._construct !== 'function') { - return - } - const r = stream._readableState - const w = stream._writableState - if (r) { - r.constructed = false - } - if (w) { - w.constructed = false - } - stream.once(kConstruct, cb) - if (stream.listenerCount(kConstruct) > 1) { - // Duplex - return - } - process.nextTick(constructNT, stream) -} -function constructNT(stream) { - let called = false - function onConstruct(err) { - if (called) { - errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) - return - } - called = true - const r = stream._readableState - const w = stream._writableState - const s = w || r - if (r) { - r.constructed = true + return 'pug.' + name; } - if (w) { - w.constructed = true + }, + + error: function(message, code, node) { + var err = makeError(code, message, { + line: node.line, + column: node.column, + filename: node.filename, + }); + throw err; + }, + + /** + * Compile parse tree to JavaScript. + * + * @api public + */ + + compile: function() { + this.buf = []; + if (this.pp) this.buf.push('var pug_indent = [];'); + this.lastBufferedIdx = -1; + this.visit(this.node); + if (!this.dynamicMixins) { + // if there are no dynamic mixins we can remove any un-used mixins + var mixinNames = Object.keys(this.mixins); + for (var i = 0; i < mixinNames.length; i++) { + var mixin = this.mixins[mixinNames[i]]; + if (!mixin.used) { + for (var x = 0; x < mixin.instances.length; x++) { + for ( + var y = mixin.instances[x].start; + y < mixin.instances[x].end; + y++ + ) { + this.buf[y] = ''; + } + } + } + } } - if (s.destroyed) { - stream.emit(kDestroy, err) - } else if (err) { - errorOrDestroy(stream, err, true) + var js = this.buf.join('\n'); + var globals = this.options.globals + ? this.options.globals.concat(INTERNAL_VARIABLES) + : INTERNAL_VARIABLES; + if (this.options.self) { + js = 'var self = locals || {};' + js; } else { - process.nextTick(emitConstructNT, stream) + js = addWith( + 'locals || {}', + js, + globals.concat( + this.runtimeFunctionsUsed.map(function(name) { + return 'pug_' + name; + }) + ) + ); + } + if (this.debug) { + if (this.options.includeSources) { + js = + 'var pug_debug_sources = ' + + stringify(this.options.includeSources) + + ';\n' + + js; + } + js = + 'var pug_debug_filename, pug_debug_line;' + + 'try {' + + js + + '} catch (err) {' + + (this.inlineRuntimeFunctions ? 'pug_rethrow' : 'pug.rethrow') + + '(err, pug_debug_filename, pug_debug_line' + + (this.options.includeSources + ? ', pug_debug_sources[pug_debug_filename]' + : '') + + ');' + + '}'; } - } - try { - stream._construct((err) => { - process.nextTick(onConstruct, err) - }) - } catch (err) { - process.nextTick(onConstruct, err) - } -} -function emitConstructNT(stream) { - stream.emit(kConstruct) -} -function isRequest(stream) { - return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' -} -function emitCloseLegacy(stream) { - stream.emit('close') -} -function emitErrorCloseLegacy(stream, err) { - stream.emit('error', err) - process.nextTick(emitCloseLegacy, stream) -} - -// Normalize destroy for legacy. -function destroyer(stream, err) { - if (!stream || isDestroyed(stream)) { - return - } - if (!err && !isFinished(stream)) { - err = new AbortError() - } - // TODO: Remove isRequest branches. - if (isServerRequest(stream)) { - stream.socket = null - stream.destroy(err) - } else if (isRequest(stream)) { - stream.abort() - } else if (isRequest(stream.req)) { - stream.req.abort() - } else if (typeof stream.destroy === 'function') { - stream.destroy(err) - } else if (typeof stream.close === 'function') { - // TODO: Don't lose err? - stream.close() - } else if (err) { - process.nextTick(emitErrorCloseLegacy, stream, err) - } else { - process.nextTick(emitCloseLegacy, stream) - } - if (!stream.destroyed) { - stream[kIsDestroyed] = true - } -} -module.exports = { - construct, - destroyer, - destroy, - undestroy, - errorOrDestroy -} + return ( + buildRuntime(this.runtimeFunctionsUsed) + + 'function ' + + (this.options.templateName || 'template') + + '(locals) {var pug_html = "", pug_mixins = {}, pug_interp;' + + js + + ';return pug_html;}' + ); + }, + /** + * Sets the default doctype `name`. Sets terse mode to `true` when + * html 5 is used, causing self-closing tags to end with ">" vs "/>", + * and boolean attributes are not mirrored. + * + * @param {string} name + * @api public + */ -/***/ }), + setDoctype: function(name) { + this.doctype = doctypes[name.toLowerCase()] || ''; + this.terse = this.doctype.toLowerCase() == ''; + this.xml = 0 == this.doctype.indexOf(' { + /** + * Buffer the given `str` exactly as is or with interpolation + * + * @param {String} str + * @param {Boolean} interpolate + * @api public + */ -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + buffer: function(str) { + var self = this; -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototype inheritance, this class -// prototypically inherits from Readable, and then parasitically from -// Writable. + str = stringify(str); + str = str.substr(1, str.length - 2); + if ( + this.lastBufferedIdx == this.buf.length && + this.bufferedConcatenationCount < 100 + ) { + if (this.lastBufferedType === 'code') { + this.lastBuffered += ' + "'; + this.bufferedConcatenationCount++; + } + this.lastBufferedType = 'text'; + this.lastBuffered += str; + this.buf[this.lastBufferedIdx - 1] = + 'pug_html = pug_html + ' + + this.bufferStartChar + + this.lastBuffered + + '";'; + } else { + this.bufferedConcatenationCount = 0; + this.buf.push('pug_html = pug_html + "' + str + '";'); + this.lastBufferedType = 'text'; + this.bufferStartChar = '"'; + this.lastBuffered = str; + this.lastBufferedIdx = this.buf.length; + } + }, + /** + * Buffer the given `src` so it is evaluated at run time + * + * @param {String} src + * @api public + */ -const { - ObjectDefineProperties, - ObjectGetOwnPropertyDescriptor, - ObjectKeys, - ObjectSetPrototypeOf -} = __nccwpck_require__(89629) -module.exports = Duplex -const Readable = __nccwpck_require__(57920) -const Writable = __nccwpck_require__(48488) -ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) -ObjectSetPrototypeOf(Duplex, Readable) -{ - const keys = ObjectKeys(Writable.prototype) - // Allow the keys array to be GC'ed. - for (let i = 0; i < keys.length; i++) { - const method = keys[i] - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] - } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options) - Readable.call(this, options) - Writable.call(this, options) - if (options) { - this.allowHalfOpen = options.allowHalfOpen !== false - if (options.readable === false) { - this._readableState.readable = false - this._readableState.ended = true - this._readableState.endEmitted = true + bufferExpression: function(src) { + if (isConstant(src)) { + return this.buffer(toConstant(src) + ''); } - if (options.writable === false) { - this._writableState.writable = false - this._writableState.ending = true - this._writableState.ended = true - this._writableState.finished = true + if ( + this.lastBufferedIdx == this.buf.length && + this.bufferedConcatenationCount < 100 + ) { + this.bufferedConcatenationCount++; + if (this.lastBufferedType === 'text') this.lastBuffered += '"'; + this.lastBufferedType = 'code'; + this.lastBuffered += ' + (' + src + ')'; + this.buf[this.lastBufferedIdx - 1] = + 'pug_html = pug_html + (' + + this.bufferStartChar + + this.lastBuffered + + ');'; + } else { + this.bufferedConcatenationCount = 0; + this.buf.push('pug_html = pug_html + (' + src + ');'); + this.lastBufferedType = 'code'; + this.bufferStartChar = ''; + this.lastBuffered = '(' + src + ')'; + this.lastBufferedIdx = this.buf.length; } - } else { - this.allowHalfOpen = true - } -} -ObjectDefineProperties(Duplex.prototype, { - writable: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') - }, - writableHighWaterMark: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') }, - writableObjectMode: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') + + /** + * Buffer an indent based on the current `indent` + * property and an additional `offset`. + * + * @param {Number} offset + * @param {Boolean} newline + * @api public + */ + + prettyIndent: function(offset, newline) { + offset = offset || 0; + newline = newline ? '\n' : ''; + this.buffer(newline + Array(this.indents + offset).join(this.pp)); + if (this.parentIndents) + this.buf.push('pug_html = pug_html + pug_indent.join("");'); }, - writableBuffer: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') + + /** + * Visit `node`. + * + * @param {Node} node + * @api public + */ + + visit: function(node, parent) { + var debug = this.debug; + + if (!node) { + var msg; + if (parent) { + msg = + 'A child of ' + + parent.type + + ' (' + + (parent.filename || 'Pug') + + ':' + + parent.line + + ')'; + } else { + msg = 'A top-level node'; + } + msg += ' is ' + node + ', expected a Pug AST Node.'; + throw new TypeError(msg); + } + + if (debug && node.debug !== false && node.type !== 'Block') { + if (node.line) { + var js = ';pug_debug_line = ' + node.line; + if (node.filename) + js += ';pug_debug_filename = ' + stringify(node.filename); + this.buf.push(js + ';'); + } + } + + if (!this['visit' + node.type]) { + var msg; + if (parent) { + msg = 'A child of ' + parent.type; + } else { + msg = 'A top-level node'; + } + msg += + ' (' + + (node.filename || 'Pug') + + ':' + + node.line + + ')' + + ' is of type ' + + node.type + + ',' + + ' which is not supported by pug-code-gen.'; + switch (node.type) { + case 'Filter': + msg += ' Please use pug-filters to preprocess this AST.'; + break; + case 'Extends': + case 'Include': + case 'NamedBlock': + case 'FileReference': // unlikely but for the sake of completeness + msg += ' Please use pug-linker to preprocess this AST.'; + break; + } + throw new TypeError(msg); + } + + this.visitNode(node); }, - writableLength: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') + + /** + * Visit `node`. + * + * @param {Node} node + * @api public + */ + + visitNode: function(node) { + return this['visit' + node.type](node); }, - writableFinished: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') + + /** + * Visit case `node`. + * + * @param {Literal} node + * @api public + */ + + visitCase: function(node) { + this.buf.push('switch (' + node.expr + '){'); + this.visit(node.block, node); + this.buf.push('}'); }, - writableCorked: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') + + /** + * Visit when `node`. + * + * @param {Literal} node + * @api public + */ + + visitWhen: function(node) { + if ('default' == node.expr) { + this.buf.push('default:'); + } else { + this.buf.push('case ' + node.expr + ':'); + } + if (node.block) { + this.visit(node.block, node); + this.buf.push(' break;'); + } }, - writableEnded: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') + + /** + * Visit literal `node`. + * + * @param {Literal} node + * @api public + */ + + visitLiteral: function(node) { + this.buffer(node.str); }, - writableNeedDrain: { - __proto__: null, - ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') + + visitNamedBlock: function(block) { + return this.visitBlock(block); }, - destroyed: { - __proto__: null, - get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false - } - return this._readableState.destroyed && this._writableState.destroyed - }, - set(value) { - // Backward compatibility, the user is explicitly - // managing destroyed. - if (this._readableState && this._writableState) { - this._readableState.destroyed = value - this._writableState.destroyed = value + /** + * Visit all nodes in `block`. + * + * @param {Block} block + * @api public + */ + + visitBlock: function(block) { + var escapePrettyMode = this.escapePrettyMode; + var pp = this.pp; + + // Pretty print multi-line text + if ( + pp && + block.nodes.length > 1 && + !escapePrettyMode && + block.nodes[0].type === 'Text' && + block.nodes[1].type === 'Text' + ) { + this.prettyIndent(1, true); + } + for (var i = 0; i < block.nodes.length; ++i) { + // Pretty print text + if ( + pp && + i > 0 && + !escapePrettyMode && + block.nodes[i].type === 'Text' && + block.nodes[i - 1].type === 'Text' && + /\n$/.test(block.nodes[i - 1].val) + ) { + this.prettyIndent(1, false); } + this.visit(block.nodes[i], block); } - } -}) -let webStreamsAdapters + }, -// Lazy to avoid circular references -function lazyWebStreams() { - if (webStreamsAdapters === undefined) webStreamsAdapters = {} - return webStreamsAdapters -} -Duplex.fromWeb = function (pair, options) { - return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) -} -Duplex.toWeb = function (duplex) { - return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) -} -let duplexify -Duplex.from = function (body) { - if (!duplexify) { - duplexify = __nccwpck_require__(86350) - } - return duplexify(body, 'body') -} + /** + * Visit a mixin's `block` keyword. + * + * @param {MixinBlock} block + * @api public + */ + visitMixinBlock: function(block) { + if (this.pp) + this.buf.push( + 'pug_indent.push(' + + stringify(Array(this.indents + 1).join(this.pp)) + + ');' + ); + this.buf.push('block && block();'); + if (this.pp) this.buf.push('pug_indent.pop();'); + }, -/***/ }), + /** + * Visit `doctype`. Sets terse mode to `true` when html 5 + * is used, causing self-closing tags to end with ">" vs "/>", + * and boolean attributes are not mirrored. + * + * @param {Doctype} doctype + * @api public + */ -/***/ 86350: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + visitDoctype: function(doctype) { + if (doctype && (doctype.val || !this.doctype)) { + this.setDoctype(doctype.val || 'html'); + } -/* replacement start */ + if (this.doctype) this.buffer(this.doctype); + this.hasCompiledDoctype = true; + }, -const process = __nccwpck_require__(45676) + /** + * Visit `mixin`, generating a function that + * may be called within the template. + * + * @param {Mixin} mixin + * @api public + */ -/* replacement end */ + visitMixin: function(mixin) { + var name = 'pug_mixins['; + var args = mixin.args || ''; + var block = mixin.block; + var attrs = mixin.attrs; + var attrsBlocks = this.attributeBlocks(mixin.attributeBlocks); + var pp = this.pp; + var dynamic = mixin.name[0] === '#'; + var key = mixin.name; + if (dynamic) this.dynamicMixins = true; + name += + (dynamic + ? mixin.name.substr(2, mixin.name.length - 3) + : '"' + mixin.name + '"') + ']'; -;('use strict') -const bufferModule = __nccwpck_require__(14300) -const { - isReadable, - isWritable, - isIterable, - isNodeStream, - isReadableNodeStream, - isWritableNodeStream, - isDuplexNodeStream, - isReadableStream, - isWritableStream -} = __nccwpck_require__(27981) -const eos = __nccwpck_require__(76080) -const { - AbortError, - codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } -} = __nccwpck_require__(80529) -const { destroyer } = __nccwpck_require__(97049) -const Duplex = __nccwpck_require__(72613) -const Readable = __nccwpck_require__(57920) -const Writable = __nccwpck_require__(48488) -const { createDeferredPromise } = __nccwpck_require__(46959) -const from = __nccwpck_require__(39082) -const Blob = globalThis.Blob || bufferModule.Blob -const isBlob = - typeof Blob !== 'undefined' - ? function isBlob(b) { - return b instanceof Blob - } - : function isBlob(b) { - return false - } -const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) -const { FunctionPrototypeCall } = __nccwpck_require__(89629) + this.mixins[key] = this.mixins[key] || {used: false, instances: []}; + if (mixin.call) { + this.mixins[key].used = true; + if (pp) + this.buf.push( + 'pug_indent.push(' + + stringify(Array(this.indents + 1).join(pp)) + + ');' + ); + if (block || attrs.length || attrsBlocks.length) { + this.buf.push(name + '.call({'); -// This is needed for pre node 17. -class Duplexify extends Duplex { - constructor(options) { - super(options) + if (block) { + this.buf.push('block: function(){'); - // https://github.com/nodejs/node/pull/34385 + // Render block with no indents, dynamically added when rendered + this.parentIndents++; + var _indents = this.indents; + this.indents = 0; + this.visit(mixin.block, mixin); + this.indents = _indents; + this.parentIndents--; - if ((options === null || options === undefined ? undefined : options.readable) === false) { - this._readableState.readable = false - this._readableState.ended = true - this._readableState.endEmitted = true - } - if ((options === null || options === undefined ? undefined : options.writable) === false) { - this._writableState.writable = false - this._writableState.ending = true - this._writableState.ended = true - this._writableState.finished = true - } - } -} -module.exports = function duplexify(body, name) { - if (isDuplexNodeStream(body)) { - return body - } - if (isReadableNodeStream(body)) { - return _duplexify({ - readable: body - }) - } - if (isWritableNodeStream(body)) { - return _duplexify({ - writable: body - }) - } - if (isNodeStream(body)) { - return _duplexify({ - writable: false, - readable: false - }) - } - if (isReadableStream(body)) { - return _duplexify({ - readable: Readable.fromWeb(body) - }) - } - if (isWritableStream(body)) { - return _duplexify({ - writable: Writable.fromWeb(body) - }) - } - if (typeof body === 'function') { - const { value, write, final, destroy } = fromAsyncGen(body) - if (isIterable(value)) { - return from(Duplexify, value, { - // TODO (ronag): highWaterMark? - objectMode: true, - write, - final, - destroy - }) - } - const then = value === null || value === undefined ? undefined : value.then - if (typeof then === 'function') { - let d - const promise = FunctionPrototypeCall( - then, - value, - (val) => { - if (val != null) { - throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) + if (attrs.length || attrsBlocks.length) { + this.buf.push('},'); + } else { + this.buf.push('}'); } - }, - (err) => { - destroyer(d, err) } - ) - return (d = new Duplexify({ - // TODO (ronag): highWaterMark? - objectMode: true, - readable: false, - write, - final(cb) { - final(async () => { - try { - await promise - process.nextTick(cb, null) - } catch (err) { - process.nextTick(cb, err) - } - }) - }, - destroy - })) - } - throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) - } - if (isBlob(body)) { - return duplexify(body.arrayBuffer()) - } - if (isIterable(body)) { - return from(Duplexify, body, { - // TODO (ronag): highWaterMark? - objectMode: true, - writable: false - }) - } - if ( - isReadableStream(body === null || body === undefined ? undefined : body.readable) && - isWritableStream(body === null || body === undefined ? undefined : body.writable) - ) { - return Duplexify.fromWeb(body) - } - if ( - typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || - typeof (body === null || body === undefined ? undefined : body.readable) === 'object' - ) { - const readable = - body !== null && body !== undefined && body.readable - ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) - ? body === null || body === undefined - ? undefined - : body.readable - : duplexify(body.readable) - : undefined - const writable = - body !== null && body !== undefined && body.writable - ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) - ? body === null || body === undefined - ? undefined - : body.writable - : duplexify(body.writable) - : undefined - return _duplexify({ - readable, - writable - }) - } - const then = body === null || body === undefined ? undefined : body.then - if (typeof then === 'function') { - let d - FunctionPrototypeCall( - then, - body, - (val) => { - if (val != null) { - d.push(val) + + if (attrsBlocks.length) { + if (attrs.length) { + var val = this.attrs(attrs); + attrsBlocks.unshift(val); + } + if (attrsBlocks.length > 1) { + this.buf.push( + 'attributes: ' + + this.runtime('merge') + + '([' + + attrsBlocks.join(',') + + '])' + ); + } else { + this.buf.push('attributes: ' + attrsBlocks[0]); + } + } else if (attrs.length) { + var val = this.attrs(attrs); + this.buf.push('attributes: ' + val); } - d.push(null) - }, - (err) => { - destroyer(d, err) + + if (args) { + this.buf.push('}, ' + args + ');'); + } else { + this.buf.push('});'); + } + } else { + this.buf.push(name + '(' + args + ');'); } - ) - return (d = new Duplexify({ - objectMode: true, - writable: false, - read() {} - })) - } - throw new ERR_INVALID_ARG_TYPE( - name, - [ - 'Blob', - 'ReadableStream', - 'WritableStream', - 'Stream', - 'Iterable', - 'AsyncIterable', - 'Function', - '{ readable, writable } pair', - 'Promise' - ], - body - ) -} -function fromAsyncGen(fn) { - let { promise, resolve } = createDeferredPromise() - const ac = new AbortController() - const signal = ac.signal - const value = fn( - (async function* () { - while (true) { - const _promise = promise - promise = null - const { chunk, done, cb } = await _promise - process.nextTick(cb) - if (done) return - if (signal.aborted) - throw new AbortError(undefined, { - cause: signal.reason - }) - ;({ promise, resolve } = createDeferredPromise()) - yield chunk + if (pp) this.buf.push('pug_indent.pop();'); + } else { + var mixin_start = this.buf.length; + args = args ? args.split(',') : []; + var rest; + if (args.length && /^\.\.\./.test(args[args.length - 1].trim())) { + rest = args + .pop() + .trim() + .replace(/^\.\.\./, ''); } - })(), - { - signal - } - ) - return { - value, - write(chunk, encoding, cb) { - const _resolve = resolve - resolve = null - _resolve({ - chunk, - done: false, - cb - }) - }, - final(cb) { - const _resolve = resolve - resolve = null - _resolve({ - done: true, - cb - }) - }, - destroy(err, cb) { - ac.abort() - cb(err) + // we need use pug_interp here for v8: https://code.google.com/p/v8/issues/detail?id=4165 + // once fixed, use this: this.buf.push(name + ' = function(' + args.join(',') + '){'); + this.buf.push(name + ' = pug_interp = function(' + args.join(',') + '){'); + this.buf.push( + 'var block = (this && this.block), attributes = (this && this.attributes) || {};' + ); + if (rest) { + this.buf.push('var ' + rest + ' = [];'); + this.buf.push( + 'for (pug_interp = ' + + args.length + + '; pug_interp < arguments.length; pug_interp++) {' + ); + this.buf.push(' ' + rest + '.push(arguments[pug_interp]);'); + this.buf.push('}'); + } + this.parentIndents++; + this.visit(block, mixin); + this.parentIndents--; + this.buf.push('};'); + var mixin_end = this.buf.length; + this.mixins[key].instances.push({start: mixin_start, end: mixin_end}); } - } -} -function _duplexify(pair) { - const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable - const w = pair.writable - let readable = !!isReadable(r) - let writable = !!isWritable(w) - let ondrain - let onfinish - let onreadable - let onclose - let d - function onfinished(err) { - const cb = onclose - onclose = null - if (cb) { - cb(err) - } else if (err) { - d.destroy(err) + }, + + /** + * Visit `tag` buffering tag markup, generating + * attributes, visiting the `tag`'s code and block. + * + * @param {Tag} tag + * @param {boolean} interpolated + * @api public + */ + + visitTag: function(tag, interpolated) { + this.indents++; + var name = tag.name, + pp = this.pp, + self = this; + + function bufferName() { + if (interpolated) self.bufferExpression(tag.expr); + else self.buffer(name); } - } - // TODO(ronag): Avoid double buffering. - // Implement Writable/Readable/Duplex traits. - // See, https://github.com/nodejs/node/pull/33515. - d = new Duplexify({ - // TODO (ronag): highWaterMark? - readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), - writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), - readable, - writable - }) - if (writable) { - eos(w, (err) => { - writable = false - if (err) { - destroyer(r, err) - } - onfinished(err) - }) - d._write = function (chunk, encoding, callback) { - if (w.write(chunk, encoding)) { - callback() - } else { - ondrain = callback + if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true) + this.escapePrettyMode = true; + + if (!this.hasCompiledTag) { + if (!this.hasCompiledDoctype && 'html' == name) { + this.visitDoctype(); } + this.hasCompiledTag = true; } - d._final = function (callback) { - w.end() - onfinish = callback - } - w.on('drain', function () { - if (ondrain) { - const cb = ondrain - ondrain = null - cb() - } - }) - w.on('finish', function () { - if (onfinish) { - const cb = onfinish - onfinish = null - cb() - } - }) - } - if (readable) { - eos(r, (err) => { - readable = false - if (err) { - destroyer(r, err) - } - onfinished(err) - }) - r.on('readable', function () { - if (onreadable) { - const cb = onreadable - onreadable = null - cb() + + // pretty print + if (pp && !tag.isInline) this.prettyIndent(0, true); + if (tag.selfClosing || (!this.xml && selfClosing[tag.name])) { + this.buffer('<'); + bufferName(); + this.visitAttributes( + tag.attrs, + this.attributeBlocks(tag.attributeBlocks) + ); + if (this.terse && !tag.selfClosing) { + this.buffer('>'); + } else { + this.buffer('/>'); } - }) - r.on('end', function () { - d.push(null) - }) - d._read = function () { - while (true) { - const buf = r.read() - if (buf === null) { - onreadable = d._read - return - } - if (!d.push(buf)) { - return - } + // if it is non-empty throw an error + if ( + tag.code || + (tag.block && + !(tag.block.type === 'Block' && tag.block.nodes.length === 0) && + tag.block.nodes.some(function(tag) { + return tag.type !== 'Text' || !/^\s*$/.test(tag.val); + })) + ) { + this.error( + name + + ' is a self closing element: <' + + name + + '/> but contains nested content.', + 'SELF_CLOSING_CONTENT', + tag + ); } - } - } - d._destroy = function (err, callback) { - if (!err && onclose !== null) { - err = new AbortError() - } - onreadable = null - ondrain = null - onfinish = null - if (onclose === null) { - callback(err) } else { - onclose = callback - destroyer(w, err) - destroyer(r, err) + // Optimize attributes buffering + this.buffer('<'); + bufferName(); + this.visitAttributes( + tag.attrs, + this.attributeBlocks(tag.attributeBlocks) + ); + this.buffer('>'); + if (tag.code) this.visitCode(tag.code); + this.visit(tag.block, tag); + + // pretty print + if ( + pp && + !tag.isInline && + WHITE_SPACE_SENSITIVE_TAGS[tag.name] !== true && + !tagCanInline(tag) + ) + this.prettyIndent(0, true); + + this.buffer(''); } - } - return d -} + if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true) + this.escapePrettyMode = false; -/***/ }), + this.indents--; + }, -/***/ 76080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Visit InterpolatedTag. + * + * @param {InterpolatedTag} tag + * @api public + */ -"use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). + visitInterpolatedTag: function(tag) { + return this.visitTag(tag, true); + }, + /** + * Visit `text` node. + * + * @param {Text} text + * @api public + */ + visitText: function(text) { + this.buffer(text.val); + }, -/* replacement start */ + /** + * Visit a `comment`, only buffering when the buffer flag is set. + * + * @param {Comment} comment + * @api public + */ -const process = __nccwpck_require__(45676) + visitComment: function(comment) { + if (!comment.buffer) return; + if (this.pp) this.prettyIndent(1, true); + this.buffer(''); + }, -/* replacement end */ + /** + * Visit a `YieldBlock`. + * + * This is necessary since we allow compiling a file with `yield`. + * + * @param {YieldBlock} block + * @api public + */ -const { AbortError, codes } = __nccwpck_require__(80529) -const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes -const { kEmptyObject, once } = __nccwpck_require__(46959) -const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = __nccwpck_require__(669) -const { Promise, PromisePrototypeThen, SymbolDispose } = __nccwpck_require__(89629) -const { - isClosed, - isReadable, - isReadableNodeStream, - isReadableStream, - isReadableFinished, - isReadableErrored, - isWritable, - isWritableNodeStream, - isWritableStream, - isWritableFinished, - isWritableErrored, - isNodeStream, - willEmitClose: _willEmitClose, - kIsClosedPromise -} = __nccwpck_require__(27981) -let addAbortListener -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function' -} -const nop = () => {} -function eos(stream, options, callback) { - var _options$readable, _options$writable - if (arguments.length === 2) { - callback = options - options = kEmptyObject - } else if (options == null) { - options = kEmptyObject - } else { - validateObject(options, 'options') - } - validateFunction(callback, 'callback') - validateAbortSignal(options.signal, 'options.signal') - callback = once(callback) - if (isReadableStream(stream) || isWritableStream(stream)) { - return eosWeb(stream, options, callback) - } - if (!isNodeStream(stream)) { - throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) - } - const readable = - (_options$readable = options.readable) !== null && _options$readable !== undefined - ? _options$readable - : isReadableNodeStream(stream) - const writable = - (_options$writable = options.writable) !== null && _options$writable !== undefined - ? _options$writable - : isWritableNodeStream(stream) - const wState = stream._writableState - const rState = stream._readableState - const onlegacyfinish = () => { - if (!stream.writable) { - onfinish() - } - } + visitYieldBlock: function(block) {}, - // TODO (ronag): Improve soft detection to include core modules and - // common ecosystem modules that do properly emit 'close' but fail - // this generic check. - let willEmitClose = - _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable - let writableFinished = isWritableFinished(stream, false) - const onfinish = () => { - writableFinished = true - // Stream should not be destroyed here. If it is that - // means that user space is doing something differently and - // we cannot trust willEmitClose. - if (stream.destroyed) { - willEmitClose = false - } - if (willEmitClose && (!stream.readable || readable)) { - return - } - if (!readable || readableFinished) { - callback.call(stream) - } - } - let readableFinished = isReadableFinished(stream, false) - const onend = () => { - readableFinished = true - // Stream should not be destroyed here. If it is that - // means that user space is doing something differently and - // we cannot trust willEmitClose. - if (stream.destroyed) { - willEmitClose = false - } - if (willEmitClose && (!stream.writable || writable)) { - return - } - if (!writable || writableFinished) { - callback.call(stream) - } - } - const onerror = (err) => { - callback.call(stream, err) - } - let closed = isClosed(stream) - const onclose = () => { - closed = true - const errored = isWritableErrored(stream) || isReadableErrored(stream) - if (errored && typeof errored !== 'boolean') { - return callback.call(stream, errored) - } - if (readable && !readableFinished && isReadableNodeStream(stream, true)) { - if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) - } - if (writable && !writableFinished) { - if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) - } - callback.call(stream) - } - const onclosed = () => { - closed = true - const errored = isWritableErrored(stream) || isReadableErrored(stream) - if (errored && typeof errored !== 'boolean') { - return callback.call(stream, errored) - } - callback.call(stream) - } - const onrequest = () => { - stream.req.on('finish', onfinish) - } - if (isRequest(stream)) { - stream.on('complete', onfinish) - if (!willEmitClose) { - stream.on('abort', onclose) - } - if (stream.req) { - onrequest() - } else { - stream.on('request', onrequest) - } - } else if (writable && !wState) { - // legacy streams - stream.on('end', onlegacyfinish) - stream.on('close', onlegacyfinish) - } + /** + * Visit a `BlockComment`. + * + * @param {Comment} comment + * @api public + */ - // Not all streams will emit 'close' after 'aborted'. - if (!willEmitClose && typeof stream.aborted === 'boolean') { - stream.on('aborted', onclose) - } - stream.on('end', onend) - stream.on('finish', onfinish) - if (options.error !== false) { - stream.on('error', onerror) - } - stream.on('close', onclose) - if (closed) { - process.nextTick(onclose) - } else if ( - (wState !== null && wState !== undefined && wState.errorEmitted) || - (rState !== null && rState !== undefined && rState.errorEmitted) - ) { - if (!willEmitClose) { - process.nextTick(onclosed) - } - } else if ( - !readable && - (!willEmitClose || isReadable(stream)) && - (writableFinished || isWritable(stream) === false) - ) { - process.nextTick(onclosed) - } else if ( - !writable && - (!willEmitClose || isWritable(stream)) && - (readableFinished || isReadable(stream) === false) - ) { - process.nextTick(onclosed) - } else if (rState && stream.req && stream.aborted) { - process.nextTick(onclosed) - } - const cleanup = () => { - callback = nop - stream.removeListener('aborted', onclose) - stream.removeListener('complete', onfinish) - stream.removeListener('abort', onclose) - stream.removeListener('request', onrequest) - if (stream.req) stream.req.removeListener('finish', onfinish) - stream.removeListener('end', onlegacyfinish) - stream.removeListener('close', onlegacyfinish) - stream.removeListener('finish', onfinish) - stream.removeListener('end', onend) - stream.removeListener('error', onerror) - stream.removeListener('close', onclose) - } - if (options.signal && !closed) { - const abort = () => { - // Keep it because cleanup removes it. - const endCallback = callback - cleanup() - endCallback.call( - stream, - new AbortError(undefined, { - cause: options.signal.reason - }) - ) - } - if (options.signal.aborted) { - process.nextTick(abort) - } else { - addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) - const disposable = addAbortListener(options.signal, abort) - const originalCallback = callback - callback = once((...args) => { - disposable[SymbolDispose]() - originalCallback.apply(stream, args) - }) - } - } - return cleanup -} -function eosWeb(stream, options, callback) { - let isAborted = false - let abort = nop - if (options.signal) { - abort = () => { - isAborted = true - callback.call( - stream, - new AbortError(undefined, { - cause: options.signal.reason - }) - ) - } - if (options.signal.aborted) { - process.nextTick(abort) + visitBlockComment: function(comment) { + if (!comment.buffer) return; + if (this.pp) this.prettyIndent(1, true); + this.buffer(''); + }, + + /** + * Visit `code`, respecting buffer / escape flags. + * If the code is followed by a block, wrap it in + * a self-calling function. + * + * @param {Code} code + * @api public + */ + + visitCode: function(code) { + // Wrap code blocks with {}. + // we only wrap unbuffered code blocks ATM + // since they are usually flow control + + // Buffer code + if (code.buffer) { + var val = code.val.trim(); + val = 'null == (pug_interp = ' + val + ') ? "" : pug_interp'; + if (code.mustEscape !== false) + val = this.runtime('escape') + '(' + val + ')'; + this.bufferExpression(val); } else { - addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) - const disposable = addAbortListener(options.signal, abort) - const originalCallback = callback - callback = once((...args) => { - disposable[SymbolDispose]() - originalCallback.apply(stream, args) - }) + this.buf.push(code.val); } - } - const resolverFn = (...args) => { - if (!isAborted) { - process.nextTick(() => callback.apply(stream, args)) + + // Block support + if (code.block) { + if (!code.buffer) this.buf.push('{'); + this.visit(code.block, code); + if (!code.buffer) this.buf.push('}'); } - } - PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) - return nop -} -function finished(stream, opts) { - var _opts - let autoCleanup = false - if (opts === null) { - opts = kEmptyObject - } - if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { - validateBoolean(opts.cleanup, 'cleanup') - autoCleanup = opts.cleanup - } - return new Promise((resolve, reject) => { - const cleanup = eos(stream, opts, (err) => { - if (autoCleanup) { - cleanup() - } - if (err) { - reject(err) + }, + + /** + * Visit `Conditional`. + * + * @param {Conditional} cond + * @api public + */ + + visitConditional: function(cond) { + var test = cond.test; + this.buf.push('if (' + test + ') {'); + this.visit(cond.consequent, cond); + this.buf.push('}'); + if (cond.alternate) { + if (cond.alternate.type === 'Conditional') { + this.buf.push('else'); + this.visitConditional(cond.alternate); } else { - resolve() + this.buf.push('else {'); + this.visit(cond.alternate, cond); + this.buf.push('}'); } - }) - }) -} -module.exports = eos -module.exports.finished = finished + } + }, + + /** + * Visit `While`. + * + * @param {While} loop + * @api public + */ + + visitWhile: function(loop) { + var test = loop.test; + this.buf.push('while (' + test + ') {'); + this.visit(loop.block, loop); + this.buf.push('}'); + }, + + /** + * Visit `each` block. + * + * @param {Each} each + * @api public + */ + + visitEach: function(each) { + var indexVarName = each.key || 'pug_index' + this.eachCount; + this.eachCount++; + + this.buf.push( + '' + + '// iterate ' + + each.obj + + '\n' + + ';(function(){\n' + + ' var $$obj = ' + + each.obj + + ';\n' + + " if ('number' == typeof $$obj.length) {" + ); + if (each.alternate) { + this.buf.push(' if ($$obj.length) {'); + } -/***/ }), + this.buf.push( + '' + + ' for (var ' + + indexVarName + + ' = 0, $$l = $$obj.length; ' + + indexVarName + + ' < $$l; ' + + indexVarName + + '++) {\n' + + ' var ' + + each.val + + ' = $$obj[' + + indexVarName + + '];' + ); -/***/ 39082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.visit(each.block, each); -"use strict"; + this.buf.push(' }'); + if (each.alternate) { + this.buf.push(' } else {'); + this.visit(each.alternate, each); + this.buf.push(' }'); + } -/* replacement start */ + this.buf.push( + '' + + ' } else {\n' + + ' var $$l = 0;\n' + + ' for (var ' + + indexVarName + + ' in $$obj) {\n' + + ' $$l++;\n' + + ' var ' + + each.val + + ' = $$obj[' + + indexVarName + + '];' + ); -const process = __nccwpck_require__(45676) + this.visit(each.block, each); -/* replacement end */ + this.buf.push(' }'); + if (each.alternate) { + this.buf.push(' if ($$l === 0) {'); + this.visit(each.alternate, each); + this.buf.push(' }'); + } + this.buf.push(' }\n}).call(this);\n'); + }, -const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = __nccwpck_require__(89629) -const { Buffer } = __nccwpck_require__(14300) -const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = (__nccwpck_require__(80529).codes) -function from(Readable, iterable, opts) { - let iterator - if (typeof iterable === 'string' || iterable instanceof Buffer) { - return new Readable({ - objectMode: true, - ...opts, - read() { - this.push(iterable) - this.push(null) - } - }) - } - let isAsync - if (iterable && iterable[SymbolAsyncIterator]) { - isAsync = true - iterator = iterable[SymbolAsyncIterator]() - } else if (iterable && iterable[SymbolIterator]) { - isAsync = false - iterator = iterable[SymbolIterator]() - } else { - throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) - } - const readable = new Readable({ - objectMode: true, - highWaterMark: 1, - // TODO(ronag): What options should be allowed? - ...opts - }) + visitEachOf: function(each) { + this.buf.push( + '' + + '// iterate ' + + each.obj + + '\n' + + 'for (const ' + + each.val + + ' of ' + + each.obj + + ') {\n' + ); - // Flag to protect against _read - // being called before last iteration completion. - let reading = false - readable._read = function () { - if (!reading) { - reading = true - next() - } - } - readable._destroy = function (error, cb) { - PromisePrototypeThen( - close(error), - () => process.nextTick(cb, error), - // nextTick is here in case cb throws - (e) => process.nextTick(cb, e || error) - ) - } - async function close(error) { - const hadError = error !== undefined && error !== null - const hasThrow = typeof iterator.throw === 'function' - if (hadError && hasThrow) { - const { value, done } = await iterator.throw(error) - await value - if (done) { - return + this.visit(each.block, each); + + this.buf.push('}\n'); + }, + + /** + * Visit `attrs`. + * + * @param {Array} attrs + * @api public + */ + + visitAttributes: function(attrs, attributeBlocks) { + if (attributeBlocks.length) { + if (attrs.length) { + var val = this.attrs(attrs); + attributeBlocks.unshift(val); } - } - if (typeof iterator.return === 'function') { - const { value } = await iterator.return() - await value - } - } - async function next() { - for (;;) { - try { - const { value, done } = isAsync ? await iterator.next() : iterator.next() - if (done) { - readable.push(null) - } else { - const res = value && typeof value.then === 'function' ? await value : value - if (res === null) { - reading = false - throw new ERR_STREAM_NULL_VALUES() - } else if (readable.push(res)) { - continue - } else { - reading = false - } - } - } catch (err) { - readable.destroy(err) + if (attributeBlocks.length > 1) { + this.bufferExpression( + this.runtime('attrs') + + '(' + + this.runtime('merge') + + '([' + + attributeBlocks.join(',') + + ']), ' + + stringify(this.terse) + + ')' + ); + } else { + this.bufferExpression( + this.runtime('attrs') + + '(' + + attributeBlocks[0] + + ', ' + + stringify(this.terse) + + ')' + ); } - break + } else if (attrs.length) { + this.attrs(attrs, true); } - } - return readable -} -module.exports = from + }, + /** + * Compile attributes. + */ -/***/ }), + attrs: function(attrs, buffer) { + var res = compileAttrs(attrs, { + terse: this.terse, + format: buffer ? 'html' : 'object', + runtime: this.runtime.bind(this), + }); + if (buffer) { + this.bufferExpression(res); + } + return res; + }, -/***/ 49792: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Compile attribute blocks. + */ -"use strict"; + attributeBlocks: function(attributeBlocks) { + return ( + attributeBlocks && + attributeBlocks.slice().map(function(attrBlock) { + return attrBlock.val; + }) + ); + }, +}; +function tagCanInline(tag) { + function isInline(node) { + // Recurse if the node is a block + if (node.type === 'Block') return node.nodes.every(isInline); + // When there is a YieldBlock here, it is an indication that the file is + // expected to be included but is not. If this is the case, the block + // must be empty. + if (node.type === 'YieldBlock') return true; + return (node.type === 'Text' && !/\n/.test(node.val)) || node.isInline; + } -const { ArrayIsArray, ObjectSetPrototypeOf } = __nccwpck_require__(89629) -const { EventEmitter: EE } = __nccwpck_require__(82361) -function Stream(opts) { - EE.call(this, opts) + return tag.block.nodes.every(isInline); } -ObjectSetPrototypeOf(Stream.prototype, EE.prototype) -ObjectSetPrototypeOf(Stream, EE) -Stream.prototype.pipe = function (dest, options) { - const source = this - function ondata(chunk) { - if (dest.writable && dest.write(chunk) === false && source.pause) { - source.pause() - } - } - source.on('data', ondata) - function ondrain() { - if (source.readable && source.resume) { - source.resume() - } - } - dest.on('drain', ondrain) - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend) - source.on('close', onclose) - } - let didOnEnd = false - function onend() { - if (didOnEnd) return - didOnEnd = true - dest.end() - } - function onclose() { - if (didOnEnd) return - didOnEnd = true - if (typeof dest.destroy === 'function') dest.destroy() - } - // Don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup() - if (EE.listenerCount(this, 'error') === 0) { - this.emit('error', er) - } - } - prependListener(source, 'error', onerror) - prependListener(dest, 'error', onerror) +/***/ }), - // Remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata) - dest.removeListener('drain', ondrain) - source.removeListener('end', onend) - source.removeListener('close', onclose) - source.removeListener('error', onerror) - dest.removeListener('error', onerror) - source.removeListener('end', cleanup) - source.removeListener('close', cleanup) - dest.removeListener('close', cleanup) - } - source.on('end', cleanup) - source.on('close', cleanup) - dest.on('close', cleanup) - dest.emit('pipe', source) +/***/ 66198: +/***/ ((module, exports) => { - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest -} -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) +"use strict"; - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn) - else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn) - else emitter._events[event] = [fn, emitter._events[event]] -} -module.exports = { - Stream, - prependListener +Object.defineProperty(exports, "__esModule", ({ value: true })); +function makeError(code, message, options) { + var line = options.line; + var column = options.column; + var filename = options.filename; + var src = options.src; + var fullMessage; + var location = line + (column ? ':' + column : ''); + if (src && line >= 1 && line <= src.split('\n').length) { + var lines = src.split('\n'); + var start_1 = Math.max(line - 3, 0); + var end = Math.min(lines.length, line + 3); + // Error context + var context = lines + .slice(start_1, end) + .map(function (text, i) { + var curr = i + start_1 + 1; + var preamble = (curr == line ? ' > ' : ' ') + curr + '| '; + var out = preamble + text; + if (curr === line && column > 0) { + out += '\n'; + out += Array(preamble.length + column).join('-') + '^'; + } + return out; + }) + .join('\n'); + fullMessage = + (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message; + } + else { + fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message; + } + var err = new Error(fullMessage); + err.code = 'PUG:' + code; + err.msg = message; + err.line = line; + err.column = column; + err.filename = filename; + err.src = src; + err.toJSON = function () { + return { + code: this.code, + msg: this.msg, + line: this.line, + column: this.column, + filename: this.filename, + }; + }; + return err; } - +exports["default"] = makeError; +// Make this easier to use from CommonJS +module.exports = makeError; +module.exports["default"] = makeError; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 63193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 11449: +/***/ ((module) => { "use strict"; -const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) -const { - codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, - AbortError -} = __nccwpck_require__(80529) -const { validateAbortSignal, validateInteger, validateObject } = __nccwpck_require__(669) -const kWeakHandler = (__nccwpck_require__(89629).Symbol)('kWeak') -const kResistStopPropagation = (__nccwpck_require__(89629).Symbol)('kResistStopPropagation') -const { finished } = __nccwpck_require__(76080) -const staticCompose = __nccwpck_require__(63129) -const { addAbortSignalNoValidate } = __nccwpck_require__(80289) -const { isWritable, isNodeStream } = __nccwpck_require__(27981) -const { deprecate } = __nccwpck_require__(46959) -const { - ArrayPrototypePush, - Boolean, - MathFloor, - Number, - NumberIsNaN, - Promise, - PromiseReject, - PromiseResolve, - PromisePrototypeThen, - Symbol -} = __nccwpck_require__(89629) -const kEmpty = Symbol('kEmpty') -const kEof = Symbol('kEof') -function compose(stream, options) { - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - if (isNodeStream(stream) && !isWritable(stream)) { - throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') - } - const composedStream = staticCompose(this, stream) - if (options !== null && options !== undefined && options.signal) { - // Not validating as we already validated before - addAbortSignalNoValidate(options.signal, composedStream) - } - return composedStream -} -function map(fn, options) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) - } - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - let concurrency = 1 - if ((options === null || options === undefined ? undefined : options.concurrency) != null) { - concurrency = MathFloor(options.concurrency) - } - let highWaterMark = concurrency - 1 - if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { - highWaterMark = MathFloor(options.highWaterMark) - } - validateInteger(concurrency, 'options.concurrency', 1) - validateInteger(highWaterMark, 'options.highWaterMark', 0) - highWaterMark += concurrency - return async function* map() { - const signal = (__nccwpck_require__(46959).AbortSignalAny)( - [options === null || options === undefined ? undefined : options.signal].filter(Boolean) - ) - const stream = this - const queue = [] - const signalOpt = { - signal - } - let next - let resume - let done = false - let cnt = 0 - function onCatch() { - done = true - afterItemProcessed() - } - function afterItemProcessed() { - cnt -= 1 - maybeResume() - } - function maybeResume() { - if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { - resume() - resume = null - } - } - async function pump() { - try { - for await (let val of stream) { - if (done) { - return - } - if (signal.aborted) { - throw new AbortError() - } - try { - val = fn(val, signalOpt) - if (val === kEmpty) { - continue - } - val = PromiseResolve(val) - } catch (err) { - val = PromiseReject(err) - } - cnt += 1 - PromisePrototypeThen(val, afterItemProcessed, onCatch) - queue.push(val) - if (next) { - next() - next = null - } - if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { - await new Promise((resolve) => { - resume = resolve - }) - } - } - queue.push(kEof) - } catch (err) { - const val = PromiseReject(err) - PromisePrototypeThen(val, afterItemProcessed, onCatch) - queue.push(val) - } finally { - done = true - if (next) { - next() - next = null - } - } - } - pump() - try { - while (true) { - while (queue.length > 0) { - const val = await queue[0] - if (val === kEof) { - return - } - if (signal.aborted) { - throw new AbortError() - } - if (val !== kEmpty) { - yield val - } - queue.shift() - maybeResume() +module.exports = makeError; +function makeError(code, message, options) { + var line = options.line; + var column = options.column; + var filename = options.filename; + var src = options.src; + var fullMessage; + var location = line + (column ? ':' + column : ''); + if (src && line >= 1 && line <= src.split('\n').length) { + var lines = src.split('\n'); + var start = Math.max(line - 3, 0); + var end = Math.min(lines.length, line + 3); + // Error context + var context = lines + .slice(start, end) + .map(function(text, i) { + var curr = i + start + 1; + var preamble = (curr == line ? ' > ' : ' ') + curr + '| '; + var out = preamble + text; + if (curr === line && column > 0) { + out += '\n'; + out += Array(preamble.length + column).join('-') + '^'; } - await new Promise((resolve) => { - next = resolve - }) - } - } finally { - done = true - if (resume) { - resume() - resume = null - } - } - }.call(this) -} -function asIndexedPairs(options = undefined) { - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - return async function* asIndexedPairs() { - let index = 0 - for await (const val of this) { - var _options$signal - if ( - options !== null && - options !== undefined && - (_options$signal = options.signal) !== null && - _options$signal !== undefined && - _options$signal.aborted - ) { - throw new AbortError({ - cause: options.signal.reason - }) - } - yield [index++, val] - } - }.call(this) -} -async function some(fn, options = undefined) { - for await (const unused of filter.call(this, fn, options)) { - return true - } - return false -} -async function every(fn, options = undefined) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) - } - // https://en.wikipedia.org/wiki/De_Morgan%27s_laws - return !(await some.call( - this, - async (...args) => { - return !(await fn(...args)) - }, - options - )) -} -async function find(fn, options) { - for await (const result of filter.call(this, fn, options)) { - return result - } - return undefined -} -async function forEach(fn, options) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) - } - async function forEachFn(value, options) { - await fn(value, options) - return kEmpty - } - // eslint-disable-next-line no-unused-vars - for await (const unused of map.call(this, forEachFn, options)); -} -function filter(fn, options) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) - } - async function filterFn(value, options) { - if (await fn(value, options)) { - return value - } - return kEmpty - } - return map.call(this, filterFn, options) -} - -// Specific to provide better error to reduce since the argument is only -// missing if the stream has no items in it - but the code is still appropriate -class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { - constructor() { - super('reduce') - this.message = 'Reduce of an empty stream requires an initial value' - } -} -async function reduce(reducer, initialValue, options) { - var _options$signal2 - if (typeof reducer !== 'function') { - throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) - } - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - let hasInitialValue = arguments.length > 1 - if ( - options !== null && - options !== undefined && - (_options$signal2 = options.signal) !== null && - _options$signal2 !== undefined && - _options$signal2.aborted - ) { - const err = new AbortError(undefined, { - cause: options.signal.reason - }) - this.once('error', () => {}) // The error is already propagated - await finished(this.destroy(err)) - throw err - } - const ac = new AbortController() - const signal = ac.signal - if (options !== null && options !== undefined && options.signal) { - const opts = { - once: true, - [kWeakHandler]: this, - [kResistStopPropagation]: true - } - options.signal.addEventListener('abort', () => ac.abort(), opts) - } - let gotAnyItemFromStream = false - try { - for await (const value of this) { - var _options$signal3 - gotAnyItemFromStream = true - if ( - options !== null && - options !== undefined && - (_options$signal3 = options.signal) !== null && - _options$signal3 !== undefined && - _options$signal3.aborted - ) { - throw new AbortError() - } - if (!hasInitialValue) { - initialValue = value - hasInitialValue = true - } else { - initialValue = await reducer(initialValue, value, { - signal - }) - } - } - if (!gotAnyItemFromStream && !hasInitialValue) { - throw new ReduceAwareErrMissingArgs() - } - } finally { - ac.abort() - } - return initialValue -} -async function toArray(options) { - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - const result = [] - for await (const val of this) { - var _options$signal4 - if ( - options !== null && - options !== undefined && - (_options$signal4 = options.signal) !== null && - _options$signal4 !== undefined && - _options$signal4.aborted - ) { - throw new AbortError(undefined, { - cause: options.signal.reason + return out; }) - } - ArrayPrototypePush(result, val) - } - return result -} -function flatMap(fn, options) { - const values = map.call(this, fn, options) - return async function* flatMap() { - for await (const val of values) { - yield* val - } - }.call(this) -} -function toIntegerOrInfinity(number) { - // We coerce here to align with the spec - // https://github.com/tc39/proposal-iterator-helpers/issues/169 - number = Number(number) - if (NumberIsNaN(number)) { - return 0 - } - if (number < 0) { - throw new ERR_OUT_OF_RANGE('number', '>= 0', number) - } - return number -} -function drop(number, options = undefined) { - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') - } - number = toIntegerOrInfinity(number) - return async function* drop() { - var _options$signal5 - if ( - options !== null && - options !== undefined && - (_options$signal5 = options.signal) !== null && - _options$signal5 !== undefined && - _options$signal5.aborted - ) { - throw new AbortError() - } - for await (const val of this) { - var _options$signal6 - if ( - options !== null && - options !== undefined && - (_options$signal6 = options.signal) !== null && - _options$signal6 !== undefined && - _options$signal6.aborted - ) { - throw new AbortError() - } - if (number-- <= 0) { - yield val - } - } - }.call(this) -} -function take(number, options = undefined) { - if (options != null) { - validateObject(options, 'options') - } - if ((options === null || options === undefined ? undefined : options.signal) != null) { - validateAbortSignal(options.signal, 'options.signal') + .join('\n'); + fullMessage = + (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message; + } else { + fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message; } - number = toIntegerOrInfinity(number) - return async function* take() { - var _options$signal7 - if ( - options !== null && - options !== undefined && - (_options$signal7 = options.signal) !== null && - _options$signal7 !== undefined && - _options$signal7.aborted - ) { - throw new AbortError() - } - for await (const val of this) { - var _options$signal8 - if ( - options !== null && - options !== undefined && - (_options$signal8 = options.signal) !== null && - _options$signal8 !== undefined && - _options$signal8.aborted - ) { - throw new AbortError() - } - if (number-- > 0) { - yield val - } - - // Don't get another item from iterator in case we reached the end - if (number <= 0) { - return - } - } - }.call(this) -} -module.exports.streamReturningOperators = { - asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), - drop, - filter, - flatMap, - map, - take, - compose -} -module.exports.promiseReturningOperators = { - every, - forEach, - reduce, - toArray, - some, - find + var err = new Error(fullMessage); + err.code = 'PUG:' + code; + err.msg = message; + err.line = line; + err.column = column; + err.filename = filename; + err.src = src; + err.toJSON = function() { + return { + code: this.code, + msg: this.msg, + line: this.line, + column: this.column, + filename: this.filename, + }; + }; + return err; } /***/ }), -/***/ 72839: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 69309: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -const { ObjectSetPrototypeOf } = __nccwpck_require__(89629) -module.exports = PassThrough -const Transform = __nccwpck_require__(86941) -ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype) -ObjectSetPrototypeOf(PassThrough, Transform) -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options) - Transform.call(this, options) -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk) -} +exports.runFilter = __nccwpck_require__(9498); +exports.handleFilters = __nccwpck_require__(77823); /***/ }), -/***/ 76989: +/***/ 77823: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* replacement start */ +"use strict"; -const process = __nccwpck_require__(45676) -/* replacement end */ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). +var dirname = (__nccwpck_require__(71017).dirname); +var constantinople = __nccwpck_require__(40953); +var walk = __nccwpck_require__(60283); +var error = __nccwpck_require__(11449); +var runFilter = __nccwpck_require__(9498); -;('use strict') -const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = __nccwpck_require__(89629) -const eos = __nccwpck_require__(76080) -const { once } = __nccwpck_require__(46959) -const destroyImpl = __nccwpck_require__(97049) -const Duplex = __nccwpck_require__(72613) -const { - aggregateTwoErrors, - codes: { - ERR_INVALID_ARG_TYPE, - ERR_INVALID_RETURN_VALUE, - ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED, - ERR_STREAM_PREMATURE_CLOSE - }, - AbortError -} = __nccwpck_require__(80529) -const { validateFunction, validateAbortSignal } = __nccwpck_require__(669) -const { - isIterable, - isReadable, - isReadableNodeStream, - isNodeStream, - isTransformStream, - isWebStream, - isReadableStream, - isReadableFinished -} = __nccwpck_require__(27981) -const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) -let PassThrough -let Readable -let addAbortListener -function destroyer(stream, reading, writing) { - let finished = false - stream.on('close', () => { - finished = true - }) - const cleanup = eos( - stream, - { - readable: reading, - writable: writing - }, - (err) => { - finished = !err - } - ) - return { - destroy: (err) => { - if (finished) return - finished = true - destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')) - }, - cleanup - } -} -function popCallback(streams) { - // Streams should never be an empty array. It should always contain at least - // a single stream. Therefore optimize for the average case instead of - // checking for length === 0 as well. - validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]') - return streams.pop() -} -function makeAsyncIterable(val) { - if (isIterable(val)) { - return val - } else if (isReadableNodeStream(val)) { - // Legacy streams are not Iterable. - return fromReadable(val) - } - throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val) -} -async function* fromReadable(val) { - if (!Readable) { - Readable = __nccwpck_require__(57920) - } - yield* Readable.prototype[SymbolAsyncIterator].call(val) -} -async function pumpToNode(iterable, writable, finish, { end }) { - let error - let onresolve = null - const resume = (err) => { - if (err) { - error = err - } - if (onresolve) { - const callback = onresolve - onresolve = null - callback() - } - } - const wait = () => - new Promise((resolve, reject) => { - if (error) { - reject(error) - } else { - onresolve = () => { - if (error) { - reject(error) +module.exports = handleFilters; +function handleFilters(ast, filters, options, filterAliases) { + options = options || {}; + walk( + ast, + function(node) { + var dir = node.filename ? dirname(node.filename) : null; + if (node.type === 'Filter') { + handleNestedFilters(node, filters, options, filterAliases); + var text = getBodyAsText(node); + var attrs = getAttributes(node, options); + attrs.filename = node.filename; + node.type = 'Text'; + node.val = filterWithFallback(node, text, attrs); + } else if (node.type === 'RawInclude' && node.filters.length) { + var firstFilter = node.filters.pop(); + var attrs = getAttributes(firstFilter, options); + var filename = (attrs.filename = node.file.fullPath); + node.type = 'Text'; + node.val = filterFileWithFallback( + firstFilter, + filename, + node.file, + attrs + ); + node.filters + .slice() + .reverse() + .forEach(function(filter) { + var attrs = getAttributes(filter, options); + attrs.filename = filename; + node.val = filterWithFallback(filter, node.val, attrs); + }); + node.filters = undefined; + node.file = undefined; + } + + function filterWithFallback(filter, text, attrs, funcName) { + try { + var filterName = getFilterName(filter); + if (filters && filters[filterName]) { + return filters[filterName](text, attrs); } else { - resolve() + return runFilter(filterName, text, attrs, dir, funcName); + } + } catch (ex) { + if (ex.code === 'UNKNOWN_FILTER') { + throw error(ex.code, ex.message, filter); } + throw ex; + } + } + + function filterFileWithFallback(filter, filename, file, attrs) { + var filterName = getFilterName(filter); + if (filters && filters[filterName]) { + if (filters[filterName].renderBuffer) { + return filters[filterName].renderBuffer(file.raw, attrs); + } else { + return filters[filterName](file.str, attrs); + } + } else { + return filterWithFallback(filter, filename, attrs, 'renderFile'); } } - }) - writable.on('drain', resume) - const cleanup = eos( - writable, - { - readable: false }, - resume - ) - try { - if (writable.writableNeedDrain) { - await wait() - } - for await (const chunk of iterable) { - if (!writable.write(chunk)) { - await wait() + {includeDependencies: true} + ); + function getFilterName(filter) { + var filterName = filter.name; + if (filterAliases && filterAliases[filterName]) { + filterName = filterAliases[filterName]; + if (filterAliases[filterName]) { + throw error( + 'FILTER_ALISE_CHAIN', + 'The filter "' + + filter.name + + '" is an alias for "' + + filterName + + '", which is an alias for "' + + filterAliases[filterName] + + '". Pug does not support chains of filter aliases.', + filter + ); } } - if (end) { - writable.end() - await wait() - } - finish() - } catch (err) { - finish(error !== err ? aggregateTwoErrors(error, err) : err) - } finally { - cleanup() - writable.off('drain', resume) + return filterName; } + return ast; } -async function pumpToWeb(readable, writable, finish, { end }) { - if (isTransformStream(writable)) { - writable = writable.writable - } - // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure - const writer = writable.getWriter() - try { - for await (const chunk of readable) { - await writer.ready - writer.write(chunk).catch(() => {}) - } - await writer.ready - if (end) { - await writer.close() - } - finish() - } catch (err) { - try { - await writer.abort(err) - finish(err) - } catch (err) { - finish(err) - } + +function handleNestedFilters(node, filters, options, filterAliases) { + if (node.block.nodes[0] && node.block.nodes[0].type === 'Filter') { + node.block.nodes[0] = handleFilters( + node.block, + filters, + options, + filterAliases + ).nodes[0]; } } -function pipeline(...streams) { - return pipelineImpl(streams, once(popCallback(streams))) + +function getBodyAsText(node) { + return node.block.nodes + .map(function(node) { + return node.val; + }) + .join(''); } -function pipelineImpl(streams, callback, opts) { - if (streams.length === 1 && ArrayIsArray(streams[0])) { - streams = streams[0] - } - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams') - } - const ac = new AbortController() - const signal = ac.signal - const outerSignal = opts === null || opts === undefined ? undefined : opts.signal - // Need to cleanup event listeners if last stream is readable - // https://github.com/nodejs/node/issues/35452 - const lastStreamCleanup = [] - validateAbortSignal(outerSignal, 'options.signal') - function abort() { - finishImpl(new AbortError()) - } - addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) - let disposable - if (outerSignal) { - disposable = addAbortListener(outerSignal, abort) - } - let error - let value - const destroys = [] - let finishCount = 0 - function finish(err) { - finishImpl(err, --finishCount === 0) - } - function finishImpl(err, final) { - var _disposable - if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { - error = err +function getAttributes(node, options) { + var attrs = {}; + node.attrs.forEach(function(attr) { + try { + attrs[attr.name] = + attr.val === true ? true : constantinople.toConstant(attr.val); + } catch (ex) { + if (/not constant/.test(ex.message)) { + throw error( + 'FILTER_OPTION_NOT_CONSTANT', + ex.message + + ' All filters are rendered compile-time so filter options must be constants.', + node + ); + } + throw ex; } - if (!error && !final) { - return + }); + var opts = options[node.name] || {}; + Object.keys(opts).forEach(function(opt) { + if (!attrs.hasOwnProperty(opt)) { + attrs[opt] = opts[opt]; } - while (destroys.length) { - destroys.shift()(error) + }); + return attrs; +} + + +/***/ }), + +/***/ 9498: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var jstransformer = __nccwpck_require__(77369); +var resolve = __nccwpck_require__(81679); + +module.exports = filter; + +function getMinifyTransformerName(outputFormat) { + switch (outputFormat) { + case 'js': + return 'uglify-js'; + case 'css': + return 'clean-css'; + } +} + +function filter(name, str, options, currentDirectory, funcName) { + funcName = funcName || 'render'; + var trPath; + try { + try { + trPath = resolve.sync('jstransformer-' + name, { + basedir: currentDirectory || process.cwd(), + }); + } catch (ex) { + trPath = require.resolve('jstransformer-' + name); } - ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]() - ac.abort() - if (final) { - if (!error) { - lastStreamCleanup.forEach((fn) => fn()) + } catch (ex) { + var err = new Error('unknown filter ":' + name + '"'); + err.code = 'UNKNOWN_FILTER'; + throw err; + } + var tr = jstransformer(require(trPath)); + // TODO: we may want to add a way for people to separately specify "locals" + var result = tr[funcName](str, options, options).body; + if (options && options.minify) { + var minifyTranformer = getMinifyTransformerName(tr.outputFormat); + if (minifyTranformer) { + try { + result = filter(minifyTranformer, result, null, currentDirectory); + } catch (ex) { + // better to fail to minify than output nothing } - process.nextTick(callback, error, value) } } - let ret - for (let i = 0; i < streams.length; i++) { - const stream = streams[i] - const reading = i < streams.length - 1 - const writing = i > 0 - const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false - const isLastStream = i === streams.length - 1 - if (isNodeStream(stream)) { - if (end) { - const { destroy, cleanup } = destroyer(stream, reading, writing) - destroys.push(destroy) - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(cleanup) - } - } + return result; +} - // Catch stream errors that occur after pipe/pump has completed. - function onError(err) { - if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - finish(err) - } - } - stream.on('error', onError) - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(() => { - stream.removeListener('error', onError) - }) - } - } - if (i === 0) { - if (typeof stream === 'function') { - ret = stream({ - signal - }) - if (!isIterable(ret)) { - throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) - } - } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { - ret = stream - } else { - ret = Duplex.from(stream) - } - } else if (typeof stream === 'function') { - if (isTransformStream(ret)) { - var _ret - ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable) - } else { - ret = makeAsyncIterable(ret) - } - ret = stream(ret, { - signal - }) - if (reading) { - if (!isIterable(ret, true)) { - throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) - } - } else { - var _ret2 - if (!PassThrough) { - PassThrough = __nccwpck_require__(72839) - } - // If the last argument to pipeline is not a stream - // we must create a proxy stream so that pipeline(...) - // always returns a stream which can be further - // composed through `.pipe(stream)`. +/***/ }), - const pt = new PassThrough({ - objectMode: true - }) +/***/ 53230: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Handle Promises/A+ spec, `then` could be a getter that throws on - // second use. - const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then - if (typeof then === 'function') { - finishCount++ - then.call( - ret, - (val) => { - value = val - if (val != null) { - pt.write(val) - } - if (end) { - pt.end() - } - process.nextTick(finish) - }, - (err) => { - pt.destroy(err) - process.nextTick(finish, err) - } - ) - } else if (isIterable(ret, true)) { - finishCount++ - pumpToNode(ret, pt, finish, { - end - }) - } else if (isReadableStream(ret) || isTransformStream(ret)) { - const toRead = ret.readable || ret - finishCount++ - pumpToNode(toRead, pt, finish, { - end - }) - } else { - throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) - } - ret = pt - const { destroy, cleanup } = destroyer(ret, false, true) - destroys.push(destroy) - if (isLastStream) { - lastStreamCleanup.push(cleanup) +"use strict"; + + +var has = __nccwpck_require__(76339); + +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} + +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} + +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } + + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node + : nodeVersion; + + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } + + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} + +var data = __nccwpck_require__(79849); + +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; + + +/***/ }), + +/***/ 81679: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var async = __nccwpck_require__(37600); +async.core = __nccwpck_require__(4632); +async.isCore = __nccwpck_require__(16520); +async.sync = __nccwpck_require__(92966); + +module.exports = async; + + +/***/ }), + +/***/ 37600: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(57147); +var getHomedir = __nccwpck_require__(58108); +var path = __nccwpck_require__(71017); +var caller = __nccwpck_require__(50907); +var nodeModulesPaths = __nccwpck_require__(4287); +var normalizeOptions = __nccwpck_require__(48315); +var isCore = __nccwpck_require__(53230); + +var realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); } - } - } else if (isNodeStream(stream)) { - if (isReadableNodeStream(ret)) { - finishCount += 2 - const cleanup = pipe(ret, stream, finish, { - end - }) - if (isReadable(stream) && isLastStream) { - lastStreamCleanup.push(cleanup) + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); } - } else if (isTransformStream(ret) || isReadableStream(ret)) { - const toRead = ret.readable || ret - finishCount++ - pumpToNode(toRead, stream, finish, { - end - }) - } else if (isIterable(ret)) { - finishCount++ - pumpToNode(ret, stream, finish, { - end - }) - } else { - throw new ERR_INVALID_ARG_TYPE( - 'val', - ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], - ret - ) - } - ret = stream - } else if (isWebStream(stream)) { - if (isReadableNodeStream(ret)) { - finishCount++ - pumpToWeb(makeAsyncIterable(ret), stream, finish, { - end - }) - } else if (isReadableStream(ret) || isIterable(ret)) { - finishCount++ - pumpToWeb(ret, stream, finish, { - end - }) - } else if (isTransformStream(ret)) { - finishCount++ - pumpToWeb(ret.readable, stream, finish, { - end - }) - } else { - throw new ERR_INVALID_ARG_TYPE( - 'val', - ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], - ret - ) - } - ret = stream + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); } else { - ret = Duplex.from(stream) - } - } - if ( - (signal !== null && signal !== undefined && signal.aborted) || - (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) - ) { - process.nextTick(abort) - } - return ret -} -function pipe(src, dst, finish, { end }) { - let ended = false - dst.on('close', () => { - if (!ended) { - // Finish if the destination closes before the source has completed. - finish(new ERR_STREAM_PREMATURE_CLOSE()) + cb(null, x); } - }) - src.pipe(dst, { - end: false - }) // If end is true we already will have a listener to end dst. +}; - if (end) { - // Compat. Before node v10.12.0 stdio used to throw an error so - // pipe() did/does not end() stdio destinations. - // Now they allow it but "secretly" don't close the underlying fd. +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; - function endFn() { - ended = true - dst.end() +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); } - if (isReadableFinished(src)) { - // End the destination if the source has already ended. - process.nextTick(endFn) - } else { - src.once('end', endFn) + return dirs; +}; + +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; } - } else { - finish() - } - eos( - src, - { - readable: true, - writable: false - }, - (err) => { - const rState = src._readableState - if ( - err && - err.code === 'ERR_STREAM_PREMATURE_CLOSE' && - rState && - rState.ended && - !rState.errored && - !rState.errorEmitted - ) { - // Some readable streams will emit 'close' before 'end'. However, since - // this is on the readable side 'end' should still be emitted if the - // stream has been ended and no error emitted. This should be allowed in - // favor of backwards compatibility. Since the stream is piped to a - // destination this should not result in any observable difference. - // We don't need to check if this is a writable premature close since - // eos will only fail with premature close on the reading side for - // duplex streams. - src.once('end', finish).once('error', finish) - } else { - finish(err) - } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); } - ) - return eos( - dst, - { - readable: false, - writable: true - }, - finish - ) -} -module.exports = { - pipelineImpl, - pipeline -} + opts = normalizeOptions(x, opts); -/***/ }), + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } + var packageIterator = opts.packageIterator; -/***/ 57920: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + opts.paths = opts.paths || defaultPaths(); + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); -/* replacement start */ + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } -const process = __nccwpck_require__(45676) + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } -/* replacement end */ + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } -const { - ArrayPrototypeIndexOf, - NumberIsInteger, - NumberIsNaN, - NumberParseInt, - ObjectDefineProperties, - ObjectKeys, - ObjectSetPrototypeOf, - Promise, - SafeSet, - SymbolAsyncDispose, - SymbolAsyncIterator, - Symbol -} = __nccwpck_require__(89629) -module.exports = Readable -Readable.ReadableState = ReadableState -const { EventEmitter: EE } = __nccwpck_require__(82361) -const { Stream, prependListener } = __nccwpck_require__(49792) -const { Buffer } = __nccwpck_require__(14300) -const { addAbortSignal } = __nccwpck_require__(80289) -const eos = __nccwpck_require__(76080) -let debug = (__nccwpck_require__(46959).debuglog)('stream', (fn) => { - debug = fn -}) -const BufferList = __nccwpck_require__(52746) -const destroyImpl = __nccwpck_require__(97049) -const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) -const { - aggregateTwoErrors, - codes: { - ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED, - ERR_OUT_OF_RANGE, - ERR_STREAM_PUSH_AFTER_EOF, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT - }, - AbortError -} = __nccwpck_require__(80529) -const { validateObject } = __nccwpck_require__(669) -const kPaused = Symbol('kPaused') -const { StringDecoder } = __nccwpck_require__(94841) -const from = __nccwpck_require__(39082) -ObjectSetPrototypeOf(Readable.prototype, Stream.prototype) -ObjectSetPrototypeOf(Readable, Stream) -const nop = () => {} -const { errorOrDestroy } = destroyImpl -const kObjectMode = 1 << 0 -const kEnded = 1 << 1 -const kEndEmitted = 1 << 2 -const kReading = 1 << 3 -const kConstructed = 1 << 4 -const kSync = 1 << 5 -const kNeedReadable = 1 << 6 -const kEmittedReadable = 1 << 7 -const kReadableListening = 1 << 8 -const kResumeScheduled = 1 << 9 -const kErrorEmitted = 1 << 10 -const kEmitClose = 1 << 11 -const kAutoDestroy = 1 << 12 -const kDestroyed = 1 << 13 -const kClosed = 1 << 14 -const kCloseEmitted = 1 << 15 -const kMultiAwaitDrain = 1 << 16 -const kReadingMore = 1 << 17 -const kDataEmitted = 1 << 18 + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); -// TODO(benjamingr) it is likely slower to do it this way than with free functions -function makeBitMapDescriptor(bit) { - return { - enumerable: false, - get() { - return (this.state & bit) !== 0 - }, - set(value) { - if (value) this.state |= bit - else this.state &= ~bit + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } } - } -} -ObjectDefineProperties(ReadableState.prototype, { - objectMode: makeBitMapDescriptor(kObjectMode), - ended: makeBitMapDescriptor(kEnded), - endEmitted: makeBitMapDescriptor(kEndEmitted), - reading: makeBitMapDescriptor(kReading), - // Stream is still being constructed and cannot be - // destroyed until construction finished or failed. - // Async construction is opt in, therefore we start as - // constructed. - constructed: makeBitMapDescriptor(kConstructed), - // A flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - sync: makeBitMapDescriptor(kSync), - // Whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - needReadable: makeBitMapDescriptor(kNeedReadable), - emittedReadable: makeBitMapDescriptor(kEmittedReadable), - readableListening: makeBitMapDescriptor(kReadableListening), - resumeScheduled: makeBitMapDescriptor(kResumeScheduled), - // True if the error was already emitted and should not be thrown again. - errorEmitted: makeBitMapDescriptor(kErrorEmitted), - emitClose: makeBitMapDescriptor(kEmitClose), - autoDestroy: makeBitMapDescriptor(kAutoDestroy), - // Has it been destroyed. - destroyed: makeBitMapDescriptor(kDestroyed), - // Indicates whether the stream has finished destroying. - closed: makeBitMapDescriptor(kClosed), - // True if close has been emitted or would have been emitted - // depending on emitClose. - closeEmitted: makeBitMapDescriptor(kCloseEmitted), - multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), - // If true, a maybeReadMore has been scheduled. - readingMore: makeBitMapDescriptor(kReadingMore), - dataEmitted: makeBitMapDescriptor(kDataEmitted) -}) -function ReadableState(options, stream, isDuplex) { - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(72613) - // Bit map field to store ReadableState more effciently with 1 bit per field - // instead of a V8 slot per field. - this.state = kEmitClose | kAutoDestroy | kConstructed | kSync - // Object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away. - if (options && options.objectMode) this.state |= kObjectMode - if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); - // The point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - this.highWaterMark = options - ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) - : getDefaultHighWaterMark(false) + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift(). - this.buffer = new BufferList() - this.length = 0 - this.pipes = [] - this.flowing = null - this[kPaused] = null + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) cb(err); - // Should close be emitted on destroy. Defaults to true. - if (options && options.emitClose === false) this.state &= ~kEmitClose + var pkg = pkgParam; - // Should .destroy() be called after 'end' (and potentially 'finish'). - if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } - // Indicates whether the stream has errored. When true no further - // _read calls, 'data' or 'readable' events should occur. This is needed - // since when autoDestroy is disabled we need a way to tell whether the - // stream has failed. - this.errored = null + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); - // Ref the piped dest which we need a drain event on it - // type: null | Writable | Set. - this.awaitDrainWriters = null - this.decoder = null - this.encoding = null - if (options && options.encoding) { - this.decoder = new StringDecoder(options.encoding) - this.encoding = options.encoding - } -} -function Readable(options) { - if (!(this instanceof Readable)) return new Readable(options) + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) return cb(err); - // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5. - const isDuplex = this instanceof __nccwpck_require__(72613) - this._readableState = new ReadableState(options, this, isDuplex) - if (options) { - if (typeof options.read === 'function') this._read = options.read - if (typeof options.destroy === 'function') this._destroy = options.destroy - if (typeof options.construct === 'function') this._construct = options.construct - if (options.signal && !isDuplex) addAbortSignal(options.signal, this) - } - Stream.call(this, options) - destroyImpl.construct(this, () => { - if (this._readableState.needReadable) { - maybeReadMore(this, this._readableState) + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); } - }) -} -Readable.prototype.destroy = destroyImpl.destroy -Readable.prototype._undestroy = destroyImpl.undestroy -Readable.prototype._destroy = function (err, cb) { - cb(err) -} -Readable.prototype[EE.captureRejectionSymbol] = function (err) { - this.destroy(err) -} -Readable.prototype[SymbolAsyncDispose] = function () { - let error - if (!this.destroyed) { - error = this.readableEnded ? null : new AbortError() - this.destroy(error) - } - return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) -} -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - return readableAddChunk(this, chunk, encoding, false) -} + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; -// Unshift should *always* be something directly out of read(). -Readable.prototype.unshift = function (chunk, encoding) { - return readableAddChunk(this, chunk, encoding, true) -} -function readableAddChunk(stream, chunk, encoding, addToFront) { - debug('readableAddChunk', chunk) - const state = stream._readableState - let err - if ((state.state & kObjectMode) === 0) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding - if (state.encoding !== encoding) { - if (addToFront && state.encoding) { - // When unshifting, if state.encoding is set, we have to save - // the string in the BufferList with the state encoding. - chunk = Buffer.from(chunk, encoding).toString(state.encoding) - } else { - chunk = Buffer.from(chunk, encoding) - encoding = '' + isDirectory(path.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); } - } - } else if (chunk instanceof Buffer) { - encoding = '' - } else if (Stream._isUint8Array(chunk)) { - chunk = Stream._uint8ArrayToBuffer(chunk) - encoding = '' - } else if (chunk != null) { - err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) } - } - if (err) { - errorOrDestroy(stream, err) - } else if (chunk === null) { - state.state &= ~kReading - onEofChunk(stream, state) - } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { - if (addToFront) { - if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) - else if (state.destroyed || state.errored) return false - else addChunk(stream, state, chunk, true) - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()) - } else if (state.destroyed || state.errored) { - return false - } else { - state.state &= ~kReading - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk) - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false) - else maybeReadMore(stream, state) - } else { - addChunk(stream, state, chunk, false) - } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); } - } else if (!addToFront) { - state.state &= ~kReading - maybeReadMore(stream, state) - } +}; - // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - return !state.ended && (state.length < state.highWaterMark || state.length === 0) -} -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { - // Use the guard to avoid creating `Set()` repeatedly - // when we have multiple pipes. - if ((state.state & kMultiAwaitDrain) !== 0) { - state.awaitDrainWriters.clear() - } else { - state.awaitDrainWriters = null - } - state.dataEmitted = true - stream.emit('data', chunk) - } else { - // Update the buffer info. - state.length += state.objectMode ? 1 : chunk.length - if (addToFront) state.buffer.unshift(chunk) - else state.buffer.push(chunk) - if ((state.state & kNeedReadable) !== 0) emitReadable(stream) - } - maybeReadMore(stream, state) -} -Readable.prototype.isPaused = function () { - const state = this._readableState - return state[kPaused] === true || state.flowing === false -} -// Backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - const decoder = new StringDecoder(enc) - this._readableState.decoder = decoder - // If setEncoding(null), decoder.encoding equals utf8. - this._readableState.encoding = this._readableState.decoder.encoding - const buffer = this._readableState.buffer - // Iterate over current buffer to convert already stored Buffers: - let content = '' - for (const data of buffer) { - content += decoder.write(data) - } - buffer.clear() - if (content !== '') buffer.push(content) - this._readableState.length = content.length - return this -} +/***/ }), -// Don't raise the hwm > 1GB. -const MAX_HWM = 0x40000000 -function computeNewHighWaterMark(n) { - if (n > MAX_HWM) { - throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts. - n-- - n |= n >>> 1 - n |= n >>> 2 - n |= n >>> 4 - n |= n >>> 8 - n |= n >>> 16 - n++ - } - return n -} +/***/ 50907: +/***/ ((module) => { -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || (state.length === 0 && state.ended)) return 0 - if ((state.state & kObjectMode) !== 0) return 1 - if (NumberIsNaN(n)) { - // Only flow one buffer at a time. - if (state.flowing && state.length) return state.buffer.first().length - return state.length - } - if (n <= state.length) return n - return state.ended ? state.length : 0 +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; + + +/***/ }), + +/***/ 4632: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var isCoreModule = __nccwpck_require__(53230); +var data = __nccwpck_require__(19495); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = isCoreModule(mod); + } } +module.exports = core; -// You can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n) - // Same as parseInt(undefined, 10), however V8 7.3 performance regressed - // in this scenario, so we are doing it manually. - if (n === undefined) { - n = NaN - } else if (!NumberIsInteger(n)) { - n = NumberParseInt(n, 10) - } - const state = this._readableState - const nOrig = n - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n) - if (n !== 0) state.state &= ~kEmittedReadable +/***/ }), - // If we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if ( - n === 0 && - state.needReadable && - ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) - ) { - debug('read: emitReadable', state.length, state.ended) - if (state.length === 0 && state.ended) endReadable(this) - else emitReadable(this) - return null - } - n = howMuchToRead(n, state) +/***/ 58108: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this) - return null - } +"use strict"; - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - let doRead = (state.state & kNeedReadable) !== 0 - debug('need readable', doRead) +var os = __nccwpck_require__(22037); - // If we currently have less than the highWaterMark, then also read some. - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true - debug('length less than watermark', doRead) - } +// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js - // However, if we've ended, then there's no point, if we're already - // reading, then it's unnecessary, if we're constructing we have to wait, - // and if we're destroyed or errored, then it's not allowed, - if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { - doRead = false - debug('reading, ended or constructing', doRead) - } else if (doRead) { - debug('do read') - state.state |= kReading | kSync - // If the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.state |= kNeedReadable +module.exports = os.homedir || function homedir() { + var home = process.env.HOME; + var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; - // Call internal read method - try { - this._read(state.highWaterMark) - } catch (err) { - errorOrDestroy(this, err) + if (process.platform === 'win32') { + return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; } - state.state &= ~kSync - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state) - } - let ret - if (n > 0) ret = fromList(n, state) - else ret = null - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark - n = 0 - } else { - state.length -= n - if (state.multiAwaitDrain) { - state.awaitDrainWriters.clear() - } else { - state.awaitDrainWriters = null + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); } - } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this) - } - if (ret !== null && !state.errorEmitted && !state.closeEmitted) { - state.dataEmitted = true - this.emit('data', ret) - } - return ret -} -function onEofChunk(stream, state) { - debug('onEofChunk') - if (state.ended) return - if (state.decoder) { - const chunk = state.decoder.end() - if (chunk && chunk.length) { - state.buffer.push(chunk) - state.length += state.objectMode ? 1 : chunk.length + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens } - } - state.ended = true - if (state.sync) { - // If we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call. - emitReadable(stream) - } else { - // Emit 'readable' now to make sure it gets picked up. - state.needReadable = false - state.emittedReadable = true - // We have to emit readable now that we are EOF. Modules - // in the ecosystem (e.g. dicer) rely on this event being sync. - emitReadable_(stream) - } -} -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - const state = stream._readableState - debug('emitReadable', state.needReadable, state.emittedReadable) - state.needReadable = false - if (!state.emittedReadable) { - debug('emitReadable', state.flowing) - state.emittedReadable = true - process.nextTick(emitReadable_, stream) - } -} -function emitReadable_(stream) { - const state = stream._readableState - debug('emitReadable_', state.destroyed, state.length, state.ended) - if (!state.destroyed && !state.errored && (state.length || state.ended)) { - stream.emit('readable') - state.emittedReadable = false - } + return home || null; +}; - // The stream needs another readable event if: - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark - flow(stream) -} -// At this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore && state.constructed) { - state.readingMore = true - process.nextTick(maybeReadMore_, stream, state) - } -} -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while ( - !state.reading && - !state.ended && - (state.length < state.highWaterMark || (state.flowing && state.length === 0)) - ) { - const len = state.length - debug('maybeReadMore read 0') - stream.read(0) - if (len === state.length) - // Didn't get any data, stop spinning. - break - } - state.readingMore = false -} +/***/ }), -// Abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') -} -Readable.prototype.pipe = function (dest, pipeOpts) { - const src = this - const state = this._readableState - if (state.pipes.length === 1) { - if (!state.multiAwaitDrain) { - state.multiAwaitDrain = true - state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []) - } - } - state.pipes.push(dest) - debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts) - const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr - const endFn = doEnd ? onend : unpipe - if (state.endEmitted) process.nextTick(endFn) - else src.once('end', endFn) - dest.on('unpipe', onunpipe) - function onunpipe(readable, unpipeInfo) { - debug('onunpipe') - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true - cleanup() - } - } - } - function onend() { - debug('onend') - dest.end() - } - let ondrain - let cleanedUp = false - function cleanup() { - debug('cleanup') - // Cleanup event handlers once the pipe is broken. - dest.removeListener('close', onclose) - dest.removeListener('finish', onfinish) - if (ondrain) { - dest.removeListener('drain', ondrain) - } - dest.removeListener('error', onerror) - dest.removeListener('unpipe', onunpipe) - src.removeListener('end', onend) - src.removeListener('end', unpipe) - src.removeListener('data', ondata) - cleanedUp = true +/***/ 16520: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain() - } - function pause() { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if (!cleanedUp) { - if (state.pipes.length === 1 && state.pipes[0] === dest) { - debug('false write response, pause', 0) - state.awaitDrainWriters = dest - state.multiAwaitDrain = false - } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { - debug('false write response, pause', state.awaitDrainWriters.size) - state.awaitDrainWriters.add(dest) - } - src.pause() - } - if (!ondrain) { - // When the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - ondrain = pipeOnDrain(src, dest) - dest.on('drain', ondrain) - } - } - src.on('data', ondata) - function ondata(chunk) { - debug('ondata') - const ret = dest.write(chunk) - debug('dest.write', ret) - if (ret === false) { - pause() - } - } +var isCoreModule = __nccwpck_require__(53230); - // If the dest has an error, then stop piping into it. - // However, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er) - unpipe() - dest.removeListener('error', onerror) - if (dest.listenerCount('error') === 0) { - const s = dest._writableState || dest._readableState - if (s && !s.errorEmitted) { - // User incorrectly emitted 'error' directly on the stream. - errorOrDestroy(dest, er) - } else { - dest.emit('error', er) - } - } - } +module.exports = function isCore(x) { + return isCoreModule(x); +}; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror) - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish) - unpipe() - } - dest.once('close', onclose) - function onfinish() { - debug('onfinish') - dest.removeListener('close', onclose) - unpipe() - } - dest.once('finish', onfinish) - function unpipe() { - debug('unpipe') - src.unpipe(dest) - } +/***/ }), - // Tell the dest that it's being piped to. - dest.emit('pipe', src) +/***/ 4287: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Start the flow if it hasn't been started already. +var path = __nccwpck_require__(71017); +var parse = path.parse || __nccwpck_require__(5980); // eslint-disable-line global-require - if (dest.writableNeedDrain === true) { - pause() - } else if (!state.flowing) { - debug('pipe resume') - src.resume() - } - return dest -} -function pipeOnDrain(src, dest) { - return function pipeOnDrainFunctionResult() { - const state = src._readableState +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } - // `ondrain` will call directly, - // `this` maybe not a reference to dest, - // so we use the real dest here. - if (state.awaitDrainWriters === dest) { - debug('pipeOnDrain', 1) - state.awaitDrainWriters = null - } else if (state.multiAwaitDrain) { - debug('pipeOnDrain', state.awaitDrainWriters.size) - state.awaitDrainWriters.delete(dest) + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); } - if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { - src.resume() + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); } - } -} -Readable.prototype.unpipe = function (dest) { - const state = this._readableState - const unpipeInfo = { - hasUnpiped: false - } - // If we're not piping anywhere, then do nothing. - if (state.pipes.length === 0) return this - if (!dest) { - // remove all. - const dests = state.pipes - state.pipes = [] - this.pause() - for (let i = 0; i < dests.length; i++) - dests[i].emit('unpipe', this, { - hasUnpiped: false - }) - return this - } + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; - // Try to find the right one. - const index = ArrayPrototypeIndexOf(state.pipes, dest) - if (index === -1) return this - state.pipes.splice(index, 1) - if (state.pipes.length === 0) this.pause() - dest.emit('unpipe', this, unpipeInfo) - return this -} -// Set up data events if they are asked for -// Ensure readable listeners eventually get something. -Readable.prototype.on = function (ev, fn) { - const res = Stream.prototype.on.call(this, ev, fn) - const state = this._readableState - if (ev === 'data') { - // Update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0 +/***/ }), - // Try start flowing on next tick if stream isn't explicitly paused. - if (state.flowing !== false) this.resume() - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true - state.flowing = false - state.emittedReadable = false - debug('on readable', state.length, state.reading) - if (state.length) { - emitReadable(this) - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this) - } - } - } - return res -} -Readable.prototype.addListener = Readable.prototype.on -Readable.prototype.removeListener = function (ev, fn) { - const res = Stream.prototype.removeListener.call(this, ev, fn) - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this) - } - return res -} -Readable.prototype.off = Readable.prototype.removeListener -Readable.prototype.removeAllListeners = function (ev) { - const res = Stream.prototype.removeAllListeners.apply(this, arguments) - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this) - } - return res -} -function updateReadableListening(self) { - const state = self._readableState - state.readableListening = self.listenerCount('readable') > 0 - if (state.resumeScheduled && state[kPaused] === false) { - // Flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true +/***/ 48315: +/***/ ((module) => { - // Crude way to check if we should resume. - } else if (self.listenerCount('data') > 0) { - self.resume() - } else if (!state.readableListening) { - state.flowing = null - } -} -function nReadingNextTick(self) { - debug('readable nexttick read 0') - self.read(0) -} +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - const state = this._readableState - if (!state.flowing) { - debug('resume') - // We flow only if there is no one listening - // for readable, but we still have to call - // resume(). - state.flowing = !state.readableListening - resume(this, state) - } - state[kPaused] = false - return this -} -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true - process.nextTick(resume_, stream, state) - } -} -function resume_(stream, state) { - debug('resume', state.reading) - if (!state.reading) { - stream.read(0) - } - state.resumeScheduled = false - stream.emit('resume') - flow(stream) - if (state.flowing && !state.reading) stream.read(0) -} -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing) - if (this._readableState.flowing !== false) { - debug('pause') - this._readableState.flowing = false - this.emit('pause') - } - this._readableState[kPaused] = true - return this -} -function flow(stream) { - const state = stream._readableState - debug('flow', state.flowing) - while (state.flowing && stream.read() !== null); -} + return opts || {}; +}; -// Wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - let paused = false - // TODO (ronag): Should this.destroy(err) emit - // 'error' on the wrapped stream? Would require - // a static factory method, e.g. Readable.wrap(stream). +/***/ }), - stream.on('data', (chunk) => { - if (!this.push(chunk) && stream.pause) { - paused = true - stream.pause() - } - }) - stream.on('end', () => { - this.push(null) - }) - stream.on('error', (err) => { - errorOrDestroy(this, err) - }) - stream.on('close', () => { - this.destroy() - }) - stream.on('destroy', () => { - this.destroy() - }) - this._read = () => { - if (paused && stream.resume) { - paused = false - stream.resume() - } - } +/***/ 92966: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Proxy all the other methods. Important when wrapping filters and duplexes. - const streamKeys = ObjectKeys(stream) - for (let j = 1; j < streamKeys.length; j++) { - const i = streamKeys[j] - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = stream[i].bind(stream) - } - } - return this -} -Readable.prototype[SymbolAsyncIterator] = function () { - return streamToAsyncIterator(this) -} -Readable.prototype.iterator = function (options) { - if (options !== undefined) { - validateObject(options, 'options') - } - return streamToAsyncIterator(this, options) -} -function streamToAsyncIterator(stream, options) { - if (typeof stream.read !== 'function') { - stream = Readable.wrap(stream, { - objectMode: true - }) - } - const iter = createAsyncIterator(stream, options) - iter.stream = stream - return iter -} -async function* createAsyncIterator(stream, options) { - let callback = nop - function next(resolve) { - if (this === stream) { - callback() - callback = nop - } else { - callback = resolve - } - } - stream.on('readable', next) - let error - const cleanup = eos( - stream, - { - writable: false - }, - (err) => { - error = err ? aggregateTwoErrors(error, err) : null - callback() - callback = nop - } - ) - try { - while (true) { - const chunk = stream.destroyed ? null : stream.read() - if (chunk !== null) { - yield chunk - } else if (error) { - throw error - } else if (error === null) { - return - } else { - await new Promise(next) - } - } - } catch (err) { - error = aggregateTwoErrors(error, err) - throw error - } finally { - if ( - (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && - (error === undefined || stream._readableState.autoDestroy) - ) { - destroyImpl.destroyer(stream, null) - } else { - stream.off('readable', next) - cleanup() - } - } -} +var isCore = __nccwpck_require__(53230); +var fs = __nccwpck_require__(57147); +var path = __nccwpck_require__(71017); +var getHomedir = __nccwpck_require__(58108); +var caller = __nccwpck_require__(50907); +var nodeModulesPaths = __nccwpck_require__(4287); +var normalizeOptions = __nccwpck_require__(48315); -// Making it explicit these properties are not enumerable -// because otherwise some prototype manipulation in -// userland will fail. -ObjectDefineProperties(Readable.prototype, { - readable: { - __proto__: null, - get() { - const r = this._readableState - // r.readable === false means that this is part of a Duplex stream - // where the readable side was disabled upon construction. - // Compat. The user might manually disable readable side through - // deprecated setter. - return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted - }, - set(val) { - // Backwards compat. - if (this._readableState) { - this._readableState.readable = !!val - } - } - }, - readableDidRead: { - __proto__: null, - enumerable: false, - get: function () { - return this._readableState.dataEmitted - } - }, - readableAborted: { - __proto__: null, - enumerable: false, - get: function () { - return !!( - this._readableState.readable !== false && - (this._readableState.destroyed || this._readableState.errored) && - !this._readableState.endEmitted - ) - } - }, - readableHighWaterMark: { - __proto__: null, - enumerable: false, - get: function () { - return this._readableState.highWaterMark - } - }, - readableBuffer: { - __proto__: null, - enumerable: false, - get: function () { - return this._readableState && this._readableState.buffer - } - }, - readableFlowing: { - __proto__: null, - enumerable: false, - get: function () { - return this._readableState.flowing - }, - set: function (state) { - if (this._readableState) { - this._readableState.flowing = state - } - } - }, - readableLength: { - __proto__: null, - enumerable: false, - get() { - return this._readableState.length - } - }, - readableObjectMode: { - __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.objectMode : false - } - }, - readableEncoding: { - __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.encoding : null +var realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; } - }, - errored: { - __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.errored : null + return !!stat && (stat.isFile() || stat.isFIFO()); +}; + +var defaultIsDir = function isDirectory(dir) { + try { + var stat = fs.statSync(dir, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; } - }, - closed: { - __proto__: null, - get() { - return this._readableState ? this._readableState.closed : false + return !!stat && stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } } - }, - destroyed: { - __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.destroyed : false - }, - set(value) { - // We ignore the value if the stream - // has not been initialized yet. - if (!this._readableState) { - return - } + return x; +}; - // Backward compatibility, the user is explicitly - // managing destroyed. - this._readableState.destroyed = value +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); } - }, - readableEnded: { - __proto__: null, - enumerable: false, - get() { - return this._readableState ? this._readableState.endEmitted : false + return x; +}; + +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); } - } -}) -ObjectDefineProperties(ReadableState.prototype, { - // Legacy getter for `pipesCount`. - pipesCount: { - __proto__: null, - get() { - return this.pipes.length + return dirs; +}; + +module.exports = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); } - }, - // Legacy property for `paused`. - paused: { - __proto__: null, - get() { - return this[kPaused] !== false - }, - set(value) { - this[kPaused] = !!value + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); } - } -}) + var packageIterator = opts.packageIterator; -// Exposed for testing purposes only. -Readable._fromList = fromList + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered. - if (state.length === 0) return null - let ret - if (state.objectMode) ret = state.buffer.shift() - else if (!n || n >= state.length) { - // Read it all, truncate the list. - if (state.decoder) ret = state.buffer.join('') - else if (state.buffer.length === 1) ret = state.buffer.first() - else ret = state.buffer.concat(state.length) - state.buffer.clear() - } else { - // read part of list. - ret = state.buffer.consume(n, state.decoder) - } - return ret -} -function endReadable(stream) { - const state = stream._readableState - debug('endReadable', state.endEmitted) - if (!state.endEmitted) { - state.ended = true - process.nextTick(endReadableNT, state, stream) - } -} -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length) + opts.paths = opts.paths || defaultPaths(); - // Check that we didn't get one last unshift. - if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { - state.endEmitted = true - stream.emit('end') - if (stream.writable && stream.allowHalfOpen === false) { - process.nextTick(endWritableNT, stream) - } else if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well. - const wState = stream._writableState - const autoDestroy = - !wState || - (wState.autoDestroy && - // We don't expect the writable to ever 'finish' - // if writable is explicitly set to false. - (wState.finished || wState.writable === false)) - if (autoDestroy) { - stream.destroy() - } - } - } -} -function endWritableNT(stream) { - const writable = stream.writable && !stream.writableEnded && !stream.destroyed - if (writable) { - stream.end() - } -} -Readable.from = function (iterable, opts) { - return from(Readable, iterable, opts) -} -let webStreamsAdapters + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); -// Lazy to avoid circular references -function lazyWebStreams() { - if (webStreamsAdapters === undefined) webStreamsAdapters = {} - return webStreamsAdapters -} -Readable.fromWeb = function (readableStream, options) { - return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) -} -Readable.toWeb = function (streamReadable, options) { - return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) -} -Readable.wrap = function (src, options) { - var _ref, _src$readableObjectMo - return new Readable({ - objectMode: - (_ref = - (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined - ? _src$readableObjectMo - : src.objectMode) !== null && _ref !== undefined - ? _ref - : true, - ...options, - destroy(err, callback) { - destroyImpl.destroyer(src, err) - callback(err) + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); } - }).wrap(src) -} + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; -/***/ }), - -/***/ 39948: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); -"use strict"; + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + if (isFile(x)) { + return x; + } -const { MathFloor, NumberIsInteger } = __nccwpck_require__(89629) -const { validateInteger } = __nccwpck_require__(669) -const { ERR_INVALID_ARG_VALUE } = (__nccwpck_require__(80529).codes) -let defaultHighWaterMarkBytes = 16 * 1024 -let defaultHighWaterMarkObjectMode = 16 -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null -} -function getDefaultHighWaterMark(objectMode) { - return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes -} -function setDefaultHighWaterMark(objectMode, value) { - validateInteger(value, 'value', 0) - if (objectMode) { - defaultHighWaterMarkObjectMode = value - } else { - defaultHighWaterMarkBytes = value - } -} -function getHighWaterMark(state, options, duplexKey, isDuplex) { - const hwm = highWaterMarkFrom(options, isDuplex, duplexKey) - if (hwm != null) { - if (!NumberIsInteger(hwm) || hwm < 0) { - const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark' - throw new ERR_INVALID_ARG_VALUE(name, hwm) + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } } - return MathFloor(hwm) - } - // Default value - return getDefaultHighWaterMark(state.objectMode) -} -module.exports = { - getHighWaterMark, - getDefaultHighWaterMark, - setDefaultHighWaterMark -} + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); -/***/ }), + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); + } -/***/ 86941: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var pkg = readPackageSync(readFileSync, pkgfile); -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + return { pkg: pkg, dir: dir }; + } + function loadAsDirectorySync(x) { + var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var pkg = readPackageSync(readFileSync, pkgfile); + } catch (e) {} + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } -const { ObjectSetPrototypeOf, Symbol } = __nccwpck_require__(89629) -module.exports = Transform -const { ERR_METHOD_NOT_IMPLEMENTED } = (__nccwpck_require__(80529).codes) -const Duplex = __nccwpck_require__(72613) -const { getHighWaterMark } = __nccwpck_require__(39948) -ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype) -ObjectSetPrototypeOf(Transform, Duplex) -const kCallback = Symbol('kCallback') -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options) + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } - // TODO (ronag): This should preferably always be - // applied but would be semver-major. Or even better; - // make Transform a Readable with the Writable interface. - const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null - if (readableHighWaterMark === 0) { - // A Duplex will buffer both on the writable and readable side while - // a Transform just wants to buffer hwm number of elements. To avoid - // buffering twice we disable buffering on the writable side. - options = { - ...options, - highWaterMark: null, - readableHighWaterMark, - // TODO (ronag): 0 is not optimal since we have - // a "bug" where we check needDrain before calling _write and not after. - // Refs: https://github.com/nodejs/node/pull/32887 - // Refs: https://github.com/nodejs/node/pull/35941 - writableHighWaterMark: options.writableHighWaterMark || 0 + return loadAsFileSync(path.join(x, '/index')); } - } - Duplex.call(this, options) - // We have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false - this[kCallback] = null - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform - if (typeof options.flush === 'function') this._flush = options.flush - } + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); - // When the writable side finishes, then flush out anything remaining. - // Backwards compat. Some Transform streams incorrectly implement _final - // instead of or in addition to _flush. By using 'prefinish' instead of - // implementing _final we continue supporting this unfortunate use case. - this.on('prefinish', prefinish) -} -function final(cb) { - if (typeof this._flush === 'function' && !this.destroyed) { - this._flush((er, data) => { - if (er) { - if (cb) { - cb(er) - } else { - this.destroy(er) + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(path.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } } - return - } - if (data != null) { - this.push(data) - } - this.push(null) - if (cb) { - cb() - } - }) - } else { - this.push(null) - if (cb) { - cb() - } - } -} -function prefinish() { - if (this._final !== final) { - final.call(this) - } -} -Transform.prototype._final = final -Transform.prototype._transform = function (chunk, encoding, callback) { - throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') -} -Transform.prototype._write = function (chunk, encoding, callback) { - const rState = this._readableState - const wState = this._writableState - const length = rState.length - this._transform(chunk, encoding, (err, val) => { - if (err) { - callback(err) - return - } - if (val != null) { - this.push(val) - } - if ( - wState.ended || - // Backwards compat. - length === rState.length || - // Backwards compat. - rState.length < rState.highWaterMark - ) { - callback() - } else { - this[kCallback] = callback } - }) -} -Transform.prototype._read = function () { - if (this[kCallback]) { - const callback = this[kCallback] - this[kCallback] = null - callback() - } -} +}; /***/ }), -/***/ 27981: +/***/ 32428: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = __nccwpck_require__(89629) - -// We need to use SymbolFor to make these globally available -// for interopt with readable-stream, i.e. readable-stream -// and node core needs to be able to read/write private state -// from each other for proper interoperability. -const kIsDestroyed = SymbolFor('nodejs.stream.destroyed') -const kIsErrored = SymbolFor('nodejs.stream.errored') -const kIsReadable = SymbolFor('nodejs.stream.readable') -const kIsWritable = SymbolFor('nodejs.stream.writable') -const kIsDisturbed = SymbolFor('nodejs.stream.disturbed') -const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise') -const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction') -function isReadableNodeStream(obj, strict = false) { - var _obj$_readableState - return !!( - ( - obj && - typeof obj.pipe === 'function' && - typeof obj.on === 'function' && - (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && - (!obj._writableState || - ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined - ? undefined - : _obj$_readableState.readable) !== false) && - // Duplex - (!obj._writableState || obj._readableState) - ) // Writable has .pipe. - ) -} -function isWritableNodeStream(obj) { - var _obj$_writableState - return !!( - ( - obj && - typeof obj.write === 'function' && - typeof obj.on === 'function' && - (!obj._readableState || - ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined - ? undefined - : _obj$_writableState.writable) !== false) - ) // Duplex - ) -} -function isDuplexNodeStream(obj) { - return !!( - obj && - typeof obj.pipe === 'function' && - obj._readableState && - typeof obj.on === 'function' && - typeof obj.write === 'function' - ) -} -function isNodeStream(obj) { - return ( - obj && - (obj._readableState || - obj._writableState || - (typeof obj.write === 'function' && typeof obj.on === 'function') || - (typeof obj.pipe === 'function' && typeof obj.on === 'function')) - ) -} -function isReadableStream(obj) { - return !!( - obj && - !isNodeStream(obj) && - typeof obj.pipeThrough === 'function' && - typeof obj.getReader === 'function' && - typeof obj.cancel === 'function' - ) -} -function isWritableStream(obj) { - return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') -} -function isTransformStream(obj) { - return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') -} -function isWebStream(obj) { - return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) -} -function isIterable(obj, isAsync) { - if (obj == null) return false - if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' - if (isAsync === false) return typeof obj[SymbolIterator] === 'function' - return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' -} -function isDestroyed(stream) { - if (!isNodeStream(stream)) return null - const wState = stream._writableState - const rState = stream._readableState - const state = wState || rState - return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) -} - -// Have been end():d. -function isWritableEnded(stream) { - if (!isWritableNodeStream(stream)) return null - if (stream.writableEnded === true) return true - const wState = stream._writableState - if (wState !== null && wState !== undefined && wState.errored) return false - if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null - return wState.ended -} +var assert = __nccwpck_require__(39491); +var isExpression = __nccwpck_require__(53448); +var characterParser = __nccwpck_require__(8937); +var error = __nccwpck_require__(11449); -// Have emitted 'finish'. -function isWritableFinished(stream, strict) { - if (!isWritableNodeStream(stream)) return null - if (stream.writableFinished === true) return true - const wState = stream._writableState - if (wState !== null && wState !== undefined && wState.errored) return false - if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null - return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) +module.exports = lex; +module.exports.Lexer = Lexer; +function lex(str, options) { + var lexer = new Lexer(str, options); + return JSON.parse(JSON.stringify(lexer.getTokens())); } -// Have been push(null):d. -function isReadableEnded(stream) { - if (!isReadableNodeStream(stream)) return null - if (stream.readableEnded === true) return true - const rState = stream._readableState - if (!rState || rState.errored) return false - if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null - return rState.ended -} +/** + * Initialize `Lexer` with the given `str`. + * + * @param {String} str + * @param {String} filename + * @api private + */ -// Have emitted 'end'. -function isReadableFinished(stream, strict) { - if (!isReadableNodeStream(stream)) return null - const rState = stream._readableState - if (rState !== null && rState !== undefined && rState.errored) return false - if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null - return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) -} -function isReadable(stream) { - if (stream && stream[kIsReadable] != null) return stream[kIsReadable] - if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null - if (isDestroyed(stream)) return false - return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) -} -function isWritable(stream) { - if (stream && stream[kIsWritable] != null) return stream[kIsWritable] - if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null - if (isDestroyed(stream)) return false - return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) -} -function isFinished(stream, opts) { - if (!isNodeStream(stream)) { - return null - } - if (isDestroyed(stream)) { - return true - } - if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { - return false - } - if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { - return false - } - return true -} -function isWritableErrored(stream) { - var _stream$_writableStat, _stream$_writableStat2 - if (!isNodeStream(stream)) { - return null - } - if (stream.writableErrored) { - return stream.writableErrored - } - return (_stream$_writableStat = - (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined - ? undefined - : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined - ? _stream$_writableStat - : null -} -function isReadableErrored(stream) { - var _stream$_readableStat, _stream$_readableStat2 - if (!isNodeStream(stream)) { - return null - } - if (stream.readableErrored) { - return stream.readableErrored - } - return (_stream$_readableStat = - (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined - ? undefined - : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined - ? _stream$_readableStat - : null -} -function isClosed(stream) { - if (!isNodeStream(stream)) { - return null - } - if (typeof stream.closed === 'boolean') { - return stream.closed - } - const wState = stream._writableState - const rState = stream._readableState - if ( - typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || - typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' - ) { - return ( - (wState === null || wState === undefined ? undefined : wState.closed) || - (rState === null || rState === undefined ? undefined : rState.closed) - ) +function Lexer(str, options) { + options = options || {}; + if (typeof str !== 'string') { + throw new Error( + 'Expected source code to be a string but got "' + typeof str + '"' + ); } - if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { - return stream._closed + if (typeof options !== 'object') { + throw new Error( + 'Expected "options" to be an object but got "' + typeof options + '"' + ); } - return null -} -function isOutgoingMessage(stream) { - return ( - typeof stream._closed === 'boolean' && - typeof stream._defaultKeepAlive === 'boolean' && - typeof stream._removedConnection === 'boolean' && - typeof stream._removedContLen === 'boolean' - ) -} -function isServerResponse(stream) { - return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) -} -function isServerRequest(stream) { - var _stream$req - return ( - typeof stream._consuming === 'boolean' && - typeof stream._dumped === 'boolean' && - ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === - undefined - ) -} -function willEmitClose(stream) { - if (!isNodeStream(stream)) return null - const wState = stream._writableState - const rState = stream._readableState - const state = wState || rState - return ( - (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) - ) -} -function isDisturbed(stream) { - var _stream$kIsDisturbed - return !!( - stream && - ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined - ? _stream$kIsDisturbed - : stream.readableDidRead || stream.readableAborted) - ) -} -function isErrored(stream) { - var _ref, - _ref2, - _ref3, - _ref4, - _ref5, - _stream$kIsErrored, - _stream$_readableStat3, - _stream$_writableStat3, - _stream$_readableStat4, - _stream$_writableStat4 - return !!( - stream && - ((_ref = - (_ref2 = - (_ref3 = - (_ref4 = - (_ref5 = - (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined - ? _stream$kIsErrored - : stream.readableErrored) !== null && _ref5 !== undefined - ? _ref5 - : stream.writableErrored) !== null && _ref4 !== undefined - ? _ref4 - : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined - ? undefined - : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined - ? _ref3 - : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined - ? undefined - : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined - ? _ref2 - : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined - ? undefined - : _stream$_readableStat4.errored) !== null && _ref !== undefined - ? _ref - : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined - ? undefined - : _stream$_writableStat4.errored) - ) -} -module.exports = { - isDestroyed, - kIsDestroyed, - isDisturbed, - kIsDisturbed, - isErrored, - kIsErrored, - isReadable, - kIsReadable, - kIsClosedPromise, - kControllerErrorFunction, - kIsWritable, - isClosed, - isDuplexNodeStream, - isFinished, - isIterable, - isReadableNodeStream, - isReadableStream, - isReadableEnded, - isReadableFinished, - isReadableErrored, - isNodeStream, - isWebStream, - isWritable, - isWritableNodeStream, - isWritableStream, - isWritableEnded, - isWritableFinished, - isWritableErrored, - isServerRequest, - isServerResponse, - willEmitClose, - isTransformStream + //Strip any UTF-8 BOM off of the start of `str`, if it exists. + str = str.replace(/^\uFEFF/, ''); + this.input = str.replace(/\r\n|\r/g, '\n'); + this.originalInput = this.input; + this.filename = options.filename; + this.interpolated = options.interpolated || false; + this.lineno = options.startingLine || 1; + this.colno = options.startingColumn || 1; + this.plugins = options.plugins || []; + this.indentStack = [0]; + this.indentRe = null; + // If #{}, !{} or #[] syntax is allowed when adding text + this.interpolationAllowed = true; + this.whitespaceRe = /[ \n\t]/; + + this.tokens = []; + this.ended = false; } +/** + * Lexer prototype. + */ -/***/ }), +Lexer.prototype = { + constructor: Lexer, -/***/ 48488: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + error: function(code, message) { + var err = error(code, message, { + line: this.lineno, + column: this.colno, + filename: this.filename, + src: this.originalInput, + }); + throw err; + }, -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + assert: function(value, message) { + if (!value) this.error('ASSERT_FAILED', message); + }, + + isExpression: function(exp) { + return isExpression(exp, { + throw: true, + }); + }, + + assertExpression: function(exp, noThrow) { + //this verifies that a JavaScript expression is valid + try { + this.callLexerFunction('isExpression', exp); + return true; + } catch (ex) { + if (noThrow) return false; + + // not coming from acorn + if (!ex.loc) throw ex; + + this.incrementLine(ex.loc.line - 1); + this.incrementColumn(ex.loc.column); + var msg = + 'Syntax Error: ' + ex.message.replace(/ \([0-9]+:[0-9]+\)$/, ''); + this.error('SYNTAX_ERROR', msg); + } + }, + + assertNestingCorrect: function(exp) { + //this verifies that code is properly nested, but allows + //invalid JavaScript such as the contents of `attributes` + var res = characterParser(exp); + if (res.isNesting()) { + this.error( + 'INCORRECT_NESTING', + 'Nesting must match on expression `' + exp + '`' + ); + } + }, + + /** + * Construct a token with the given `type` and `val`. + * + * @param {String} type + * @param {String} val + * @return {Object} + * @api private + */ + + tok: function(type, val) { + var res = { + type: type, + loc: { + start: { + line: this.lineno, + column: this.colno, + }, + filename: this.filename, + }, + }; + + if (val !== undefined) res.val = val; + + return res; + }, + + /** + * Set the token's `loc.end` value. + * + * @param {Object} tok + * @returns {Object} + * @api private + */ + + tokEnd: function(tok) { + tok.loc.end = { + line: this.lineno, + column: this.colno, + }; + return tok; + }, + + /** + * Increment `this.lineno` and reset `this.colno`. + * + * @param {Number} increment + * @api private + */ + + incrementLine: function(increment) { + this.lineno += increment; + if (increment) this.colno = 1; + }, + + /** + * Increment `this.colno`. + * + * @param {Number} increment + * @api private + */ + + incrementColumn: function(increment) { + this.colno += increment; + }, + + /** + * Consume the given `len` of input. + * + * @param {Number} len + * @api private + */ -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. + consume: function(len) { + this.input = this.input.substr(len); + }, + /** + * Scan for `type` with the given `regexp`. + * + * @param {String} type + * @param {RegExp} regexp + * @return {Object} + * @api private + */ + scan: function(regexp, type) { + var captures; + if ((captures = regexp.exec(this.input))) { + var len = captures[0].length; + var val = captures[1]; + var diff = len - (val ? val.length : 0); + var tok = this.tok(type, val); + this.consume(len); + this.incrementColumn(diff); + return tok; + } + }, + scanEndOfLine: function(regexp, type) { + var captures; + if ((captures = regexp.exec(this.input))) { + var whitespaceLength = 0; + var whitespace; + var tok; + if ((whitespace = /^([ ]+)([^ ]*)/.exec(captures[0]))) { + whitespaceLength = whitespace[1].length; + this.incrementColumn(whitespaceLength); + } + var newInput = this.input.substr(captures[0].length); + if (newInput[0] === ':') { + this.input = newInput; + tok = this.tok(type, captures[1]); + this.incrementColumn(captures[0].length - whitespaceLength); + return tok; + } + if (/^[ \t]*(\n|$)/.test(newInput)) { + this.input = newInput.substr(/^[ \t]*/.exec(newInput)[0].length); + tok = this.tok(type, captures[1]); + this.incrementColumn(captures[0].length - whitespaceLength); + return tok; + } + } + }, -/* replacement start */ + /** + * Return the indexOf `(` or `{` or `[` / `)` or `}` or `]` delimiters. + * + * Make sure that when calling this function, colno is at the character + * immediately before the beginning. + * + * @return {Number} + * @api private + */ -const process = __nccwpck_require__(45676) + bracketExpression: function(skip) { + skip = skip || 0; + var start = this.input[skip]; + assert( + start === '(' || start === '{' || start === '[', + 'The start character should be "(", "{" or "["' + ); + var end = characterParser.BRACKETS[start]; + var range; + try { + range = characterParser.parseUntil(this.input, end, {start: skip + 1}); + } catch (ex) { + if (ex.index !== undefined) { + var idx = ex.index; + // starting from this.input[skip] + var tmp = this.input.substr(skip).indexOf('\n'); + // starting from this.input[0] + var nextNewline = tmp + skip; + var ptr = 0; + while (idx > nextNewline && tmp !== -1) { + this.incrementLine(1); + idx -= nextNewline + 1; + ptr += nextNewline + 1; + tmp = nextNewline = this.input.substr(ptr).indexOf('\n'); + } -/* replacement end */ + this.incrementColumn(idx); + } + if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { + this.error( + 'NO_END_BRACKET', + 'The end of the string reached with no closing bracket ' + + end + + ' found.' + ); + } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { + this.error('BRACKET_MISMATCH', ex.message); + } + throw ex; + } + return range; + }, -const { - ArrayPrototypeSlice, - Error, - FunctionPrototypeSymbolHasInstance, - ObjectDefineProperty, - ObjectDefineProperties, - ObjectSetPrototypeOf, - StringPrototypeToLowerCase, - Symbol, - SymbolHasInstance -} = __nccwpck_require__(89629) -module.exports = Writable -Writable.WritableState = WritableState -const { EventEmitter: EE } = __nccwpck_require__(82361) -const Stream = (__nccwpck_require__(49792).Stream) -const { Buffer } = __nccwpck_require__(14300) -const destroyImpl = __nccwpck_require__(97049) -const { addAbortSignal } = __nccwpck_require__(80289) -const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) -const { - ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED, - ERR_STREAM_ALREADY_FINISHED, - ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING -} = (__nccwpck_require__(80529).codes) -const { errorOrDestroy } = destroyImpl -ObjectSetPrototypeOf(Writable.prototype, Stream.prototype) -ObjectSetPrototypeOf(Writable, Stream) -function nop() {} -const kOnFinished = Symbol('kOnFinished') -function WritableState(options, stream, isDuplex) { - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(72613) + scanIndentation: function() { + var captures, re; - // Object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!(options && options.objectMode) - if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode) + // established regexp + if (this.indentRe) { + captures = this.indentRe.exec(this.input); + // determine regexp + } else { + // tabs + re = /^\n(\t*) */; + captures = re.exec(this.input); - // The point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write(). - this.highWaterMark = options - ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) - : getDefaultHighWaterMark(false) + // spaces + if (captures && !captures[1].length) { + re = /^\n( *)/; + captures = re.exec(this.input); + } - // if _final has been called. - this.finalCalled = false + // established + if (captures && captures[1].length) this.indentRe = re; + } - // drain event flag. - this.needDrain = false - // At the start of calling end() - this.ending = false - // When end() has been called, and returned. - this.ended = false - // When 'finish' is emitted. - this.finished = false + return captures; + }, - // Has it been destroyed - this.destroyed = false + /** + * end-of-source. + */ - // Should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - const noDecode = !!(options && options.decodeStrings === false) - this.decodeStrings = !noDecode + eos: function() { + if (this.input.length) return; + if (this.interpolated) { + this.error( + 'NO_END_BRACKET', + 'End of line was reached with no closing bracket for interpolation.' + ); + } + for (var i = 0; this.indentStack[i]; i++) { + this.tokens.push(this.tokEnd(this.tok('outdent'))); + } + this.tokens.push(this.tokEnd(this.tok('eos'))); + this.ended = true; + return true; + }, - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' + /** + * Blank line. + */ - // Not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0 + blank: function() { + var captures; + if ((captures = /^\n[ \t]*\n/.exec(this.input))) { + this.consume(captures[0].length - 1); + this.incrementLine(1); + return true; + } + }, - // A flag to see when we're in the middle of a write. - this.writing = false + /** + * Comment. + */ - // When true all writes will be buffered until .uncork() call. - this.corked = 0 + comment: function() { + var captures; + if ((captures = /^\/\/(-)?([^\n]*)/.exec(this.input))) { + this.consume(captures[0].length); + var tok = this.tok('comment', captures[2]); + tok.buffer = '-' != captures[1]; + this.interpolationAllowed = tok.buffer; + this.tokens.push(tok); + this.incrementColumn(captures[0].length); + this.tokEnd(tok); + this.callLexerFunction('pipelessText'); + return true; + } + }, - // A flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true + /** + * Interpolated tag. + */ - // A flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false + interpolation: function() { + if (/^#\{/.test(this.input)) { + var match = this.bracketExpression(1); + this.consume(match.end + 1); + var tok = this.tok('interpolation', match.src); + this.tokens.push(tok); + this.incrementColumn(2); // '#{' + this.assertExpression(match.src); - // The callback that's passed to _write(chunk, cb). - this.onwrite = onwrite.bind(undefined, stream) + var splitted = match.src.split('\n'); + var lines = splitted.length - 1; + this.incrementLine(lines); + this.incrementColumn(splitted[lines].length + 1); // + 1 → '}' + this.tokEnd(tok); + return true; + } + }, - // The callback that the user supplies to write(chunk, encoding, cb). - this.writecb = null + /** + * Tag. + */ - // The amount that is being written when _write is called. - this.writelen = 0 + tag: function() { + var captures; - // Storage for data passed to the afterWrite() callback in case of - // synchronous _write() completion. - this.afterWriteTickInfo = null - resetBuffer(this) + if ((captures = /^(\w(?:[-:\w]*\w)?)/.exec(this.input))) { + var tok, + name = captures[1], + len = captures[0].length; + this.consume(len); + tok = this.tok('tag', name); + this.tokens.push(tok); + this.incrementColumn(len); + this.tokEnd(tok); + return true; + } + }, - // Number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted. - this.pendingcb = 0 + /** + * Filter. + */ - // Stream is still being constructed and cannot be - // destroyed until construction finished or failed. - // Async construction is opt in, therefore we start as - // constructed. - this.constructed = true + filter: function(opts) { + var tok = this.scan(/^:([\w\-]+)/, 'filter'); + var inInclude = opts && opts.inInclude; + if (tok) { + this.tokens.push(tok); + this.incrementColumn(tok.val.length); + this.tokEnd(tok); + this.callLexerFunction('attrs'); + if (!inInclude) { + this.interpolationAllowed = false; + this.callLexerFunction('pipelessText'); + } + return true; + } + }, - // Emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams. - this.prefinished = false + /** + * Doctype. + */ - // True if the error was already emitted and should not be thrown again. - this.errorEmitted = false + doctype: function() { + var node = this.scanEndOfLine(/^doctype *([^\n]*)/, 'doctype'); + if (node) { + this.tokens.push(this.tokEnd(node)); + return true; + } + }, - // Should close be emitted on destroy. Defaults to true. - this.emitClose = !options || options.emitClose !== false + /** + * Id. + */ - // Should .destroy() be called after 'finish' (and potentially 'end'). - this.autoDestroy = !options || options.autoDestroy !== false + id: function() { + var tok = this.scan(/^#([\w-]+)/, 'id'); + if (tok) { + this.tokens.push(tok); + this.incrementColumn(tok.val.length); + this.tokEnd(tok); + return true; + } + if (/^#/.test(this.input)) { + this.error( + 'INVALID_ID', + '"' + + /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + + '" is not a valid ID.' + ); + } + }, - // Indicates whether the stream has errored. When true all write() calls - // should return false. This is needed since when autoDestroy - // is disabled we need a way to tell whether the stream has failed. - this.errored = null + /** + * Class. + */ - // Indicates whether the stream has finished destroying. - this.closed = false + className: function() { + var tok = this.scan(/^\.([_a-z0-9\-]*[_a-z][_a-z0-9\-]*)/i, 'class'); + if (tok) { + this.tokens.push(tok); + this.incrementColumn(tok.val.length); + this.tokEnd(tok); + return true; + } + if (/^\.[_a-z0-9\-]+/i.test(this.input)) { + this.error( + 'INVALID_CLASS_NAME', + 'Class names must contain at least one letter or underscore.' + ); + } + if (/^\./.test(this.input)) { + this.error( + 'INVALID_CLASS_NAME', + '"' + + /.[^ \t\(\#\.\:]*/.exec(this.input.substr(1))[0] + + '" is not a valid class name. Class names can only contain "_", "-", a-z and 0-9, and must contain at least one of "_", or a-z' + ); + } + }, - // True if close has been emitted or would have been emitted - // depending on emitClose. - this.closeEmitted = false - this[kOnFinished] = [] -} -function resetBuffer(state) { - state.buffered = [] - state.bufferedIndex = 0 - state.allBuffers = true - state.allNoop = true -} -WritableState.prototype.getBuffer = function getBuffer() { - return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) -} -ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { - __proto__: null, - get() { - return this.buffered.length - this.bufferedIndex - } -}) -function Writable(options) { - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + /** + * Text. + */ + endInterpolation: function() { + if (this.interpolated && this.input[0] === ']') { + this.input = this.input.substr(1); + this.ended = true; + return true; + } + }, + addText: function(type, value, prefix, escaped) { + var tok; + if (value + prefix === '') return; + prefix = prefix || ''; + escaped = escaped || 0; + var indexOfEnd = this.interpolated ? value.indexOf(']') : -1; + var indexOfStart = this.interpolationAllowed ? value.indexOf('#[') : -1; + var indexOfEscaped = this.interpolationAllowed ? value.indexOf('\\#[') : -1; + var matchOfStringInterp = /(\\)?([#!]){((?:.|\n)*)$/.exec(value); + var indexOfStringInterp = + this.interpolationAllowed && matchOfStringInterp + ? matchOfStringInterp.index + : Infinity; - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. + if (indexOfEnd === -1) indexOfEnd = Infinity; + if (indexOfStart === -1) indexOfStart = Infinity; + if (indexOfEscaped === -1) indexOfEscaped = Infinity; - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5. - const isDuplex = this instanceof __nccwpck_require__(72613) - if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) - this._writableState = new WritableState(options, this, isDuplex) - if (options) { - if (typeof options.write === 'function') this._write = options.write - if (typeof options.writev === 'function') this._writev = options.writev - if (typeof options.destroy === 'function') this._destroy = options.destroy - if (typeof options.final === 'function') this._final = options.final - if (typeof options.construct === 'function') this._construct = options.construct - if (options.signal) addAbortSignal(options.signal, this) - } - Stream.call(this, options) - destroyImpl.construct(this, () => { - const state = this._writableState - if (!state.writing) { - clearBuffer(this, state) + if ( + indexOfEscaped !== Infinity && + indexOfEscaped < indexOfEnd && + indexOfEscaped < indexOfStart && + indexOfEscaped < indexOfStringInterp + ) { + prefix = prefix + value.substring(0, indexOfEscaped) + '#['; + return this.addText( + type, + value.substring(indexOfEscaped + 3), + prefix, + escaped + 1 + ); } - finishMaybe(this, state) - }) -} -ObjectDefineProperty(Writable, SymbolHasInstance, { - __proto__: null, - value: function (object) { - if (FunctionPrototypeSymbolHasInstance(this, object)) return true - if (this !== Writable) return false - return object && object._writableState instanceof WritableState - } -}) + if ( + indexOfStart !== Infinity && + indexOfStart < indexOfEnd && + indexOfStart < indexOfEscaped && + indexOfStart < indexOfStringInterp + ) { + tok = this.tok(type, prefix + value.substring(0, indexOfStart)); + this.incrementColumn(prefix.length + indexOfStart + escaped); + this.tokens.push(this.tokEnd(tok)); + tok = this.tok('start-pug-interpolation'); + this.incrementColumn(2); + this.tokens.push(this.tokEnd(tok)); + var child = new this.constructor(value.substr(indexOfStart + 2), { + filename: this.filename, + interpolated: true, + startingLine: this.lineno, + startingColumn: this.colno, + plugins: this.plugins, + }); + var interpolated; + try { + interpolated = child.getTokens(); + } catch (ex) { + if (ex.code && /^PUG:/.test(ex.code)) { + this.colno = ex.column; + this.error(ex.code.substr(4), ex.msg); + } + throw ex; + } + this.colno = child.colno; + this.tokens = this.tokens.concat(interpolated); + tok = this.tok('end-pug-interpolation'); + this.incrementColumn(1); + this.tokens.push(this.tokEnd(tok)); + this.addText(type, child.input); + return; + } + if ( + indexOfEnd !== Infinity && + indexOfEnd < indexOfStart && + indexOfEnd < indexOfEscaped && + indexOfEnd < indexOfStringInterp + ) { + if (prefix + value.substring(0, indexOfEnd)) { + this.addText(type, value.substring(0, indexOfEnd), prefix); + } + this.ended = true; + this.input = value.substr(value.indexOf(']') + 1) + this.input; + return; + } + if (indexOfStringInterp !== Infinity) { + if (matchOfStringInterp[1]) { + prefix = + prefix + + value.substring(0, indexOfStringInterp) + + matchOfStringInterp[2] + + '{'; + return this.addText( + type, + value.substring(indexOfStringInterp + 3), + prefix, + escaped + 1 + ); + } + var before = value.substr(0, indexOfStringInterp); + if (prefix || before) { + before = prefix + before; + tok = this.tok(type, before); + this.incrementColumn(before.length + escaped); + this.tokens.push(this.tokEnd(tok)); + } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()) -} -function _write(stream, chunk, encoding, cb) { - const state = stream._writableState - if (typeof encoding === 'function') { - cb = encoding - encoding = state.defaultEncoding - } else { - if (!encoding) encoding = state.defaultEncoding - else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) - if (typeof cb !== 'function') cb = nop - } - if (chunk === null) { - throw new ERR_STREAM_NULL_VALUES() - } else if (!state.objectMode) { - if (typeof chunk === 'string') { - if (state.decodeStrings !== false) { - chunk = Buffer.from(chunk, encoding) - encoding = 'buffer' + var rest = matchOfStringInterp[3]; + var range; + tok = this.tok('interpolated-code'); + this.incrementColumn(2); + try { + range = characterParser.parseUntil(rest, '}'); + } catch (ex) { + if (ex.index !== undefined) { + this.incrementColumn(ex.index); + } + if (ex.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { + this.error( + 'NO_END_BRACKET', + 'End of line was reached with no closing bracket for interpolation.' + ); + } else if (ex.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { + this.error('BRACKET_MISMATCH', ex.message); + } else { + throw ex; + } } - } else if (chunk instanceof Buffer) { - encoding = 'buffer' - } else if (Stream._isUint8Array(chunk)) { - chunk = Stream._uint8ArrayToBuffer(chunk) - encoding = 'buffer' - } else { - throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + tok.mustEscape = matchOfStringInterp[2] === '#'; + tok.buffer = true; + tok.val = range.src; + this.assertExpression(range.src); + + if (range.end + 1 < rest.length) { + rest = rest.substr(range.end + 1); + this.incrementColumn(range.end + 1); + this.tokens.push(this.tokEnd(tok)); + this.addText(type, rest); + } else { + this.incrementColumn(rest.length); + this.tokens.push(this.tokEnd(tok)); + } + return; } - } - let err - if (state.ending) { - err = new ERR_STREAM_WRITE_AFTER_END() - } else if (state.destroyed) { - err = new ERR_STREAM_DESTROYED('write') - } - if (err) { - process.nextTick(cb, err) - errorOrDestroy(stream, err, true) - return err - } - state.pendingcb++ - return writeOrBuffer(stream, state, chunk, encoding, cb) -} -Writable.prototype.write = function (chunk, encoding, cb) { - return _write(this, chunk, encoding, cb) === true -} -Writable.prototype.cork = function () { - this._writableState.corked++ -} -Writable.prototype.uncork = function () { - const state = this._writableState - if (state.corked) { - state.corked-- - if (!state.writing) clearBuffer(this, state) - } -} -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding) - if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) - this._writableState.defaultEncoding = encoding - return this -} -// If we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, callback) { - const len = state.objectMode ? 1 : chunk.length - state.length += len + value = prefix + value; + tok = this.tok(type, value); + this.incrementColumn(value.length + escaped); + this.tokens.push(this.tokEnd(tok)); + }, - // stream._write resets state.length - const ret = state.length < state.highWaterMark - // We must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true - if (state.writing || state.corked || state.errored || !state.constructed) { - state.buffered.push({ - chunk, - encoding, - callback - }) - if (state.allBuffers && encoding !== 'buffer') { - state.allBuffers = false + text: function() { + var tok = + this.scan(/^(?:\| ?| )([^\n]+)/, 'text') || + this.scan(/^( )/, 'text') || + this.scan(/^\|( ?)/, 'text'); + if (tok) { + this.addText('text', tok.val); + return true; } - if (state.allNoop && callback !== nop) { - state.allNoop = false + }, + + textHtml: function() { + var tok = this.scan(/^(<[^\n]*)/, 'text-html'); + if (tok) { + this.addText('text-html', tok.val); + return true; } - } else { - state.writelen = len - state.writecb = callback - state.writing = true - state.sync = true - stream._write(chunk, encoding, state.onwrite) - state.sync = false - } + }, - // Return false if errored or destroyed in order to break - // any synchronous while(stream.write(data)) loops. - return ret && !state.errored && !state.destroyed -} -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len - state.writecb = cb - state.writing = true - state.sync = true - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')) - else if (writev) stream._writev(chunk, state.onwrite) - else stream._write(chunk, encoding, state.onwrite) - state.sync = false -} -function onwriteError(stream, state, er, cb) { - --state.pendingcb - cb(er) - // Ensure callbacks are invoked even when autoDestroy is - // not enabled. Passing `er` here doesn't make sense since - // it's related to one specific write, not to the buffered - // writes. - errorBuffer(state) - // This can emit error, but error must always follow cb. - errorOrDestroy(stream, er) -} -function onwrite(stream, er) { - const state = stream._writableState - const sync = state.sync - const cb = state.writecb - if (typeof cb !== 'function') { - errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()) - return - } - state.writing = false - state.writecb = null - state.length -= state.writelen - state.writelen = 0 - if (er) { - // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 - er.stack // eslint-disable-line no-unused-expressions + /** + * Dot. + */ - if (!state.errored) { - state.errored = er + dot: function() { + var tok; + if ((tok = this.scanEndOfLine(/^\./, 'dot'))) { + this.tokens.push(this.tokEnd(tok)); + this.callLexerFunction('pipelessText'); + return true; } + }, - // In case of duplex streams we need to notify the readable side of the - // error. - if (stream._readableState && !stream._readableState.errored) { - stream._readableState.errored = er - } - if (sync) { - process.nextTick(onwriteError, stream, state, er, cb) - } else { - onwriteError(stream, state, er, cb) + /** + * Extends. + */ + + extends: function() { + var tok = this.scan(/^extends?(?= |$|\n)/, 'extends'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + if (!this.callLexerFunction('path')) { + this.error('NO_EXTENDS_PATH', 'missing path for extends'); + } + return true; } - } else { - if (state.buffered.length > state.bufferedIndex) { - clearBuffer(stream, state) + if (this.scan(/^extends?\b/)) { + this.error('MALFORMED_EXTENDS', 'malformed extends'); } - if (sync) { - // It is a common case that the callback passed to .write() is always - // the same. In that case, we do not schedule a new nextTick(), but - // rather just increase a counter, to improve performance and avoid - // memory allocations. - if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { - state.afterWriteTickInfo.count++ - } else { - state.afterWriteTickInfo = { - count: 1, - cb, - stream, - state - } - process.nextTick(afterWriteTick, state.afterWriteTickInfo) + }, + + /** + * Block prepend. + */ + + prepend: function() { + var captures; + if ((captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input))) { + var name = captures[1].trim(); + var comment = ''; + if (name.indexOf('//') !== -1) { + comment = + '//' + + name + .split('//') + .slice(1) + .join('//'); + name = name.split('//')[0].trim(); } - } else { - afterWrite(stream, state, 1, cb) + if (!name) return; + var tok = this.tok('block', name); + var len = captures[0].length - comment.length; + while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; + this.incrementColumn(len); + tok.mode = 'prepend'; + this.tokens.push(this.tokEnd(tok)); + this.consume(captures[0].length - comment.length); + this.incrementColumn(captures[0].length - comment.length - len); + return true; } - } -} -function afterWriteTick({ stream, state, count, cb }) { - state.afterWriteTickInfo = null - return afterWrite(stream, state, count, cb) -} -function afterWrite(stream, state, count, cb) { - const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain - if (needDrain) { - state.needDrain = false - stream.emit('drain') - } - while (count-- > 0) { - state.pendingcb-- - cb() - } - if (state.destroyed) { - errorBuffer(state) - } - finishMaybe(stream, state) -} + }, -// If there's something in the buffer waiting, then invoke callbacks. -function errorBuffer(state) { - if (state.writing) { - return - } - for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { - var _state$errored - const { chunk, callback } = state.buffered[n] - const len = state.objectMode ? 1 : chunk.length - state.length -= len - callback( - (_state$errored = state.errored) !== null && _state$errored !== undefined - ? _state$errored - : new ERR_STREAM_DESTROYED('write') - ) - } - const onfinishCallbacks = state[kOnFinished].splice(0) - for (let i = 0; i < onfinishCallbacks.length; i++) { - var _state$errored2 - onfinishCallbacks[i]( - (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined - ? _state$errored2 - : new ERR_STREAM_DESTROYED('end') - ) - } - resetBuffer(state) -} + /** + * Block append. + */ -// If there's something in the buffer waiting, then process it. -function clearBuffer(stream, state) { - if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { - return - } - const { buffered, bufferedIndex, objectMode } = state - const bufferedLength = buffered.length - bufferedIndex - if (!bufferedLength) { - return - } - let i = bufferedIndex - state.bufferProcessing = true - if (bufferedLength > 1 && stream._writev) { - state.pendingcb -= bufferedLength - 1 - const callback = state.allNoop - ? nop - : (err) => { - for (let n = i; n < buffered.length; ++n) { - buffered[n].callback(err) - } - } - // Make a copy of `buffered` if it's going to be used by `callback` above, - // since `doWrite` will mutate the array. - const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i) - chunks.allBuffers = state.allBuffers - doWrite(stream, state, true, state.length, chunks, '', callback) - resetBuffer(state) - } else { - do { - const { chunk, encoding, callback } = buffered[i] - buffered[i++] = null - const len = objectMode ? 1 : chunk.length - doWrite(stream, state, false, len, chunk, encoding, callback) - } while (i < buffered.length && !state.writing) - if (i === buffered.length) { - resetBuffer(state) - } else if (i > 256) { - buffered.splice(0, i) - state.bufferedIndex = 0 - } else { - state.bufferedIndex = i + append: function() { + var captures; + if ((captures = /^(?:block +)?append +([^\n]+)/.exec(this.input))) { + var name = captures[1].trim(); + var comment = ''; + if (name.indexOf('//') !== -1) { + comment = + '//' + + name + .split('//') + .slice(1) + .join('//'); + name = name.split('//')[0].trim(); + } + if (!name) return; + var tok = this.tok('block', name); + var len = captures[0].length - comment.length; + while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; + this.incrementColumn(len); + tok.mode = 'append'; + this.tokens.push(this.tokEnd(tok)); + this.consume(captures[0].length - comment.length); + this.incrementColumn(captures[0].length - comment.length - len); + return true; } - } - state.bufferProcessing = false -} -Writable.prototype._write = function (chunk, encoding, cb) { - if (this._writev) { - this._writev( - [ - { - chunk, - encoding - } - ], - cb - ) - } else { - throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') - } -} -Writable.prototype._writev = null -Writable.prototype.end = function (chunk, encoding, cb) { - const state = this._writableState - if (typeof chunk === 'function') { - cb = chunk - chunk = null - encoding = null - } else if (typeof encoding === 'function') { - cb = encoding - encoding = null - } - let err - if (chunk !== null && chunk !== undefined) { - const ret = _write(this, chunk, encoding) - if (ret instanceof Error) { - err = ret + }, + + /** + * Block. + */ + + block: function() { + var captures; + if ((captures = /^block +([^\n]+)/.exec(this.input))) { + var name = captures[1].trim(); + var comment = ''; + if (name.indexOf('//') !== -1) { + comment = + '//' + + name + .split('//') + .slice(1) + .join('//'); + name = name.split('//')[0].trim(); + } + if (!name) return; + var tok = this.tok('block', name); + var len = captures[0].length - comment.length; + while (this.whitespaceRe.test(this.input.charAt(len - 1))) len--; + this.incrementColumn(len); + tok.mode = 'replace'; + this.tokens.push(this.tokEnd(tok)); + this.consume(captures[0].length - comment.length); + this.incrementColumn(captures[0].length - comment.length - len); + return true; } - } + }, - // .end() fully uncorks. - if (state.corked) { - state.corked = 1 - this.uncork() - } - if (err) { - // Do nothing... - } else if (!state.errored && !state.ending) { - // This is forgiving in terms of unnecessary calls to end() and can hide - // logic errors. However, usually such errors are harmless and causing a - // hard error can be disproportionately destructive. It is not always - // trivial for the user to determine whether end() needs to be called - // or not. + /** + * Mixin Block. + */ - state.ending = true - finishMaybe(this, state, true) - state.ended = true - } else if (state.finished) { - err = new ERR_STREAM_ALREADY_FINISHED('end') - } else if (state.destroyed) { - err = new ERR_STREAM_DESTROYED('end') - } - if (typeof cb === 'function') { - if (err || state.finished) { - process.nextTick(cb, err) - } else { - state[kOnFinished].push(cb) + mixinBlock: function() { + var tok; + if ((tok = this.scanEndOfLine(/^block/, 'mixin-block'))) { + this.tokens.push(this.tokEnd(tok)); + return true; } - } - return this -} -function needFinish(state) { - return ( - state.ending && - !state.destroyed && - state.constructed && - state.length === 0 && - !state.errored && - state.buffered.length === 0 && - !state.finished && - !state.writing && - !state.errorEmitted && - !state.closeEmitted - ) -} -function callFinal(stream, state) { - let called = false - function onFinish(err) { - if (called) { - errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()) - return + }, + + /** + * Yield. + */ + + yield: function() { + var tok = this.scanEndOfLine(/^yield/, 'yield'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + return true; } - called = true - state.pendingcb-- - if (err) { - const onfinishCallbacks = state[kOnFinished].splice(0) - for (let i = 0; i < onfinishCallbacks.length; i++) { - onfinishCallbacks[i](err) + }, + + /** + * Include. + */ + + include: function() { + var tok = this.scan(/^include(?=:| |$|\n)/, 'include'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + while (this.callLexerFunction('filter', {inInclude: true})); + if (!this.callLexerFunction('path')) { + if (/^[^ \n]+/.test(this.input)) { + // if there is more text + this.fail(); + } else { + // if not + this.error('NO_INCLUDE_PATH', 'missing path for include'); + } } - errorOrDestroy(stream, err, state.sync) - } else if (needFinish(state)) { - state.prefinished = true - stream.emit('prefinish') - // Backwards compat. Don't check state.sync here. - // Some streams assume 'finish' will be emitted - // asynchronously relative to _final callback. - state.pendingcb++ - process.nextTick(finish, stream, state) + return true; } - } - state.sync = true - state.pendingcb++ - try { - stream._final(onFinish) - } catch (err) { - onFinish(err) - } - state.sync = false -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.finalCalled = true - callFinal(stream, state) - } else { - state.prefinished = true - stream.emit('prefinish') + if (this.scan(/^include\b/)) { + this.error('MALFORMED_INCLUDE', 'malformed include'); } - } -} -function finishMaybe(stream, state, sync) { - if (needFinish(state)) { - prefinish(stream, state) - if (state.pendingcb === 0) { - if (sync) { - state.pendingcb++ - process.nextTick( - (stream, state) => { - if (needFinish(state)) { - finish(stream, state) - } else { - state.pendingcb-- - } - }, - stream, - state - ) - } else if (needFinish(state)) { - state.pendingcb++ - finish(stream, state) - } + }, + + /** + * Path + */ + + path: function() { + var tok = this.scanEndOfLine(/^ ([^\n]+)/, 'path'); + if (tok && (tok.val = tok.val.trim())) { + this.tokens.push(this.tokEnd(tok)); + return true; } - } -} -function finish(stream, state) { - state.pendingcb-- - state.finished = true - const onfinishCallbacks = state[kOnFinished].splice(0) - for (let i = 0; i < onfinishCallbacks.length; i++) { - onfinishCallbacks[i]() - } - stream.emit('finish') - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well. - const rState = stream._readableState - const autoDestroy = - !rState || - (rState.autoDestroy && - // We don't expect the readable to ever 'end' - // if readable is explicitly set to false. - (rState.endEmitted || rState.readable === false)) - if (autoDestroy) { - stream.destroy() + }, + + /** + * Case. + */ + + case: function() { + var tok = this.scanEndOfLine(/^case +([^\n]+)/, 'case'); + if (tok) { + this.incrementColumn(-tok.val.length); + this.assertExpression(tok.val); + this.incrementColumn(tok.val.length); + this.tokens.push(this.tokEnd(tok)); + return true; } - } -} -ObjectDefineProperties(Writable.prototype, { - closed: { - __proto__: null, - get() { - return this._writableState ? this._writableState.closed : false + if (this.scan(/^case\b/)) { + this.error('NO_CASE_EXPRESSION', 'missing expression for case'); } }, - destroyed: { - __proto__: null, - get() { - return this._writableState ? this._writableState.destroyed : false - }, - set(value) { - // Backward compatibility, the user is explicitly managing destroyed. - if (this._writableState) { - this._writableState.destroyed = value + + /** + * When. + */ + + when: function() { + var tok = this.scanEndOfLine(/^when +([^:\n]+)/, 'when'); + if (tok) { + var parser = characterParser(tok.val); + while (parser.isNesting() || parser.isString()) { + var rest = /:([^:\n]+)/.exec(this.input); + if (!rest) break; + + tok.val += rest[0]; + this.consume(rest[0].length); + this.incrementColumn(rest[0].length); + parser = characterParser(tok.val); } + + this.incrementColumn(-tok.val.length); + this.assertExpression(tok.val); + this.incrementColumn(tok.val.length); + this.tokens.push(this.tokEnd(tok)); + return true; } - }, - writable: { - __proto__: null, - get() { - const w = this._writableState - // w.writable === false means that this is part of a Duplex stream - // where the writable side was disabled upon construction. - // Compat. The user might manually disable writable side through - // deprecated setter. - return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended - }, - set(val) { - // Backwards compatible. - if (this._writableState) { - this._writableState.writable = !!val - } + if (this.scan(/^when\b/)) { + this.error('NO_WHEN_EXPRESSION', 'missing expression for when'); } }, - writableFinished: { - __proto__: null, - get() { - return this._writableState ? this._writableState.finished : false + + /** + * Default. + */ + + default: function() { + var tok = this.scanEndOfLine(/^default/, 'default'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + return true; } - }, - writableObjectMode: { - __proto__: null, - get() { - return this._writableState ? this._writableState.objectMode : false + if (this.scan(/^default\b/)) { + this.error( + 'DEFAULT_WITH_EXPRESSION', + 'default should not have an expression' + ); } }, - writableBuffer: { - __proto__: null, - get() { - return this._writableState && this._writableState.getBuffer() + + /** + * Call mixin. + */ + + call: function() { + var tok, captures, increment; + if ((captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input))) { + // try to consume simple or interpolated call + if (captures[3]) { + // simple call + increment = captures[0].length; + this.consume(increment); + tok = this.tok('call', captures[3]); + } else { + // interpolated call + var match = this.bracketExpression(2 + captures[1].length); + increment = match.end + 1; + this.consume(increment); + this.assertExpression(match.src); + tok = this.tok('call', '#{' + match.src + '}'); + } + + this.incrementColumn(increment); + + tok.args = null; + // Check for args (not attributes) + if ((captures = /^ *\(/.exec(this.input))) { + var range = this.bracketExpression(captures[0].length - 1); + if (!/^\s*[-\w]+ *=/.test(range.src)) { + // not attributes + this.incrementColumn(1); + this.consume(range.end + 1); + tok.args = range.src; + this.assertExpression('[' + tok.args + ']'); + for (var i = 0; i <= tok.args.length; i++) { + if (tok.args[i] === '\n') { + this.incrementLine(1); + } else { + this.incrementColumn(1); + } + } + } + } + this.tokens.push(this.tokEnd(tok)); + return true; } }, - writableEnded: { - __proto__: null, - get() { - return this._writableState ? this._writableState.ending : false + + /** + * Mixin. + */ + + mixin: function() { + var captures; + if ((captures = /^mixin +([-\w]+)(?: *\((.*)\))? */.exec(this.input))) { + this.consume(captures[0].length); + var tok = this.tok('mixin', captures[1]); + tok.args = captures[2] || null; + this.incrementColumn(captures[0].length); + this.tokens.push(this.tokEnd(tok)); + return true; } }, - writableNeedDrain: { - __proto__: null, - get() { - const wState = this._writableState - if (!wState) return false - return !wState.destroyed && !wState.ending && wState.needDrain + + /** + * Conditional. + */ + + conditional: function() { + var captures; + if ((captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input))) { + this.consume(captures[0].length); + var type = captures[1].replace(/ /g, '-'); + var js = captures[2] && captures[2].trim(); + // type can be "if", "else-if" and "else" + var tok = this.tok(type, js); + this.incrementColumn(captures[0].length - js.length); + + switch (type) { + case 'if': + case 'else-if': + this.assertExpression(js); + break; + case 'unless': + this.assertExpression(js); + tok.val = '!(' + js + ')'; + tok.type = 'if'; + break; + case 'else': + if (js) { + this.error( + 'ELSE_CONDITION', + '`else` cannot have a condition, perhaps you meant `else if`' + ); + } + break; + } + this.incrementColumn(js.length); + this.tokens.push(this.tokEnd(tok)); + return true; } }, - writableHighWaterMark: { - __proto__: null, - get() { - return this._writableState && this._writableState.highWaterMark + + /** + * While. + */ + + while: function() { + var captures, tok; + if ((captures = /^while +([^\n]+)/.exec(this.input))) { + this.consume(captures[0].length); + this.assertExpression(captures[1]); + tok = this.tok('while', captures[1]); + this.incrementColumn(captures[0].length); + this.tokens.push(this.tokEnd(tok)); + return true; } - }, - writableCorked: { - __proto__: null, - get() { - return this._writableState ? this._writableState.corked : 0 + if (this.scan(/^while\b/)) { + this.error('NO_WHILE_EXPRESSION', 'missing expression for while'); } }, - writableLength: { - __proto__: null, - get() { - return this._writableState && this._writableState.length + + /** + * Each. + */ + + each: function() { + var captures; + if ( + (captures = /^(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? * in *([^\n]+)/.exec( + this.input + )) + ) { + this.consume(captures[0].length); + var tok = this.tok('each', captures[1]); + tok.key = captures[2] || null; + this.incrementColumn(captures[0].length - captures[3].length); + this.assertExpression(captures[3]); + tok.code = captures[3]; + this.incrementColumn(captures[3].length); + this.tokens.push(this.tokEnd(tok)); + return true; + } + const name = /^each\b/.exec(this.input) ? 'each' : 'for'; + if (this.scan(/^(?:each|for)\b/)) { + this.error( + 'MALFORMED_EACH', + 'This `' + + name + + '` has a syntax error. `' + + name + + '` statements should be of the form: `' + + name + + ' VARIABLE_NAME of JS_EXPRESSION`' + ); + } + if ( + (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +in +([^\n]+)/.exec( + this.input + )) + ) { + this.error( + 'MALFORMED_EACH', + 'Pug each and for should no longer be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.' + ); } }, - errored: { - __proto__: null, - enumerable: false, - get() { - return this._writableState ? this._writableState.errored : null + + /** + * EachOf. + */ + + eachOf: function() { + var captures; + if ((captures = /^(?:each|for) (.*?) of *([^\n]+)/.exec(this.input))) { + this.consume(captures[0].length); + var tok = this.tok('eachOf', captures[1]); + tok.value = captures[1]; + this.incrementColumn(captures[0].length - captures[2].length); + this.assertExpression(captures[2]); + tok.code = captures[2]; + this.incrementColumn(captures[2].length); + this.tokens.push(this.tokEnd(tok)); + + if ( + !( + /^[a-zA-Z_$][\w$]*$/.test(tok.value.trim()) || + /^\[ *[a-zA-Z_$][\w$]* *\, *[a-zA-Z_$][\w$]* *\]$/.test( + tok.value.trim() + ) + ) + ) { + this.error( + 'MALFORMED_EACH_OF_LVAL', + 'The value variable for each must either be a valid identifier (e.g. `item`) or a pair of identifiers in square brackets (e.g. `[key, value]`).' + ); + } + + return true; + } + if ( + (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +of +([^\n]+)/.exec( + this.input + )) + ) { + this.error( + 'MALFORMED_EACH', + 'Pug each and for should not be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.' + ); } }, - writableAborted: { - __proto__: null, - enumerable: false, - get: function () { - return !!( - this._writableState.writable !== false && - (this._writableState.destroyed || this._writableState.errored) && - !this._writableState.finished - ) + + /** + * Code. + */ + + code: function() { + var captures; + if ((captures = /^(!?=|-)[ \t]*([^\n]+)/.exec(this.input))) { + var flags = captures[1]; + var code = captures[2]; + var shortened = 0; + if (this.interpolated) { + var parsed; + try { + parsed = characterParser.parseUntil(code, ']'); + } catch (err) { + if (err.index !== undefined) { + this.incrementColumn(captures[0].length - code.length + err.index); + } + if (err.code === 'CHARACTER_PARSER:END_OF_STRING_REACHED') { + this.error( + 'NO_END_BRACKET', + 'End of line was reached with no closing bracket for interpolation.' + ); + } else if (err.code === 'CHARACTER_PARSER:MISMATCHED_BRACKET') { + this.error('BRACKET_MISMATCH', err.message); + } else { + throw err; + } + } + shortened = code.length - parsed.end; + code = parsed.src; + } + var consumed = captures[0].length - shortened; + this.consume(consumed); + var tok = this.tok('code', code); + tok.mustEscape = flags.charAt(0) === '='; + tok.buffer = flags.charAt(0) === '=' || flags.charAt(1) === '='; + + // p #[!= abc] hey + // ^ original colno + // -------------- captures[0] + // -------- captures[2] + // ------ captures[0] - captures[2] + // ^ after colno + + // = abc + // ^ original colno + // ------- captures[0] + // --- captures[2] + // ---- captures[0] - captures[2] + // ^ after colno + this.incrementColumn(captures[0].length - captures[2].length); + if (tok.buffer) this.assertExpression(code); + this.tokens.push(tok); + + // p #[!= abc] hey + // ^ original colno + // ----- shortened + // --- code + // ^ after colno + + // = abc + // ^ original colno + // shortened + // --- code + // ^ after colno + this.incrementColumn(code.length); + this.tokEnd(tok); + return true; } - } -}) -const destroy = destroyImpl.destroy -Writable.prototype.destroy = function (err, cb) { - const state = this._writableState + }, - // Invoke pending callbacks. - if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { - process.nextTick(errorBuffer, state) - } - destroy.call(this, err, cb) - return this -} -Writable.prototype._undestroy = destroyImpl.undestroy -Writable.prototype._destroy = function (err, cb) { - cb(err) -} -Writable.prototype[EE.captureRejectionSymbol] = function (err) { - this.destroy(err) -} -let webStreamsAdapters + /** + * Block code. + */ + blockCode: function() { + var tok; + if ((tok = this.scanEndOfLine(/^-/, 'blockcode'))) { + this.tokens.push(this.tokEnd(tok)); + this.interpolationAllowed = false; + this.callLexerFunction('pipelessText'); + return true; + } + }, -// Lazy to avoid circular references -function lazyWebStreams() { - if (webStreamsAdapters === undefined) webStreamsAdapters = {} - return webStreamsAdapters -} -Writable.fromWeb = function (writableStream, options) { - return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) -} -Writable.toWeb = function (streamWritable) { - return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) -} + /** + * Attribute Name. + */ + attribute: function(str) { + var quote = ''; + var quoteRe = /['"]/; + var key = ''; + var i; + // consume all whitespace before the key + for (i = 0; i < str.length; i++) { + if (!this.whitespaceRe.test(str[i])) break; + if (str[i] === '\n') { + this.incrementLine(1); + } else { + this.incrementColumn(1); + } + } -/***/ }), + if (i === str.length) { + return ''; + } -/***/ 669: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var tok = this.tok('attribute'); -"use strict"; -/* eslint jsdoc/require-jsdoc: "error" */ + // quote? + if (quoteRe.test(str[i])) { + quote = str[i]; + this.incrementColumn(1); + i++; + } + // start looping through the key + for (; i < str.length; i++) { + if (quote) { + if (str[i] === quote) { + this.incrementColumn(1); + i++; + break; + } + } else { + if ( + this.whitespaceRe.test(str[i]) || + str[i] === '!' || + str[i] === '=' || + str[i] === ',' + ) { + break; + } + } + key += str[i]; -const { - ArrayIsArray, - ArrayPrototypeIncludes, - ArrayPrototypeJoin, - ArrayPrototypeMap, - NumberIsInteger, - NumberIsNaN, - NumberMAX_SAFE_INTEGER, - NumberMIN_SAFE_INTEGER, - NumberParseInt, - ObjectPrototypeHasOwnProperty, - RegExpPrototypeExec, - String, - StringPrototypeToUpperCase, - StringPrototypeTrim -} = __nccwpck_require__(89629) -const { - hideStackFrames, - codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } -} = __nccwpck_require__(80529) -const { normalizeEncoding } = __nccwpck_require__(46959) -const { isAsyncFunction, isArrayBufferView } = (__nccwpck_require__(46959).types) -const signals = {} + if (str[i] === '\n') { + this.incrementLine(1); + } else { + this.incrementColumn(1); + } + } -/** - * @param {*} value - * @returns {boolean} - */ -function isInt32(value) { - return value === (value | 0) -} + tok.name = key; -/** - * @param {*} value - * @returns {boolean} - */ -function isUint32(value) { - return value === value >>> 0 -} -const octalReg = /^[0-7]+$/ -const modeDesc = 'must be a 32-bit unsigned integer or an octal string' + var valueResponse = this.attributeValue(str.substr(i)); -/** - * Parse and validate values that will be converted into mode_t (the S_* - * constants). Only valid numbers and octal strings are allowed. They could be - * converted to 32-bit unsigned integers or non-negative signed integers in the - * C++ land, but any value higher than 0o777 will result in platform-specific - * behaviors. - * @param {*} value Values to be validated - * @param {string} name Name of the argument - * @param {number} [def] If specified, will be returned for invalid values - * @returns {number} - */ -function parseFileMode(value, name, def) { - if (typeof value === 'undefined') { - value = def - } - if (typeof value === 'string') { - if (RegExpPrototypeExec(octalReg, value) === null) { - throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) + if (valueResponse.val) { + tok.val = valueResponse.val; + tok.mustEscape = valueResponse.mustEscape; + } else { + // was a boolean attribute (ex: `input(disabled)`) + tok.val = true; + tok.mustEscape = true; } - value = NumberParseInt(value, 8) - } - validateUint32(value, name) - return value -} -/** - * @callback validateInteger - * @param {*} value - * @param {string} name - * @param {number} [min] - * @param {number} [max] - * @returns {asserts value is number} - */ + str = valueResponse.remainingSource; -/** @type {validateInteger} */ -const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { - if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) - if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) - if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) -}) + this.tokens.push(this.tokEnd(tok)); -/** - * @callback validateInt32 - * @param {*} value - * @param {string} name - * @param {number} [min] - * @param {number} [max] - * @returns {asserts value is number} - */ + for (i = 0; i < str.length; i++) { + if (!this.whitespaceRe.test(str[i])) { + break; + } + if (str[i] === '\n') { + this.incrementLine(1); + } else { + this.incrementColumn(1); + } + } -/** @type {validateInt32} */ -const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { - // The defaults for min and max correspond to the limits of 32-bit integers. - if (typeof value !== 'number') { - throw new ERR_INVALID_ARG_TYPE(name, 'number', value) - } - if (!NumberIsInteger(value)) { - throw new ERR_OUT_OF_RANGE(name, 'an integer', value) - } - if (value < min || value > max) { - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) - } -}) + if (str[i] === ',') { + this.incrementColumn(1); + i++; + } -/** - * @callback validateUint32 - * @param {*} value - * @param {string} name - * @param {number|boolean} [positive=false] - * @returns {asserts value is number} - */ + return str.substr(i); + }, -/** @type {validateUint32} */ -const validateUint32 = hideStackFrames((value, name, positive = false) => { - if (typeof value !== 'number') { - throw new ERR_INVALID_ARG_TYPE(name, 'number', value) - } - if (!NumberIsInteger(value)) { - throw new ERR_OUT_OF_RANGE(name, 'an integer', value) - } - const min = positive ? 1 : 0 - // 2 ** 32 === 4294967296 - const max = 4294967295 - if (value < min || value > max) { - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) - } -}) + /** + * Attribute Value. + */ + attributeValue: function(str) { + var quoteRe = /['"]/; + var val = ''; + var done, i, x; + var escapeAttr = true; + var state = characterParser.defaultState(); + var col = this.colno; + var line = this.lineno; -/** - * @callback validateString - * @param {*} value - * @param {string} name - * @returns {asserts value is string} - */ + // consume all whitespace before the equals sign + for (i = 0; i < str.length; i++) { + if (!this.whitespaceRe.test(str[i])) break; + if (str[i] === '\n') { + line++; + col = 1; + } else { + col++; + } + } -/** @type {validateString} */ -function validateString(value, name) { - if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) -} + if (i === str.length) { + return {remainingSource: str}; + } -/** - * @callback validateNumber - * @param {*} value - * @param {string} name - * @param {number} [min] - * @param {number} [max] - * @returns {asserts value is number} - */ + if (str[i] === '!') { + escapeAttr = false; + col++; + i++; + if (str[i] !== '=') + this.error( + 'INVALID_KEY_CHARACTER', + 'Unexpected character ' + str[i] + ' expected `=`' + ); + } -/** @type {validateNumber} */ -function validateNumber(value, name, min = undefined, max) { - if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) - if ( - (min != null && value < min) || - (max != null && value > max) || - ((min != null || max != null) && NumberIsNaN(value)) - ) { - throw new ERR_OUT_OF_RANGE( - name, - `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, - value - ) - } -} + if (str[i] !== '=') { + // check for anti-pattern `div("foo"bar)` + if (i === 0 && str && !this.whitespaceRe.test(str[0]) && str[0] !== ',') { + this.error( + 'INVALID_KEY_CHARACTER', + 'Unexpected character ' + str[0] + ' expected `=`' + ); + } else { + return {remainingSource: str}; + } + } -/** - * @callback validateOneOf - * @template T - * @param {T} value - * @param {string} name - * @param {T[]} oneOf - */ + this.lineno = line; + this.colno = col + 1; + i++; -/** @type {validateOneOf} */ -const validateOneOf = hideStackFrames((value, name, oneOf) => { - if (!ArrayPrototypeIncludes(oneOf, value)) { - const allowed = ArrayPrototypeJoin( - ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), - ', ' - ) - const reason = 'must be one of: ' + allowed - throw new ERR_INVALID_ARG_VALUE(name, value, reason) - } -}) + // consume all whitespace before the value + for (; i < str.length; i++) { + if (!this.whitespaceRe.test(str[i])) break; + if (str[i] === '\n') { + this.incrementLine(1); + } else { + this.incrementColumn(1); + } + } -/** - * @callback validateBoolean - * @param {*} value - * @param {string} name - * @returns {asserts value is boolean} - */ + line = this.lineno; + col = this.colno; -/** @type {validateBoolean} */ -function validateBoolean(value, name) { - if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) -} + // start looping through the value + for (; i < str.length; i++) { + // if the character is in a string or in parentheses/brackets/braces + if (!(state.isNesting() || state.isString())) { + if (this.whitespaceRe.test(str[i])) { + done = false; -/** - * @param {any} options - * @param {string} key - * @param {boolean} defaultValue - * @returns {boolean} - */ -function getOwnPropertyValueOrDefault(options, key, defaultValue) { - return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] -} + // find the first non-whitespace character + for (x = i; x < str.length; x++) { + if (!this.whitespaceRe.test(str[x])) { + // if it is a JavaScript punctuator, then assume that it is + // a part of the value + const isNotPunctuator = !characterParser.isPunctuator(str[x]); + const isQuote = quoteRe.test(str[x]); + const isColon = str[x] === ':'; + const isSpreadOperator = + str[x] + str[x + 1] + str[x + 2] === '...'; + if ( + (isNotPunctuator || isQuote || isColon || isSpreadOperator) && + this.assertExpression(val, true) + ) { + done = true; + } + break; + } + } -/** - * @callback validateObject - * @param {*} value - * @param {string} name - * @param {{ - * allowArray?: boolean, - * allowFunction?: boolean, - * nullable?: boolean - * }} [options] - */ + // if everything else is whitespace, return now so last attribute + // does not include trailing whitespace + if (done || x === str.length) { + break; + } + } -/** @type {validateObject} */ -const validateObject = hideStackFrames((value, name, options = null) => { - const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false) - const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false) - const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false) - if ( - (!nullable && value === null) || - (!allowArray && ArrayIsArray(value)) || - (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) - ) { - throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) - } -}) + // if there's no whitespace and the character is not ',', the + // attribute did not end. + if (str[i] === ',' && this.assertExpression(val, true)) { + break; + } + } + + state = characterParser.parseChar(str[i], state); + val += str[i]; -/** - * @callback validateDictionary - We are using the Web IDL Standard definition - * of "dictionary" here, which means any value - * whose Type is either Undefined, Null, or - * Object (which includes functions). - * @param {*} value - * @param {string} name - * @see https://webidl.spec.whatwg.org/#es-dictionary - * @see https://tc39.es/ecma262/#table-typeof-operator-results - */ + if (str[i] === '\n') { + line++; + col = 1; + } else { + col++; + } + } -/** @type {validateDictionary} */ -const validateDictionary = hideStackFrames((value, name) => { - if (value != null && typeof value !== 'object' && typeof value !== 'function') { - throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) - } -}) + this.assertExpression(val); -/** - * @callback validateArray - * @param {*} value - * @param {string} name - * @param {number} [minLength] - * @returns {asserts value is any[]} - */ + this.lineno = line; + this.colno = col; -/** @type {validateArray} */ -const validateArray = hideStackFrames((value, name, minLength = 0) => { - if (!ArrayIsArray(value)) { - throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) - } - if (value.length < minLength) { - const reason = `must be longer than ${minLength}` - throw new ERR_INVALID_ARG_VALUE(name, value, reason) - } -}) + return {val: val, mustEscape: escapeAttr, remainingSource: str.substr(i)}; + }, -/** - * @callback validateStringArray - * @param {*} value - * @param {string} name - * @returns {asserts value is string[]} - */ + /** + * Attributes. + */ -/** @type {validateStringArray} */ -function validateStringArray(value, name) { - validateArray(value, name) - for (let i = 0; i < value.length; i++) { - validateString(value[i], `${name}[${i}]`) - } -} + attrs: function() { + var tok; -/** - * @callback validateBooleanArray - * @param {*} value - * @param {string} name - * @returns {asserts value is boolean[]} - */ + if ('(' == this.input.charAt(0)) { + tok = this.tok('start-attributes'); + var index = this.bracketExpression().end; + var str = this.input.substr(1, index - 1); -/** @type {validateBooleanArray} */ -function validateBooleanArray(value, name) { - validateArray(value, name) - for (let i = 0; i < value.length; i++) { - validateBoolean(value[i], `${name}[${i}]`) - } -} + this.incrementColumn(1); + this.tokens.push(this.tokEnd(tok)); + this.assertNestingCorrect(str); + this.consume(index + 1); -/** - * @callback validateAbortSignalArray - * @param {*} value - * @param {string} name - * @returns {asserts value is AbortSignal[]} - */ + while (str) { + str = this.attribute(str); + } -/** @type {validateAbortSignalArray} */ -function validateAbortSignalArray(value, name) { - validateArray(value, name) - for (let i = 0; i < value.length; i++) { - const signal = value[i] - const indexedName = `${name}[${i}]` - if (signal == null) { - throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal) + tok = this.tok('end-attributes'); + this.incrementColumn(1); + this.tokens.push(this.tokEnd(tok)); + return true; } - validateAbortSignal(signal, indexedName) - } -} + }, -/** - * @param {*} signal - * @param {string} [name='signal'] - * @returns {asserts signal is keyof signals} - */ -function validateSignalName(signal, name = 'signal') { - validateString(signal, name) - if (signals[signal] === undefined) { - if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { - throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)') + /** + * &attributes block + */ + attributesBlock: function() { + if (/^&attributes\b/.test(this.input)) { + var consumed = 11; + this.consume(consumed); + var tok = this.tok('&attributes'); + this.incrementColumn(consumed); + var args = this.bracketExpression(); + consumed = args.end + 1; + this.consume(consumed); + tok.val = args.src; + this.incrementColumn(consumed); + this.tokens.push(this.tokEnd(tok)); + return true; } - throw new ERR_UNKNOWN_SIGNAL(signal) - } -} + }, -/** - * @callback validateBuffer - * @param {*} buffer - * @param {string} [name='buffer'] - * @returns {asserts buffer is ArrayBufferView} - */ + /** + * Indent | Outdent | Newline. + */ -/** @type {validateBuffer} */ -const validateBuffer = hideStackFrames((buffer, name = 'buffer') => { - if (!isArrayBufferView(buffer)) { - throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) - } -}) + indent: function() { + var captures = this.scanIndentation(); + var tok; -/** - * @param {string} data - * @param {string} encoding - */ -function validateEncoding(data, encoding) { - const normalizedEncoding = normalizeEncoding(encoding) - const length = data.length - if (normalizedEncoding === 'hex' && length % 2 !== 0) { - throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) - } -} + if (captures) { + var indents = captures[1].length; -/** - * Check that the port number is not NaN when coerced to a number, - * is an integer and that it falls within the legal range of port numbers. - * @param {*} port - * @param {string} [name='Port'] - * @param {boolean} [allowZero=true] - * @returns {number} - */ -function validatePort(port, name = 'Port', allowZero = true) { - if ( - (typeof port !== 'number' && typeof port !== 'string') || - (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || - +port !== +port >>> 0 || - port > 0xffff || - (port === 0 && !allowZero) - ) { - throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) - } - return port | 0 -} + this.incrementLine(1); + this.consume(indents + 1); -/** - * @callback validateAbortSignal - * @param {*} signal - * @param {string} name - */ + if (' ' == this.input[0] || '\t' == this.input[0]) { + this.error( + 'INVALID_INDENTATION', + 'Invalid indentation, you can use tabs or spaces but not both' + ); + } -/** @type {validateAbortSignal} */ -const validateAbortSignal = hideStackFrames((signal, name) => { - if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { - throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) - } -}) + // blank line + if ('\n' == this.input[0]) { + this.interpolationAllowed = true; + return this.tokEnd(this.tok('newline')); + } -/** - * @callback validateFunction - * @param {*} value - * @param {string} name - * @returns {asserts value is Function} - */ + // outdent + if (indents < this.indentStack[0]) { + var outdent_count = 0; + while (this.indentStack[0] > indents) { + if (this.indentStack[1] < indents) { + this.error( + 'INCONSISTENT_INDENTATION', + 'Inconsistent indentation. Expecting either ' + + this.indentStack[1] + + ' or ' + + this.indentStack[0] + + ' spaces/tabs.' + ); + } + outdent_count++; + this.indentStack.shift(); + } + while (outdent_count--) { + this.colno = 1; + tok = this.tok('outdent'); + this.colno = this.indentStack[0] + 1; + this.tokens.push(this.tokEnd(tok)); + } + // indent + } else if (indents && indents != this.indentStack[0]) { + tok = this.tok('indent', indents); + this.colno = 1 + indents; + this.tokens.push(this.tokEnd(tok)); + this.indentStack.unshift(indents); + // newline + } else { + tok = this.tok('newline'); + this.colno = 1 + Math.min(this.indentStack[0] || 0, indents); + this.tokens.push(this.tokEnd(tok)); + } -/** @type {validateFunction} */ -const validateFunction = hideStackFrames((value, name) => { - if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) -}) + this.interpolationAllowed = true; + return true; + } + }, -/** - * @callback validatePlainFunction - * @param {*} value - * @param {string} name - * @returns {asserts value is Function} - */ + pipelessText: function pipelessText(indents) { + while (this.callLexerFunction('blank')); -/** @type {validatePlainFunction} */ -const validatePlainFunction = hideStackFrames((value, name) => { - if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) -}) + var captures = this.scanIndentation(); -/** - * @callback validateUndefined - * @param {*} value - * @param {string} name - * @returns {asserts value is undefined} - */ + indents = indents || (captures && captures[1].length); + if (indents > this.indentStack[0]) { + this.tokens.push(this.tokEnd(this.tok('start-pipeless-text'))); + var tokens = []; + var token_indent = []; + var isMatch; + // Index in this.input. Can't use this.consume because we might need to + // retry lexing the block. + var stringPtr = 0; + do { + // text has `\n` as a prefix + var i = this.input.substr(stringPtr + 1).indexOf('\n'); + if (-1 == i) i = this.input.length - stringPtr - 1; + var str = this.input.substr(stringPtr + 1, i); + var lineCaptures = this.indentRe.exec('\n' + str); + var lineIndents = lineCaptures && lineCaptures[1].length; + isMatch = lineIndents >= indents; + token_indent.push(isMatch); + isMatch = isMatch || !str.trim(); + if (isMatch) { + // consume test along with `\n` prefix if match + stringPtr += str.length + 1; + tokens.push(str.substr(indents)); + } else if (lineIndents > this.indentStack[0]) { + // line is indented less than the first line but is still indented + // need to retry lexing the text block + this.tokens.pop(); + return pipelessText.call(this, lineCaptures[1].length); + } + } while (this.input.length - stringPtr && isMatch); + this.consume(stringPtr); + while (this.input.length === 0 && tokens[tokens.length - 1] === '') + tokens.pop(); + tokens.forEach( + function(token, i) { + var tok; + this.incrementLine(1); + if (i !== 0) tok = this.tok('newline'); + if (token_indent[i]) this.incrementColumn(indents); + if (tok) this.tokens.push(this.tokEnd(tok)); + this.addText('text', token); + }.bind(this) + ); + this.tokens.push(this.tokEnd(this.tok('end-pipeless-text'))); + return true; + } + }, -/** @type {validateUndefined} */ -const validateUndefined = hideStackFrames((value, name) => { - if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) -}) + /** + * Slash. + */ -/** - * @template T - * @param {T} value - * @param {string} name - * @param {T[]} union - */ -function validateUnion(value, name, union) { - if (!ArrayPrototypeIncludes(union, value)) { - throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) - } -} + slash: function() { + var tok = this.scan(/^\//, 'slash'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + return true; + } + }, -/* - The rules for the Link header field are described here: - https://www.rfc-editor.org/rfc/rfc8288.html#section-3 + /** + * ':' + */ - This regex validates any string surrounded by angle brackets - (not necessarily a valid URI reference) followed by zero or more - link-params separated by semicolons. -*/ -const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/ + colon: function() { + var tok = this.scan(/^: +/, ':'); + if (tok) { + this.tokens.push(this.tokEnd(tok)); + return true; + } + }, -/** - * @param {any} value - * @param {string} name - */ -function validateLinkHeaderFormat(value, name) { - if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { - throw new ERR_INVALID_ARG_VALUE( - name, - value, - 'must be an array or string of format "; rel=preload; as=style"' - ) - } -} + fail: function() { + this.error( + 'UNEXPECTED_TEXT', + 'unexpected text "' + this.input.substr(0, 5) + '"' + ); + }, -/** - * @param {any} hints - * @return {string} - */ -function validateLinkHeaderValue(hints) { - if (typeof hints === 'string') { - validateLinkHeaderFormat(hints, 'hints') - return hints - } else if (ArrayIsArray(hints)) { - const hintsLength = hints.length - let result = '' - if (hintsLength === 0) { - return result + callLexerFunction: function(func) { + var rest = []; + for (var i = 1; i < arguments.length; i++) { + rest.push(arguments[i]); } - for (let i = 0; i < hintsLength; i++) { - const link = hints[i] - validateLinkHeaderFormat(link, 'hints') - result += link - if (i !== hintsLength - 1) { - result += ', ' + var pluginArgs = [this].concat(rest); + for (var i = 0; i < this.plugins.length; i++) { + var plugin = this.plugins[i]; + if (plugin[func] && plugin[func].apply(plugin, pluginArgs)) { + return true; } } - return result - } - throw new ERR_INVALID_ARG_VALUE( - 'hints', - hints, - 'must be an array or string of format "; rel=preload; as=style"' - ) -} -module.exports = { - isInt32, - isUint32, - parseFileMode, - validateArray, - validateStringArray, - validateBooleanArray, - validateAbortSignalArray, - validateBoolean, - validateBuffer, - validateDictionary, - validateEncoding, - validateFunction, - validateInt32, - validateInteger, - validateNumber, - validateObject, - validateOneOf, - validatePlainFunction, - validatePort, - validateSignalName, - validateString, - validateUint32, - validateUndefined, - validateUnion, - validateAbortSignal, - validateLinkHeaderValue -} + return this[func].apply(this, rest); + }, + /** + * Move to the next token + * + * @api private + */ -/***/ }), + advance: function() { + return ( + this.callLexerFunction('blank') || + this.callLexerFunction('eos') || + this.callLexerFunction('endInterpolation') || + this.callLexerFunction('yield') || + this.callLexerFunction('doctype') || + this.callLexerFunction('interpolation') || + this.callLexerFunction('case') || + this.callLexerFunction('when') || + this.callLexerFunction('default') || + this.callLexerFunction('extends') || + this.callLexerFunction('append') || + this.callLexerFunction('prepend') || + this.callLexerFunction('block') || + this.callLexerFunction('mixinBlock') || + this.callLexerFunction('include') || + this.callLexerFunction('mixin') || + this.callLexerFunction('call') || + this.callLexerFunction('conditional') || + this.callLexerFunction('eachOf') || + this.callLexerFunction('each') || + this.callLexerFunction('while') || + this.callLexerFunction('tag') || + this.callLexerFunction('filter') || + this.callLexerFunction('blockCode') || + this.callLexerFunction('code') || + this.callLexerFunction('id') || + this.callLexerFunction('dot') || + this.callLexerFunction('className') || + this.callLexerFunction('attrs') || + this.callLexerFunction('attributesBlock') || + this.callLexerFunction('indent') || + this.callLexerFunction('text') || + this.callLexerFunction('textHtml') || + this.callLexerFunction('comment') || + this.callLexerFunction('slash') || + this.callLexerFunction('colon') || + this.fail() + ); + }, -/***/ 80529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Return an array of tokens for the current file + * + * @returns {Array.} + * @api public + */ + getTokens: function() { + while (!this.ended) { + this.callLexerFunction('advance'); + } + return this.tokens; + }, +}; -"use strict"; +/***/ }), -const { format, inspect } = __nccwpck_require__(43075) -const { AggregateError: CustomAggregateError } = __nccwpck_require__(89629) +/***/ 63234: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - This file is a reduced and adapted version of the main lib/internal/errors.js file defined at +"use strict"; - https://github.com/nodejs/node/blob/main/lib/internal/errors.js - Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) - with the upstream file. -*/ +var assert = __nccwpck_require__(39491); +var walk = __nccwpck_require__(60283); -const AggregateError = globalThis.AggregateError || CustomAggregateError -const kIsNodeError = Symbol('kIsNodeError') -const kTypes = [ - 'string', - 'function', - 'number', - 'object', - // Accept 'Function' and 'Object' as alternative to the lower cased version. - 'Function', - 'Object', - 'boolean', - 'bigint', - 'symbol' -] -const classRegExp = /^([A-Z][a-z0-9]*)+$/ -const nodeInternalPrefix = '__node_internal_' -const codes = {} -function assert(value, message) { - if (!value) { - throw new codes.ERR_INTERNAL_ASSERTION(message) - } +function error() { + throw (__nccwpck_require__(11449).apply)(null, arguments); } -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = '' - let i = val.length - const start = val[0] === '-' ? 1 : 0 - for (; i >= start + 4; i -= 3) { - res = `_${val.slice(i - 3, i)}${res}` - } - return `${val.slice(0, i)}${res}` -} -function getMessage(key, msg, args) { - if (typeof msg === 'function') { - assert( - msg.length <= args.length, - // Default options do not count. - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` - ) - return msg(...args) - } - const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length +module.exports = link; +function link(ast) { assert( - expectedLength === args.length, - `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` - ) - if (args.length === 0) { - return msg - } - return format(msg, ...args) -} -function E(code, message, Base) { - if (!Base) { - Base = Error - } - class NodeError extends Base { - constructor(...args) { - super(getMessage(code, message, args)) - } - toString() { - return `${this.name} [${code}]: ${this.message}` + ast.type === 'Block', + 'The top level element should always be a block' + ); + var extendsNode = null; + if (ast.nodes.length) { + var hasExtends = ast.nodes[0].type === 'Extends'; + checkExtendPosition(ast, hasExtends); + if (hasExtends) { + extendsNode = ast.nodes.shift(); } } - Object.defineProperties(NodeError.prototype, { - name: { - value: Base.name, - writable: true, - enumerable: false, - configurable: true - }, - toString: { - value() { - return `${this.name} [${code}]: ${this.message}` - }, - writable: true, - enumerable: false, - configurable: true - } - }) - NodeError.prototype.code = code - NodeError.prototype[kIsNodeError] = true - codes[code] = NodeError -} -function hideStackFrames(fn) { - // We rename the functions that will be hidden to cut off the stacktrace - // at the outermost one - const hidden = nodeInternalPrefix + fn.name - Object.defineProperty(fn, 'name', { - value: hidden - }) - return fn -} -function aggregateTwoErrors(innerError, outerError) { - if (innerError && outerError && innerError !== outerError) { - if (Array.isArray(outerError.errors)) { - // If `outerError` is already an `AggregateError`. - outerError.errors.push(innerError) - return outerError - } - const err = new AggregateError([outerError, innerError], outerError.message) - err.code = outerError.code - return err + ast = applyIncludes(ast); + ast.declaredBlocks = findDeclaredBlocks(ast); + if (extendsNode) { + var mixins = []; + var expectedBlocks = []; + ast.nodes.forEach(function addNode(node) { + if (node.type === 'NamedBlock') { + expectedBlocks.push(node); + } else if (node.type === 'Block') { + node.nodes.forEach(addNode); + } else if (node.type === 'Mixin' && node.call === false) { + mixins.push(node); + } else { + error( + 'UNEXPECTED_NODES_IN_EXTENDING_ROOT', + 'Only named blocks and mixins can appear at the top level of an extending template', + node + ); + } + }); + var parent = link(extendsNode.file.ast); + extend(parent.declaredBlocks, ast); + var foundBlockNames = []; + walk(parent, function(node) { + if (node.type === 'NamedBlock') { + foundBlockNames.push(node.name); + } + }); + expectedBlocks.forEach(function(expectedBlock) { + if (foundBlockNames.indexOf(expectedBlock.name) === -1) { + error( + 'UNEXPECTED_BLOCK', + 'Unexpected block ' + expectedBlock.name, + expectedBlock + ); + } + }); + Object.keys(ast.declaredBlocks).forEach(function(name) { + parent.declaredBlocks[name] = ast.declaredBlocks[name]; + }); + parent.nodes = mixins.concat(parent.nodes); + parent.hasExtends = true; + return parent; } - return innerError || outerError + return ast; } -class AbortError extends Error { - constructor(message = 'The operation was aborted', options = undefined) { - if (options !== undefined && typeof options !== 'object') { - throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) + +function findDeclaredBlocks(ast) /*: {[name: string]: Array}*/ { + var definitions = {}; + walk(ast, function before(node) { + if (node.type === 'NamedBlock' && node.mode === 'replace') { + definitions[node.name] = definitions[node.name] || []; + definitions[node.name].push(node); } - super(message, options) - this.code = 'ABORT_ERR' - this.name = 'AbortError' - } + }); + return definitions; } -E('ERR_ASSERTION', '%s', Error) -E( - 'ERR_INVALID_ARG_TYPE', - (name, expected, actual) => { - assert(typeof name === 'string', "'name' must be a string") - if (!Array.isArray(expected)) { - expected = [expected] - } - let msg = 'The ' - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg += `${name} ` - } else { - msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} ` - } - msg += 'must be ' - const types = [] - const instances = [] - const other = [] - for (const value of expected) { - assert(typeof value === 'string', 'All expected entries have to be of type string') - if (kTypes.includes(value)) { - types.push(value.toLowerCase()) - } else if (classRegExp.test(value)) { - instances.push(value) - } else { - assert(value !== 'object', 'The value "object" should be written as "Object"') - other.push(value) - } - } - // Special handle `object` in case other instances are allowed to outline - // the differences between each other. - if (instances.length > 0) { - const pos = types.indexOf('object') - if (pos !== -1) { - types.splice(types, pos, 1) - instances.push('Object') - } +function flattenParentBlocks(parentBlocks, accumulator) { + accumulator = accumulator || []; + parentBlocks.forEach(function(parentBlock) { + if (parentBlock.parents) { + flattenParentBlocks(parentBlock.parents, accumulator); } - if (types.length > 0) { - switch (types.length) { - case 1: - msg += `of type ${types[0]}` - break - case 2: - msg += `one of type ${types[0]} or ${types[1]}` - break - default: { - const last = types.pop() - msg += `one of type ${types.join(', ')}, or ${last}` + accumulator.push(parentBlock); + }); + return accumulator; +} + +function extend(parentBlocks, ast) { + var stack = {}; + walk( + ast, + function before(node) { + if (node.type === 'NamedBlock') { + if (stack[node.name] === node.name) { + return (node.ignore = true); + } + stack[node.name] = node.name; + var parentBlockList = parentBlocks[node.name] + ? flattenParentBlocks(parentBlocks[node.name]) + : []; + if (parentBlockList.length) { + node.parents = parentBlockList; + parentBlockList.forEach(function(parentBlock) { + switch (node.mode) { + case 'append': + parentBlock.nodes = parentBlock.nodes.concat(node.nodes); + break; + case 'prepend': + parentBlock.nodes = node.nodes.concat(parentBlock.nodes); + break; + case 'replace': + parentBlock.nodes = node.nodes; + break; + } + }); } } - if (instances.length > 0 || other.length > 0) { - msg += ' or ' + }, + function after(node) { + if (node.type === 'NamedBlock' && !node.ignore) { + delete stack[node.name]; } } - if (instances.length > 0) { - switch (instances.length) { - case 1: - msg += `an instance of ${instances[0]}` - break - case 2: - msg += `an instance of ${instances[0]} or ${instances[1]}` - break - default: { - const last = instances.pop() - msg += `an instance of ${instances.join(', ')}, or ${last}` - } + ); +} + +function applyIncludes(ast, child) { + return walk( + ast, + function before(node, replace) { + if (node.type === 'RawInclude') { + replace({type: 'Text', val: node.file.str.replace(/\r/g, '')}); } - if (other.length > 0) { - msg += ' or ' + }, + function after(node, replace) { + if (node.type === 'Include') { + var childAST = link(node.file.ast); + if (childAST.hasExtends) { + childAST = removeBlocks(childAST); + } + replace(applyYield(childAST, node.block)); } } - switch (other.length) { - case 0: - break - case 1: - if (other[0].toLowerCase() !== other[0]) { - msg += 'an ' - } - msg += `${other[0]}` - break - case 2: - msg += `one of ${other[0]} or ${other[1]}` - break - default: { - const last = other.pop() - msg += `one of ${other.join(', ')}, or ${last}` + ); +} +function removeBlocks(ast) { + return walk(ast, function(node, replace) { + if (node.type === 'NamedBlock') { + replace({ + type: 'Block', + nodes: node.nodes, + }); + } + }); +} + +function applyYield(ast, block) { + if (!block || !block.nodes.length) return ast; + var replaced = false; + ast = walk(ast, null, function(node, replace) { + if (node.type === 'YieldBlock') { + replaced = true; + node.type = 'Block'; + node.nodes = [block]; + } + }); + function defaultYieldLocation(node) { + var res = node; + for (var i = 0; i < node.nodes.length; i++) { + if (node.nodes[i].textOnly) continue; + if (node.nodes[i].type === 'Block') { + res = defaultYieldLocation(node.nodes[i]); + } else if (node.nodes[i].block && node.nodes[i].block.nodes.length) { + res = defaultYieldLocation(node.nodes[i].block); } } - if (actual == null) { - msg += `. Received ${actual}` - } else if (typeof actual === 'function' && actual.name) { - msg += `. Received function ${actual.name}` - } else if (typeof actual === 'object') { - var _actual$constructor - if ( - (_actual$constructor = actual.constructor) !== null && - _actual$constructor !== undefined && - _actual$constructor.name - ) { - msg += `. Received an instance of ${actual.constructor.name}` + return res; + } + if (!replaced) { + // todo: probably should deprecate this with a warning + defaultYieldLocation(ast).nodes.push(block); + } + return ast; +} + +function checkExtendPosition(ast, hasExtends) { + var legitExtendsReached = false; + walk(ast, function(node) { + if (node.type === 'Extends') { + if (hasExtends && !legitExtendsReached) { + legitExtendsReached = true; } else { - const inspected = inspect(actual, { - depth: -1 - }) - msg += `. Received ${inspected}` - } - } else { - let inspected = inspect(actual, { - colors: false - }) - if (inspected.length > 25) { - inspected = `${inspected.slice(0, 25)}...` + error( + 'EXTENDS_NOT_FIRST', + 'Declaration of template inheritance ("extends") should be the first thing in the file. There can only be one extends statement per file.', + node + ); } - msg += `. Received type ${typeof actual} (${inspected})` - } - return msg - }, - TypeError -) -E( - 'ERR_INVALID_ARG_VALUE', - (name, value, reason = 'is invalid') => { - let inspected = inspect(value) - if (inspected.length > 128) { - inspected = inspected.slice(0, 128) + '...' } - const type = name.includes('.') ? 'property' : 'argument' - return `The ${type} '${name}' ${reason}. Received ${inspected}` - }, - TypeError -) -E( - 'ERR_INVALID_RETURN_VALUE', - (input, name, value) => { - var _value$constructor - const type = - value !== null && - value !== undefined && - (_value$constructor = value.constructor) !== null && - _value$constructor !== undefined && - _value$constructor.name - ? `instance of ${value.constructor.name}` - : `type ${typeof value}` - return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` - }, - TypeError -) -E( - 'ERR_MISSING_ARGS', - (...args) => { - assert(args.length > 0, 'At least one arg needs to be specified') - let msg - const len = args.length - args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or ') - switch (len) { - case 1: - msg += `The ${args[0]} argument` - break - case 2: - msg += `The ${args[0]} and ${args[1]} arguments` - break - default: - { - const last = args.pop() - msg += `The ${args.join(', ')}, and ${last} arguments` + }); +} + + +/***/ }), + +/***/ 44254: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var fs = __nccwpck_require__(57147); +var path = __nccwpck_require__(71017); +var walk = __nccwpck_require__(60283); +var assign = __nccwpck_require__(17426); + +module.exports = load; +function load(ast, options) { + options = getOptions(options); + // clone the ast + ast = JSON.parse(JSON.stringify(ast)); + return walk(ast, function(node) { + if (node.str === undefined) { + if ( + node.type === 'Include' || + node.type === 'RawInclude' || + node.type === 'Extends' + ) { + var file = node.file; + if (file.type !== 'FileReference') { + throw new Error('Expected file.type to be "FileReference"'); + } + var path, str, raw; + try { + path = options.resolve(file.path, file.filename, options); + file.fullPath = path; + raw = options.read(path, options); + str = raw.toString('utf8'); + } catch (ex) { + ex.message += '\n at ' + node.filename + ' line ' + node.line; + throw ex; + } + file.str = str; + file.raw = raw; + if (node.type === 'Extends' || node.type === 'Include') { + file.ast = load.string( + str, + assign({}, options, { + filename: path, + }) + ); } - break - } - return `${msg} must be specified` - }, - TypeError -) -E( - 'ERR_OUT_OF_RANGE', - (str, range, input) => { - assert(range, 'Missing "range" argument') - let received - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)) - } else if (typeof input === 'bigint') { - received = String(input) - const limit = BigInt(2) ** BigInt(32) - if (input > limit || input < -limit) { - received = addNumericalSeparator(received) } - received += 'n' - } else { - received = inspect(input) } - return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` - }, - RangeError -) -E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error) -E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error) -E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error) -E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error) -E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error) -E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError) -E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error) -E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error) -E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error) -E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error) -E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError) -module.exports = { - AbortError, - aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), - hideStackFrames, - codes + }); } +load.string = function loadString(src, options) { + options = assign(getOptions(options), { + src: src, + }); + var tokens = options.lex(src, options); + var ast = options.parse(tokens, options); + return load(ast, options); +}; +load.file = function loadFile(filename, options) { + options = assign(getOptions(options), { + filename: filename, + }); + var str = options.read(filename).toString('utf8'); + return load.string(str, options); +}; -/***/ }), - -/***/ 45193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +load.resolve = function resolve(filename, source, options) { + filename = filename.trim(); + if (filename[0] !== '/' && !source) + throw new Error( + 'the "filename" option is required to use includes and extends with "relative" paths' + ); -"use strict"; + if (filename[0] === '/' && !options.basedir) + throw new Error( + 'the "basedir" option is required to use includes and extends with "absolute" paths' + ); + filename = path.join( + filename[0] === '/' ? options.basedir : path.dirname(source.trim()), + filename + ); -const Stream = __nccwpck_require__(12781) -if (Stream && process.env.READABLE_STREAM === 'disable') { - const promises = Stream.promises + return filename; +}; +load.read = function read(filename, options) { + return fs.readFileSync(filename); +}; - // Explicit export naming is needed for ESM - module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer - module.exports._isUint8Array = Stream._isUint8Array - module.exports.isDisturbed = Stream.isDisturbed - module.exports.isErrored = Stream.isErrored - module.exports.isReadable = Stream.isReadable - module.exports.Readable = Stream.Readable - module.exports.Writable = Stream.Writable - module.exports.Duplex = Stream.Duplex - module.exports.Transform = Stream.Transform - module.exports.PassThrough = Stream.PassThrough - module.exports.addAbortSignal = Stream.addAbortSignal - module.exports.finished = Stream.finished - module.exports.destroy = Stream.destroy - module.exports.pipeline = Stream.pipeline - module.exports.compose = Stream.compose - Object.defineProperty(Stream, 'promises', { - configurable: true, - enumerable: true, - get() { - return promises - } - }) - module.exports.Stream = Stream.Stream -} else { - const CustomStream = __nccwpck_require__(75102) - const promises = __nccwpck_require__(348) - const originalDestroy = CustomStream.Readable.destroy - module.exports = CustomStream.Readable +load.validateOptions = function validateOptions(options) { + /* istanbul ignore if */ + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + /* istanbul ignore if */ + if (typeof options.lex !== 'function') { + throw new TypeError('options.lex must be a function'); + } + /* istanbul ignore if */ + if (typeof options.parse !== 'function') { + throw new TypeError('options.parse must be a function'); + } + /* istanbul ignore if */ + if (options.resolve && typeof options.resolve !== 'function') { + throw new TypeError('options.resolve must be a function'); + } + /* istanbul ignore if */ + if (options.read && typeof options.read !== 'function') { + throw new TypeError('options.read must be a function'); + } +}; - // Explicit export naming is needed for ESM - module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer - module.exports._isUint8Array = CustomStream._isUint8Array - module.exports.isDisturbed = CustomStream.isDisturbed - module.exports.isErrored = CustomStream.isErrored - module.exports.isReadable = CustomStream.isReadable - module.exports.Readable = CustomStream.Readable - module.exports.Writable = CustomStream.Writable - module.exports.Duplex = CustomStream.Duplex - module.exports.Transform = CustomStream.Transform - module.exports.PassThrough = CustomStream.PassThrough - module.exports.addAbortSignal = CustomStream.addAbortSignal - module.exports.finished = CustomStream.finished - module.exports.destroy = CustomStream.destroy - module.exports.destroy = originalDestroy - module.exports.pipeline = CustomStream.pipeline - module.exports.compose = CustomStream.compose - Object.defineProperty(CustomStream, 'promises', { - configurable: true, - enumerable: true, - get() { - return promises - } - }) - module.exports.Stream = CustomStream.Stream +function getOptions(options) { + load.validateOptions(options); + return assign( + { + resolve: load.resolve, + read: load.read, + }, + options + ); } -// Allow default importing -module.exports["default"] = module.exports - /***/ }), -/***/ 89629: -/***/ ((module) => { +/***/ 40558: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at +var assert = __nccwpck_require__(39491); +var TokenStream = __nccwpck_require__(68758); +var error = __nccwpck_require__(11449); +var inlineTags = __nccwpck_require__(33470); - https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js +module.exports = parse; +module.exports.Parser = Parser; +function parse(tokens, options) { + var parser = new Parser(tokens, options); + var ast = parser.parse(); + return JSON.parse(JSON.stringify(ast)); +} - Don't try to replace with the original file and keep it up to date with the upstream file. -*/ +/** + * Initialize `Parser` with the given input `str` and `filename`. + * + * @param {String} str + * @param {String} filename + * @param {Object} options + * @api public + */ -// This is a simplified version of AggregateError -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) - } - let message = '' - for (let i = 0; i < errors.length; i++) { - message += ` ${errors[i].stack}\n` - } - super(message) - this.name = 'AggregateError' - this.errors = errors +function Parser(tokens, options) { + options = options || {}; + if (!Array.isArray(tokens)) { + throw new Error( + 'Expected tokens to be an Array but got "' + typeof tokens + '"' + ); + } + if (typeof options !== 'object') { + throw new Error( + 'Expected "options" to be an object but got "' + typeof options + '"' + ); } + this.tokens = new TokenStream(tokens); + this.filename = options.filename; + this.src = options.src; + this.inMixin = 0; + this.plugins = options.plugins || []; } -module.exports = { - AggregateError, - ArrayIsArray(self) { - return Array.isArray(self) - }, - ArrayPrototypeIncludes(self, el) { - return self.includes(el) - }, - ArrayPrototypeIndexOf(self, el) { - return self.indexOf(el) - }, - ArrayPrototypeJoin(self, sep) { - return self.join(sep) - }, - ArrayPrototypeMap(self, fn) { - return self.map(fn) - }, - ArrayPrototypePop(self, el) { - return self.pop(el) - }, - ArrayPrototypePush(self, el) { - return self.push(el) - }, - ArrayPrototypeSlice(self, start, end) { - return self.slice(start, end) - }, - Error, - FunctionPrototypeCall(fn, thisArgs, ...args) { - return fn.call(thisArgs, ...args) + +/** + * Parser prototype. + */ + +Parser.prototype = { + /** + * Save original constructor + */ + + constructor: Parser, + + error: function(code, message, token) { + var err = error(code, message, { + line: token.loc.start.line, + column: token.loc.start.column, + filename: this.filename, + src: this.src, + }); + throw err; }, - FunctionPrototypeSymbolHasInstance(self, instance) { - return Function.prototype[Symbol.hasInstance].call(self, instance) + + /** + * Return the next token object. + * + * @return {Object} + * @api private + */ + + advance: function() { + return this.tokens.advance(); }, - MathFloor: Math.floor, - Number, - NumberIsInteger: Number.isInteger, - NumberIsNaN: Number.isNaN, - NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, - NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, - NumberParseInt: Number.parseInt, - ObjectDefineProperties(self, props) { - return Object.defineProperties(self, props) + + /** + * Single token lookahead. + * + * @return {Object} + * @api private + */ + + peek: function() { + return this.tokens.peek(); }, - ObjectDefineProperty(self, name, prop) { - return Object.defineProperty(self, name, prop) + + /** + * `n` token lookahead. + * + * @param {Number} n + * @return {Object} + * @api private + */ + + lookahead: function(n) { + return this.tokens.lookahead(n); }, - ObjectGetOwnPropertyDescriptor(self, name) { - return Object.getOwnPropertyDescriptor(self, name) + + /** + * Parse input returning a string of js for evaluation. + * + * @return {String} + * @api public + */ + + parse: function() { + var block = this.emptyBlock(0); + + while ('eos' != this.peek().type) { + if ('newline' == this.peek().type) { + this.advance(); + } else if ('text-html' == this.peek().type) { + block.nodes = block.nodes.concat(this.parseTextHtml()); + } else { + var expr = this.parseExpr(); + if (expr) { + if (expr.type === 'Block') { + block.nodes = block.nodes.concat(expr.nodes); + } else { + block.nodes.push(expr); + } + } + } + } + + return block; }, - ObjectKeys(obj) { - return Object.keys(obj) + + /** + * Expect the given type, or throw an exception. + * + * @param {String} type + * @api private + */ + + expect: function(type) { + if (this.peek().type === type) { + return this.advance(); + } else { + this.error( + 'INVALID_TOKEN', + 'expected "' + type + '", but got "' + this.peek().type + '"', + this.peek() + ); + } }, - ObjectSetPrototypeOf(target, proto) { - return Object.setPrototypeOf(target, proto) + + /** + * Accept the given `type`. + * + * @param {String} type + * @api private + */ + + accept: function(type) { + if (this.peek().type === type) { + return this.advance(); + } }, - Promise, - PromisePrototypeCatch(self, fn) { - return self.catch(fn) + + initBlock: function(line, nodes) { + /* istanbul ignore if */ + if ((line | 0) !== line) throw new Error('`line` is not an integer'); + /* istanbul ignore if */ + if (!Array.isArray(nodes)) throw new Error('`nodes` is not an array'); + return { + type: 'Block', + nodes: nodes, + line: line, + filename: this.filename, + }; }, - PromisePrototypeThen(self, thenFn, catchFn) { - return self.then(thenFn, catchFn) + + emptyBlock: function(line) { + return this.initBlock(line, []); }, - PromiseReject(err) { - return Promise.reject(err) + + runPlugin: function(context, tok) { + var rest = [this]; + for (var i = 2; i < arguments.length; i++) { + rest.push(arguments[i]); + } + var pluginContext; + for (var i = 0; i < this.plugins.length; i++) { + var plugin = this.plugins[i]; + if (plugin[context] && plugin[context][tok.type]) { + if (pluginContext) + throw new Error( + 'Multiple plugin handlers found for context ' + + JSON.stringify(context) + + ', token type ' + + JSON.stringify(tok.type) + ); + pluginContext = plugin[context]; + } + } + if (pluginContext) + return pluginContext[tok.type].apply(pluginContext, rest); }, - PromiseResolve(val) { - return Promise.resolve(val) + + /** + * tag + * | doctype + * | mixin + * | include + * | filter + * | comment + * | text + * | text-html + * | dot + * | each + * | code + * | yield + * | id + * | class + * | interpolation + */ + + parseExpr: function() { + switch (this.peek().type) { + case 'tag': + return this.parseTag(); + case 'mixin': + return this.parseMixin(); + case 'block': + return this.parseBlock(); + case 'mixin-block': + return this.parseMixinBlock(); + case 'case': + return this.parseCase(); + case 'extends': + return this.parseExtends(); + case 'include': + return this.parseInclude(); + case 'doctype': + return this.parseDoctype(); + case 'filter': + return this.parseFilter(); + case 'comment': + return this.parseComment(); + case 'text': + case 'interpolated-code': + case 'start-pug-interpolation': + return this.parseText({block: true}); + case 'text-html': + return this.initBlock(this.peek().loc.start.line, this.parseTextHtml()); + case 'dot': + return this.parseDot(); + case 'each': + return this.parseEach(); + case 'eachOf': + return this.parseEachOf(); + case 'code': + return this.parseCode(); + case 'blockcode': + return this.parseBlockCode(); + case 'if': + return this.parseConditional(); + case 'while': + return this.parseWhile(); + case 'call': + return this.parseCall(); + case 'interpolation': + return this.parseInterpolation(); + case 'yield': + return this.parseYield(); + case 'id': + case 'class': + if (!this.peek().loc.start) debugger; + this.tokens.defer({ + type: 'tag', + val: 'div', + loc: this.peek().loc, + filename: this.filename, + }); + return this.parseExpr(); + default: + var pluginResult = this.runPlugin('expressionTokens', this.peek()); + if (pluginResult) return pluginResult; + this.error( + 'INVALID_TOKEN', + 'unexpected token "' + this.peek().type + '"', + this.peek() + ); + } }, - ReflectApply: Reflect.apply, - RegExpPrototypeTest(self, value) { - return self.test(value) + + parseDot: function() { + this.advance(); + return this.parseTextBlock(); }, - SafeSet: Set, - String, - StringPrototypeSlice(self, start, end) { - return self.slice(start, end) + + /** + * Text + */ + + parseText: function(options) { + var tags = []; + var lineno = this.peek().loc.start.line; + var nextTok = this.peek(); + loop: while (true) { + switch (nextTok.type) { + case 'text': + var tok = this.advance(); + tags.push({ + type: 'Text', + val: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + case 'interpolated-code': + var tok = this.advance(); + tags.push({ + type: 'Code', + val: tok.val, + buffer: tok.buffer, + mustEscape: tok.mustEscape !== false, + isInline: true, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + case 'newline': + if (!options || !options.block) break loop; + var tok = this.advance(); + var nextType = this.peek().type; + if (nextType === 'text' || nextType === 'interpolated-code') { + tags.push({ + type: 'Text', + val: '\n', + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + } + break; + case 'start-pug-interpolation': + this.advance(); + tags.push(this.parseExpr()); + this.expect('end-pug-interpolation'); + break; + default: + var pluginResult = this.runPlugin('textTokens', nextTok, tags); + if (pluginResult) break; + break loop; + } + nextTok = this.peek(); + } + if (tags.length === 1) return tags[0]; + else return this.initBlock(lineno, tags); }, - StringPrototypeToLowerCase(self) { - return self.toLowerCase() + + parseTextHtml: function() { + var nodes = []; + var currentNode = null; + loop: while (true) { + switch (this.peek().type) { + case 'text-html': + var text = this.advance(); + if (!currentNode) { + currentNode = { + type: 'Text', + val: text.val, + filename: this.filename, + line: text.loc.start.line, + column: text.loc.start.column, + isHtml: true, + }; + nodes.push(currentNode); + } else { + currentNode.val += '\n' + text.val; + } + break; + case 'indent': + var block = this.block(); + block.nodes.forEach(function(node) { + if (node.isHtml) { + if (!currentNode) { + currentNode = node; + nodes.push(currentNode); + } else { + currentNode.val += '\n' + node.val; + } + } else { + currentNode = null; + nodes.push(node); + } + }); + break; + case 'code': + currentNode = null; + nodes.push(this.parseCode(true)); + break; + case 'newline': + this.advance(); + break; + default: + break loop; + } + } + return nodes; }, - StringPrototypeToUpperCase(self) { - return self.toUpperCase() + + /** + * ':' expr + * | block + */ + + parseBlockExpansion: function() { + var tok = this.accept(':'); + if (tok) { + var expr = this.parseExpr(); + return expr.type === 'Block' + ? expr + : this.initBlock(tok.loc.start.line, [expr]); + } else { + return this.block(); + } }, - StringPrototypeTrim(self) { - return self.trim() + + /** + * case + */ + + parseCase: function() { + var tok = this.expect('case'); + var node = { + type: 'Case', + expr: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + + var block = this.emptyBlock(tok.loc.start.line + 1); + this.expect('indent'); + while ('outdent' != this.peek().type) { + switch (this.peek().type) { + case 'comment': + case 'newline': + this.advance(); + break; + case 'when': + block.nodes.push(this.parseWhen()); + break; + case 'default': + block.nodes.push(this.parseDefault()); + break; + default: + var pluginResult = this.runPlugin('caseTokens', this.peek(), block); + if (pluginResult) break; + this.error( + 'INVALID_TOKEN', + 'Unexpected token "' + + this.peek().type + + '", expected "when", "default" or "newline"', + this.peek() + ); + } + } + this.expect('outdent'); + + node.block = block; + + return node; }, - Symbol, - SymbolFor: Symbol.for, - SymbolAsyncIterator: Symbol.asyncIterator, - SymbolHasInstance: Symbol.hasInstance, - SymbolIterator: Symbol.iterator, - SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), - SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), - TypedArrayPrototypeSet(self, buf, len) { - return self.set(buf, len) + + /** + * when + */ + + parseWhen: function() { + var tok = this.expect('when'); + if (this.peek().type !== 'newline') { + return { + type: 'When', + expr: tok.val, + block: this.parseBlockExpansion(), + debug: false, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + } else { + return { + type: 'When', + expr: tok.val, + debug: false, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + } }, - Boolean, - Uint8Array -} + /** + * default + */ -/***/ }), + parseDefault: function() { + var tok = this.expect('default'); + return { + type: 'When', + expr: 'default', + block: this.parseBlockExpansion(), + debug: false, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -/***/ 46959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * code + */ -"use strict"; + parseCode: function(noBlock) { + var tok = this.expect('code'); + assert( + typeof tok.mustEscape === 'boolean', + 'Please update to the newest version of pug-lexer.' + ); + var node = { + type: 'Code', + val: tok.val, + buffer: tok.buffer, + mustEscape: tok.mustEscape !== false, + isInline: !!noBlock, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + // todo: why is this here? It seems like a hacky workaround + if (node.val.match(/^ *else/)) node.debug = false; + if (noBlock) return node; -const bufferModule = __nccwpck_require__(14300) -const { format, inspect } = __nccwpck_require__(43075) -const { - codes: { ERR_INVALID_ARG_TYPE } -} = __nccwpck_require__(80529) -const { kResistStopPropagation, AggregateError, SymbolDispose } = __nccwpck_require__(89629) -const AbortSignal = globalThis.AbortSignal || (__nccwpck_require__(61659).AbortSignal) -const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) -const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor -const Blob = globalThis.Blob || bufferModule.Blob -/* eslint-disable indent */ -const isBlob = - typeof Blob !== 'undefined' - ? function isBlob(b) { - // eslint-disable-next-line indent - return b instanceof Blob - } - : function isBlob(b) { - return false - } -/* eslint-enable indent */ + var block; -const validateAbortSignal = (signal, name) => { - if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { - throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) - } -} -const validateFunction = (value, name) => { - if (typeof value !== 'function') { - throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) - } -} -module.exports = { - AggregateError, - kEmptyObject: Object.freeze({}), - once(callback) { - let called = false - return function (...args) { - if (called) { - return + // handle block + block = 'indent' == this.peek().type; + if (block) { + if (tok.buffer) { + this.error( + 'BLOCK_IN_BUFFERED_CODE', + 'Buffered code cannot have a block attached to it', + this.peek() + ); } - called = true - callback.apply(this, args) + node.block = this.block(); } + + return node; }, - createDeferredPromise: function () { - let resolve - let reject + parseConditional: function() { + var tok = this.expect('if'); + var node = { + type: 'Conditional', + test: tok.val, + consequent: this.emptyBlock(tok.loc.start.line), + alternate: null, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; - // eslint-disable-next-line promise/param-names - const promise = new Promise((res, rej) => { - resolve = res - reject = rej - }) - return { - promise, - resolve, - reject + // handle block + if ('indent' == this.peek().type) { + node.consequent = this.block(); } - }, - promisify(fn) { - return new Promise((resolve, reject) => { - fn((err, ...args) => { - if (err) { - return reject(err) + + var currentNode = node; + while (true) { + if (this.peek().type === 'newline') { + this.expect('newline'); + } else if (this.peek().type === 'else-if') { + tok = this.expect('else-if'); + currentNode = currentNode.alternate = { + type: 'Conditional', + test: tok.val, + consequent: this.emptyBlock(tok.loc.start.line), + alternate: null, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + if ('indent' == this.peek().type) { + currentNode.consequent = this.block(); } - return resolve(...args) - }) - }) - }, - debuglog() { - return function () {} - }, - format, - inspect, - types: { - isAsyncFunction(fn) { - return fn instanceof AsyncFunction - }, - isArrayBufferView(arr) { - return ArrayBuffer.isView(arr) + } else if (this.peek().type === 'else') { + this.expect('else'); + if (this.peek().type === 'indent') { + currentNode.alternate = this.block(); + } + break; + } else { + break; + } } + + return node; }, - isBlob, - deprecate(fn, message) { - return fn + parseWhile: function() { + var tok = this.expect('while'); + var node = { + type: 'While', + test: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + + // handle block + if ('indent' == this.peek().type) { + node.block = this.block(); + } else { + node.block = this.emptyBlock(tok.loc.start.line); + } + + return node; }, - addAbortListener: - (__nccwpck_require__(82361).addAbortListener) || - function addAbortListener(signal, listener) { - if (signal === undefined) { - throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) - } - validateAbortSignal(signal, 'signal') - validateFunction(listener, 'listener') - let removeEventListener - if (signal.aborted) { - queueMicrotask(() => listener()) - } else { - signal.addEventListener('abort', listener, { - __proto__: null, - once: true, - [kResistStopPropagation]: true - }) - removeEventListener = () => { - signal.removeEventListener('abort', listener) + + /** + * block code + */ + + parseBlockCode: function() { + var tok = this.expect('blockcode'); + var line = tok.loc.start.line; + var column = tok.loc.start.column; + var body = this.peek(); + var text = ''; + if (body.type === 'start-pipeless-text') { + this.advance(); + while (this.peek().type !== 'end-pipeless-text') { + tok = this.advance(); + switch (tok.type) { + case 'text': + text += tok.val; + break; + case 'newline': + text += '\n'; + break; + default: + var pluginResult = this.runPlugin('blockCodeTokens', tok, tok); + if (pluginResult) { + text += pluginResult; + break; + } + this.error( + 'INVALID_TOKEN', + 'Unexpected token type: ' + tok.type, + tok + ); } } + this.advance(); + } + return { + type: 'Code', + val: text, + buffer: false, + mustEscape: false, + isInline: false, + line: line, + column: column, + filename: this.filename, + }; + }, + /** + * comment + */ + + parseComment: function() { + var tok = this.expect('comment'); + var block; + if ((block = this.parseTextBlock())) { + return { + type: 'BlockComment', + val: tok.val, + block: block, + buffer: tok.buffer, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + } else { return { - __proto__: null, - [SymbolDispose]() { - var _removeEventListener - ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined - ? undefined - : _removeEventListener() - } - } - }, - AbortSignalAny: - AbortSignal.any || - function AbortSignalAny(signals) { - // Fast path if there is only one signal. - if (signals.length === 1) { - return signals[0] - } - const ac = new AbortController() - const abort = () => ac.abort() - signals.forEach((signal) => { - validateAbortSignal(signal, 'signals') - signal.addEventListener('abort', abort, { - once: true - }) - }) - ac.signal.addEventListener( - 'abort', - () => { - signals.forEach((signal) => signal.removeEventListener('abort', abort)) - }, - { - once: true - } - ) - return ac.signal + type: 'Comment', + val: tok.val, + buffer: tok.buffer, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; } -} -module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom') + }, + /** + * doctype + */ -/***/ }), + parseDoctype: function() { + var tok = this.expect('doctype'); + return { + type: 'Doctype', + val: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -/***/ 43075: -/***/ ((module) => { + parseIncludeFilter: function() { + var tok = this.expect('filter'); + var attrs = []; -"use strict"; + if (this.peek().type === 'start-attributes') { + attrs = this.attrs(); + } + return { + type: 'IncludeFilter', + name: tok.val, + attrs: attrs, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -/* - This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at + /** + * filter attrs? text-block + */ - https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js + parseFilter: function() { + var tok = this.expect('filter'); + var block, + attrs = []; - Don't try to replace with the original file and keep it up to date with the upstream file. -*/ -module.exports = { - format(format, ...args) { - // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args - return format.replace(/%([sdifj])/g, function (...[_unused, type]) { - const replacement = args.shift() - if (type === 'f') { - return replacement.toFixed(6) - } else if (type === 'j') { - return JSON.stringify(replacement) - } else if (type === 's' && typeof replacement === 'object') { - const ctor = replacement.constructor !== Object ? replacement.constructor.name : '' - return `${ctor} {}`.trim() - } else { - return replacement.toString() - } - }) - }, - inspect(value) { - // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options - switch (typeof value) { - case 'string': - if (value.includes("'")) { - if (!value.includes('"')) { - return `"${value}"` - } else if (!value.includes('`') && !value.includes('${')) { - return `\`${value}\`` - } - } - return `'${value}'` - case 'number': - if (isNaN(value)) { - return 'NaN' - } else if (Object.is(value, -0)) { - return String(value) - } - return value - case 'bigint': - return `${String(value)}n` - case 'boolean': - case 'undefined': - return String(value) - case 'object': - return '{}' + if (this.peek().type === 'start-attributes') { + attrs = this.attrs(); } - } -} - -/***/ }), + if (this.peek().type === 'text') { + var textToken = this.advance(); + block = this.initBlock(textToken.loc.start.line, [ + { + type: 'Text', + val: textToken.val, + line: textToken.loc.start.line, + column: textToken.loc.start.column, + filename: this.filename, + }, + ]); + } else if (this.peek().type === 'filter') { + block = this.initBlock(tok.loc.start.line, [this.parseFilter()]); + } else { + block = this.parseTextBlock() || this.emptyBlock(tok.loc.start.line); + } -/***/ 75102: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return { + type: 'Filter', + name: tok.val, + block: block, + attrs: attrs, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + /** + * each block + */ + parseEach: function() { + var tok = this.expect('each'); + var node = { + type: 'Each', + obj: tok.code, + val: tok.val, + key: tok.key, + block: this.block(), + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + if (this.peek().type == 'else') { + this.advance(); + node.alternate = this.block(); + } + return node; + }, + parseEachOf: function() { + var tok = this.expect('eachOf'); + var node = { + type: 'EachOf', + obj: tok.code, + val: tok.val, + block: this.block(), + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + return node; + }, + /** + * 'extends' name + */ -/* replacement start */ + parseExtends: function() { + var tok = this.expect('extends'); + var path = this.expect('path'); + return { + type: 'Extends', + file: { + type: 'FileReference', + path: path.val.trim(), + line: path.loc.start.line, + column: path.loc.start.column, + filename: this.filename, + }, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -const { Buffer } = __nccwpck_require__(14300) + /** + * 'block' name block + */ -/* replacement end */ + parseBlock: function() { + var tok = this.expect('block'); -const { ObjectDefineProperty, ObjectKeys, ReflectApply } = __nccwpck_require__(89629) -const { - promisify: { custom: customPromisify } -} = __nccwpck_require__(46959) -const { streamReturningOperators, promiseReturningOperators } = __nccwpck_require__(63193) -const { - codes: { ERR_ILLEGAL_CONSTRUCTOR } -} = __nccwpck_require__(80529) -const compose = __nccwpck_require__(63129) -const { setDefaultHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) -const { pipeline } = __nccwpck_require__(76989) -const { destroyer } = __nccwpck_require__(97049) -const eos = __nccwpck_require__(76080) -const internalBuffer = {} -const promises = __nccwpck_require__(348) -const utils = __nccwpck_require__(27981) -const Stream = (module.exports = __nccwpck_require__(49792).Stream) -Stream.isDestroyed = utils.isDestroyed -Stream.isDisturbed = utils.isDisturbed -Stream.isErrored = utils.isErrored -Stream.isReadable = utils.isReadable -Stream.isWritable = utils.isWritable -Stream.Readable = __nccwpck_require__(57920) -for (const key of ObjectKeys(streamReturningOperators)) { - const op = streamReturningOperators[key] - function fn(...args) { - if (new.target) { - throw ERR_ILLEGAL_CONSTRUCTOR() - } - return Stream.Readable.from(ReflectApply(op, this, args)) - } - ObjectDefineProperty(fn, 'name', { - __proto__: null, - value: op.name - }) - ObjectDefineProperty(fn, 'length', { - __proto__: null, - value: op.length - }) - ObjectDefineProperty(Stream.Readable.prototype, key, { - __proto__: null, - value: fn, - enumerable: false, - configurable: true, - writable: true - }) -} -for (const key of ObjectKeys(promiseReturningOperators)) { - const op = promiseReturningOperators[key] - function fn(...args) { - if (new.target) { - throw ERR_ILLEGAL_CONSTRUCTOR() - } - return ReflectApply(op, this, args) - } - ObjectDefineProperty(fn, 'name', { - __proto__: null, - value: op.name - }) - ObjectDefineProperty(fn, 'length', { - __proto__: null, - value: op.length - }) - ObjectDefineProperty(Stream.Readable.prototype, key, { - __proto__: null, - value: fn, - enumerable: false, - configurable: true, - writable: true - }) -} -Stream.Writable = __nccwpck_require__(48488) -Stream.Duplex = __nccwpck_require__(72613) -Stream.Transform = __nccwpck_require__(86941) -Stream.PassThrough = __nccwpck_require__(72839) -Stream.pipeline = pipeline -const { addAbortSignal } = __nccwpck_require__(80289) -Stream.addAbortSignal = addAbortSignal -Stream.finished = eos -Stream.destroy = destroyer -Stream.compose = compose -Stream.setDefaultHighWaterMark = setDefaultHighWaterMark -Stream.getDefaultHighWaterMark = getDefaultHighWaterMark -ObjectDefineProperty(Stream, 'promises', { - __proto__: null, - configurable: true, - enumerable: true, - get() { - return promises - } -}) -ObjectDefineProperty(pipeline, customPromisify, { - __proto__: null, - enumerable: true, - get() { - return promises.pipeline - } -}) -ObjectDefineProperty(eos, customPromisify, { - __proto__: null, - enumerable: true, - get() { - return promises.finished - } -}) + var node = + 'indent' == this.peek().type + ? this.block() + : this.emptyBlock(tok.loc.start.line); + node.type = 'NamedBlock'; + node.name = tok.val.trim(); + node.mode = tok.mode; + node.line = tok.loc.start.line; + node.column = tok.loc.start.column; -// Backwards-compat with node 0.4.x -Stream.Stream = Stream -Stream._isUint8Array = function isUint8Array(value) { - return value instanceof Uint8Array -} -Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) -} + return node; + }, + parseMixinBlock: function() { + var tok = this.expect('mixin-block'); + if (!this.inMixin) { + this.error( + 'BLOCK_OUTISDE_MIXIN', + 'Anonymous blocks are not allowed unless they are part of a mixin.', + tok + ); + } + return { + type: 'MixinBlock', + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -/***/ }), + parseYield: function() { + var tok = this.expect('yield'); + return { + type: 'YieldBlock', + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + }, -/***/ 348: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * include block? + */ -"use strict"; + parseInclude: function() { + var tok = this.expect('include'); + var node = { + type: 'Include', + file: { + type: 'FileReference', + filename: this.filename, + }, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + var filters = []; + while (this.peek().type === 'filter') { + filters.push(this.parseIncludeFilter()); + } + var path = this.expect('path'); + node.file.path = path.val.trim(); + node.file.line = path.loc.start.line; + node.file.column = path.loc.start.column; -const { ArrayPrototypePop, Promise } = __nccwpck_require__(89629) -const { isIterable, isNodeStream, isWebStream } = __nccwpck_require__(27981) -const { pipelineImpl: pl } = __nccwpck_require__(76989) -const { finished } = __nccwpck_require__(76080) -__nccwpck_require__(75102) -function pipeline(...streams) { - return new Promise((resolve, reject) => { - let signal - let end - const lastArg = streams[streams.length - 1] if ( - lastArg && - typeof lastArg === 'object' && - !isNodeStream(lastArg) && - !isIterable(lastArg) && - !isWebStream(lastArg) + (/\.jade$/.test(node.file.path) || /\.pug$/.test(node.file.path)) && + !filters.length ) { - const options = ArrayPrototypePop(streams) - signal = options.signal - end = options.end - } - pl( - streams, - (err, value) => { - if (err) { - reject(err) - } else { - resolve(value) - } - }, - { - signal, - end + node.block = + 'indent' == this.peek().type + ? this.block() + : this.emptyBlock(tok.loc.start.line); + if (/\.jade$/.test(node.file.path)) { + console.warn( + this.filename + + ', line ' + + tok.loc.start.line + + ':\nThe .jade extension is deprecated, use .pug for "' + + node.file.path + + '".' + ); } - ) - }) -} -module.exports = { - finished, - pipeline -} - + } else { + node.type = 'RawInclude'; + node.filters = filters; + if (this.peek().type === 'indent') { + this.error( + 'RAW_INCLUDE_BLOCK', + 'Raw inclusion cannot contain a block', + this.peek() + ); + } + } + return node; + }, -/***/ }), + /** + * call ident block + */ -/***/ 17978: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + parseCall: function() { + var tok = this.expect('call'); + var name = tok.val; + var args = tok.args; + var mixin = { + type: 'Mixin', + name: name, + args: args, + block: this.emptyBlock(tok.loc.start.line), + call: true, + attrs: [], + attributeBlocks: [], + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; -module.exports = readdirGlob; + this.tag(mixin); + if (mixin.code) { + mixin.block.nodes.push(mixin.code); + delete mixin.code; + } + if (mixin.block.nodes.length === 0) mixin.block = null; + return mixin; + }, -const fs = __nccwpck_require__(57147); -const { EventEmitter } = __nccwpck_require__(82361); -const { Minimatch } = __nccwpck_require__(27771); -const { resolve } = __nccwpck_require__(71017); + /** + * mixin block + */ -function readdir(dir, strict) { - return new Promise((resolve, reject) => { - fs.readdir(dir, {withFileTypes: true} ,(err, files) => { - if(err) { - switch (err.code) { - case 'ENOTDIR': // Not a directory - if(strict) { - reject(err); - } else { - resolve([]); - } - break; - case 'ENOTSUP': // Operation not supported - case 'ENOENT': // No such file or directory - case 'ENAMETOOLONG': // Filename too long - case 'UNKNOWN': - resolve([]); - break; - case 'ELOOP': // Too many levels of symbolic links - default: - reject(err); - break; - } - } else { - resolve(files); - } - }); - }); -} -function stat(file, followSymlinks) { - return new Promise((resolve, reject) => { - const statFunc = followSymlinks ? fs.stat : fs.lstat; - statFunc(file, (err, stats) => { - if(err) { - switch (err.code) { - case 'ENOENT': - if(followSymlinks) { - // Fallback to lstat to handle broken links as files - resolve(stat(file, false)); - } else { - resolve(null); - } - break; - default: - resolve(null); - break; - } - } else { - resolve(stats); - } - }); - }); -} + parseMixin: function() { + var tok = this.expect('mixin'); + var name = tok.val; + var args = tok.args; -async function* exploreWalkAsync(dir, path, followSymlinks, useStat, shouldSkip, strict) { - let files = await readdir(path + dir, strict); - for(const file of files) { - let name = file.name; - if(name === undefined) { - // undefined file.name means the `withFileTypes` options is not supported by node - // we have to call the stat function to know if file is directory or not. - name = file; - useStat = true; - } - const filename = dir + '/' + name; - const relative = filename.slice(1); // Remove the leading / - const absolute = path + '/' + relative; - let stats = null; - if(useStat || followSymlinks) { - stats = await stat(absolute, followSymlinks); - } - if(!stats && file.name !== undefined) { - stats = file; - } - if(stats === null) { - stats = { isDirectory: () => false }; + if ('indent' == this.peek().type) { + this.inMixin++; + var mixin = { + type: 'Mixin', + name: name, + args: args, + block: this.block(), + call: false, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; + this.inMixin--; + return mixin; + } else { + this.error( + 'MIXIN_WITHOUT_BODY', + 'Mixin ' + name + ' declared without body', + tok + ); } + }, - if(stats.isDirectory()) { - if(!shouldSkip(relative)) { - yield {relative, absolute, stats}; - yield* exploreWalkAsync(filename, path, followSymlinks, useStat, shouldSkip, false); + /** + * indent (text | newline)* outdent + */ + + parseTextBlock: function() { + var tok = this.accept('start-pipeless-text'); + if (!tok) return; + var block = this.emptyBlock(tok.loc.start.line); + while (this.peek().type !== 'end-pipeless-text') { + var tok = this.advance(); + switch (tok.type) { + case 'text': + block.nodes.push({ + type: 'Text', + val: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + case 'newline': + block.nodes.push({ + type: 'Text', + val: '\n', + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + case 'start-pug-interpolation': + block.nodes.push(this.parseExpr()); + this.expect('end-pug-interpolation'); + break; + case 'interpolated-code': + block.nodes.push({ + type: 'Code', + val: tok.val, + buffer: tok.buffer, + mustEscape: tok.mustEscape !== false, + isInline: true, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + default: + var pluginResult = this.runPlugin('textBlockTokens', tok, block, tok); + if (pluginResult) break; + this.error( + 'INVALID_TOKEN', + 'Unexpected token type: ' + tok.type, + tok + ); } - } else { - yield {relative, absolute, stats}; } - } -} -async function* explore(path, followSymlinks, useStat, shouldSkip) { - yield* exploreWalkAsync('', path, followSymlinks, useStat, shouldSkip, true); -} + this.advance(); + return block; + }, + /** + * indent expr* outdent + */ -function readOptions(options) { - return { - pattern: options.pattern, - dot: !!options.dot, - noglobstar: !!options.noglobstar, - matchBase: !!options.matchBase, - nocase: !!options.nocase, - ignore: options.ignore, - skip: options.skip, + block: function() { + var tok = this.expect('indent'); + var block = this.emptyBlock(tok.loc.start.line); + while ('outdent' != this.peek().type) { + if ('newline' == this.peek().type) { + this.advance(); + } else if ('text-html' == this.peek().type) { + block.nodes = block.nodes.concat(this.parseTextHtml()); + } else { + var expr = this.parseExpr(); + if (expr.type === 'Block') { + block.nodes = block.nodes.concat(expr.nodes); + } else { + block.nodes.push(expr); + } + } + } + this.expect('outdent'); + return block; + }, - follow: !!options.follow, - stat: !!options.stat, - nodir: !!options.nodir, - mark: !!options.mark, - silent: !!options.silent, - absolute: !!options.absolute - }; -} + /** + * interpolation (attrs | class | id)* (text | code | ':')? newline* block? + */ -class ReaddirGlob extends EventEmitter { - constructor(cwd, options, cb) { - super(); - if(typeof options === 'function') { - cb = options; - options = null; - } + parseInterpolation: function() { + var tok = this.advance(); + var tag = { + type: 'InterpolatedTag', + expr: tok.val, + selfClosing: false, + block: this.emptyBlock(tok.loc.start.line), + attrs: [], + attributeBlocks: [], + isInline: false, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; - this.options = readOptions(options || {}); - - this.matchers = []; - if(this.options.pattern) { - const matchers = Array.isArray(this.options.pattern) ? this.options.pattern : [this.options.pattern]; - this.matchers = matchers.map( m => - new Minimatch(m, { - dot: this.options.dot, - noglobstar:this.options.noglobstar, - matchBase:this.options.matchBase, - nocase:this.options.nocase - }) - ); - } - - this.ignoreMatchers = []; - if(this.options.ignore) { - const ignorePatterns = Array.isArray(this.options.ignore) ? this.options.ignore : [this.options.ignore]; - this.ignoreMatchers = ignorePatterns.map( ignore => - new Minimatch(ignore, {dot: true}) - ); - } - - this.skipMatchers = []; - if(this.options.skip) { - const skipPatterns = Array.isArray(this.options.skip) ? this.options.skip : [this.options.skip]; - this.skipMatchers = skipPatterns.map( skip => - new Minimatch(skip, {dot: true}) - ); - } + return this.tag(tag, {selfClosingAllowed: true}); + }, - this.iterator = explore(resolve(cwd || '.'), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this)); - this.paused = false; - this.inactive = false; - this.aborted = false; - - if(cb) { - this._matches = []; - this.on('match', match => this._matches.push(this.options.absolute ? match.absolute : match.relative)); - this.on('error', err => cb(err)); - this.on('end', () => cb(null, this._matches)); - } + /** + * tag (attrs | class | id)* (text | code | ':')? newline* block? + */ - setTimeout( () => this._next(), 0); - } + parseTag: function() { + var tok = this.advance(); + var tag = { + type: 'Tag', + name: tok.val, + selfClosing: false, + block: this.emptyBlock(tok.loc.start.line), + attrs: [], + attributeBlocks: [], + isInline: inlineTags.indexOf(tok.val) !== -1, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }; - _shouldSkipDirectory(relative) { - //console.log(relative, this.skipMatchers.some(m => m.match(relative))); - return this.skipMatchers.some(m => m.match(relative)); - } + return this.tag(tag, {selfClosingAllowed: true}); + }, - _fileMatches(relative, isDirectory) { - const file = relative + (isDirectory ? '/' : ''); - return (this.matchers.length === 0 || this.matchers.some(m => m.match(file))) - && !this.ignoreMatchers.some(m => m.match(file)) - && (!this.options.nodir || !isDirectory); - } + /** + * Parse tag. + */ - _next() { - if(!this.paused && !this.aborted) { - this.iterator.next() - .then((obj)=> { - if(!obj.done) { - const isDirectory = obj.value.stats.isDirectory(); - if(this._fileMatches(obj.value.relative, isDirectory )) { - let relative = obj.value.relative; - let absolute = obj.value.absolute; - if(this.options.mark && isDirectory) { - relative += '/'; - absolute += '/'; - } - if(this.options.stat) { - this.emit('match', {relative, absolute, stat:obj.value.stats}); - } else { - this.emit('match', {relative, absolute}); + tag: function(tag, options) { + var seenAttrs = false; + var attributeNames = []; + var selfClosingAllowed = options && options.selfClosingAllowed; + // (attrs | class | id)* + out: while (true) { + switch (this.peek().type) { + case 'id': + case 'class': + var tok = this.advance(); + if (tok.type === 'id') { + if (attributeNames.indexOf('id') !== -1) { + this.error( + 'DUPLICATE_ID', + 'Duplicate attribute "id" is not allowed.', + tok + ); } + attributeNames.push('id'); } - this._next(this.iterator); + tag.attrs.push({ + name: tok.type, + val: "'" + tok.val + "'", + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + mustEscape: false, + }); + continue; + case 'start-attributes': + if (seenAttrs) { + console.warn( + this.filename + + ', line ' + + this.peek().loc.start.line + + ':\nYou should not have pug tags with multiple attributes.' + ); + } + seenAttrs = true; + tag.attrs = tag.attrs.concat(this.attrs(attributeNames)); + continue; + case '&attributes': + var tok = this.advance(); + tag.attributeBlocks.push({ + type: 'AttributeBlock', + val: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + }); + break; + default: + var pluginResult = this.runPlugin( + 'tagAttributeTokens', + this.peek(), + tag, + attributeNames + ); + if (pluginResult) break; + break out; + } + } + + // check immediate '.' + if ('dot' == this.peek().type) { + tag.textOnly = true; + this.advance(); + } + + // (text | code | ':')? + switch (this.peek().type) { + case 'text': + case 'interpolated-code': + var text = this.parseText(); + if (text.type === 'Block') { + tag.block.nodes.push.apply(tag.block.nodes, text.nodes); } else { - this.emit('end'); + tag.block.nodes.push(text); } - }) - .catch((err) => { - this.abort(); - this.emit('error', err); - if(!err.code && !this.options.silent) { - console.error(err); + break; + case 'code': + tag.block.nodes.push(this.parseCode(true)); + break; + case ':': + this.advance(); + var expr = this.parseExpr(); + tag.block = + expr.type === 'Block' ? expr : this.initBlock(tag.line, [expr]); + break; + case 'newline': + case 'indent': + case 'outdent': + case 'eos': + case 'start-pipeless-text': + case 'end-pug-interpolation': + break; + case 'slash': + if (selfClosingAllowed) { + this.advance(); + tag.selfClosing = true; + break; } - }); - } else { - this.inactive = true; + default: + var pluginResult = this.runPlugin( + 'tagTokens', + this.peek(), + tag, + options + ); + if (pluginResult) break; + this.error( + 'INVALID_TOKEN', + 'Unexpected token `' + + this.peek().type + + '` expected `text`, `interpolated-code`, `code`, `:`' + + (selfClosingAllowed ? ', `slash`' : '') + + ', `newline` or `eos`', + this.peek() + ); } - } - abort() { - this.aborted = true; - } + // newline* + while ('newline' == this.peek().type) this.advance(); - pause() { - this.paused = true; - } + // block? + if (tag.textOnly) { + tag.block = this.parseTextBlock() || this.emptyBlock(tag.line); + } else if ('indent' == this.peek().type) { + var block = this.block(); + for (var i = 0, len = block.nodes.length; i < len; ++i) { + tag.block.nodes.push(block.nodes[i]); + } + } - resume() { - this.paused = false; - if(this.inactive) { - this.inactive = false; - this._next(); + return tag; + }, + + attrs: function(attributeNames) { + this.expect('start-attributes'); + + var attrs = []; + var tok = this.advance(); + while (tok.type === 'attribute') { + if (tok.name !== 'class' && attributeNames) { + if (attributeNames.indexOf(tok.name) !== -1) { + this.error( + 'DUPLICATE_ATTRIBUTE', + 'Duplicate attribute "' + tok.name + '" is not allowed.', + tok + ); + } + attributeNames.push(tok.name); + } + attrs.push({ + name: tok.name, + val: tok.val, + line: tok.loc.start.line, + column: tok.loc.start.column, + filename: this.filename, + mustEscape: tok.mustEscape !== false, + }); + tok = this.advance(); } - } -} - + this.tokens.defer(tok); + this.expect('end-attributes'); + return attrs; + }, +}; -function readdirGlob(pattern, options, cb) { - return new ReaddirGlob(pattern, options, cb); -} -readdirGlob.ReaddirGlob = ReaddirGlob; /***/ }), -/***/ 79482: +/***/ 33470: /***/ ((module) => { -const isWindows = typeof process === 'object' && - process && - process.platform === 'win32' -module.exports = isWindows ? { sep: '\\' } : { sep: '/' } +"use strict"; -/***/ }), +module.exports = [ + 'a', + 'abbr', + 'acronym', + 'b', + 'br', + 'code', + 'em', + 'font', + 'i', + 'img', + 'ins', + 'kbd', + 'map', + 'samp', + 'small', + 'span', + 'strong', + 'sub', + 'sup', +]; -/***/ 27771: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const minimatch = module.exports = (p, pattern, options = {}) => { - assertValidPattern(pattern) +/***/ }), - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } +/***/ 37364: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new Minimatch(pattern, options).match(p) -} +"use strict"; -module.exports = minimatch -const path = __nccwpck_require__(79482) -minimatch.sep = path.sep +var fs = __nccwpck_require__(57147); +var dependencies = __nccwpck_require__(41222); +var internals = __nccwpck_require__(373); +var sources = __nccwpck_require__(21003); -const GLOBSTAR = Symbol('globstar **') -minimatch.GLOBSTAR = GLOBSTAR -const expand = __nccwpck_require__(33717) +module.exports = build; -const plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } +function build(functions) { + var fns = []; + functions = functions.filter(function(fn) { + return !internals[fn]; + }); + for (var i = 0; i < functions.length; i++) { + if (fns.indexOf(functions[i]) === -1) { + fns.push(functions[i]); + functions.push.apply(functions, dependencies[functions[i]]); + } + } + return fns + .sort() + .map(function(name) { + return sources[name]; + }) + .join('\n'); } -// any single thing other than / -// don't need to escape / when using new RegExp() -const qmark = '[^/]' - -// * => any number of characters -const star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' -// "abc" -> { a:true, b:true, c:true } -const charSet = s => s.split('').reduce((set, c) => { - set[c] = true - return set -}, {}) +/***/ }), -// characters that need to be escaped in RegExp. -const reSpecials = charSet('().*{}+?[]^$\\!') +/***/ 27596: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// characters that indicate we have to add the pattern start -const addPatternStartSet = charSet('[.(') +"use strict"; -// normalizes slashes. -const slashSplit = /\/+/ -minimatch.filter = (pattern, options = {}) => - (p, i, list) => minimatch(p, pattern, options) +var pug_has_own_property = Object.prototype.hasOwnProperty; -const ext = (a, b = {}) => { - const t = {} - Object.keys(a).forEach(k => t[k] = a[k]) - Object.keys(b).forEach(k => t[k] = b[k]) - return t -} +/** + * Merge two attribute objects giving precedence + * to values in object `b`. Classes are special-cased + * allowing for arrays and merging/joining appropriately + * resulting in a string. + * + * @param {Object} a + * @param {Object} b + * @return {Object} a + * @api private + */ -minimatch.defaults = def => { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch +exports.merge = pug_merge; +function pug_merge(a, b) { + if (arguments.length === 1) { + var attrs = a[0]; + for (var i = 1; i < a.length; i++) { + attrs = pug_merge(attrs, a[i]); + } + return attrs; } - const orig = minimatch - - const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) - m.Minimatch = class Minimatch extends orig.Minimatch { - constructor (pattern, options) { - super(pattern, ext(def, options)) + for (var key in b) { + if (key === 'class') { + var valA = a[key] || []; + a[key] = (Array.isArray(valA) ? valA : [valA]).concat(b[key] || []); + } else if (key === 'style') { + var valA = pug_style(a[key]); + valA = valA && valA[valA.length - 1] !== ';' ? valA + ';' : valA; + var valB = pug_style(b[key]); + valB = valB && valB[valB.length - 1] !== ';' ? valB + ';' : valB; + a[key] = valA + valB; + } else { + a[key] = b[key]; } } - m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch - m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) - m.defaults = options => orig.defaults(ext(def, options)) - m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) - m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) - m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) - return m + return a; } - - - - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) - -const braceExpand = (pattern, options = {}) => { - assertValidPattern(pattern) - - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] +/** + * Process array, object, or string as a string of classes delimited by a space. + * + * If `val` is an array, all members of it and its subarrays are counted as + * classes. If `escaping` is an array, then whether or not the item in `val` is + * escaped depends on the corresponding item in `escaping`. If `escaping` is + * not an array, no escaping is done. + * + * If `val` is an object, all the keys whose value is truthy are counted as + * classes. No escaping is done. + * + * If `val` is a string, it is counted as a class. No escaping is done. + * + * @param {(Array.|Object.|string)} val + * @param {?Array.} escaping + * @return {String} + */ +exports.classes = pug_classes; +function pug_classes_array(val, escaping) { + var classString = '', + className, + padding = '', + escapeEnabled = Array.isArray(escaping); + for (var i = 0; i < val.length; i++) { + className = pug_classes(val[i]); + if (!className) continue; + escapeEnabled && escaping[i] && (className = pug_escape(className)); + classString = classString + padding + className; + padding = ' '; } - - return expand(pattern) + return classString; } - -const MAX_PATTERN_LENGTH = 1024 * 64 -const assertValidPattern = pattern => { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } - - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') +function pug_classes_object(val) { + var classString = '', + padding = ''; + for (var key in val) { + if (key && val[key] && pug_has_own_property.call(val, key)) { + classString = classString + padding + key; + padding = ' '; + } } + return classString; } - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -const SUBPARSE = Symbol('subparse') - -minimatch.makeRe = (pattern, options) => - new Minimatch(pattern, options || {}).makeRe() - -minimatch.match = (list, pattern, options = {}) => { - const mm = new Minimatch(pattern, options) - list = list.filter(f => mm.match(f)) - if (mm.options.nonull && !list.length) { - list.push(pattern) +function pug_classes(val, escaping) { + if (Array.isArray(val)) { + return pug_classes_array(val, escaping); + } else if (val && typeof val === 'object') { + return pug_classes_object(val); + } else { + return val || ''; } - return list } -// replace stuff like \* with * -const globUnescape = s => s.replace(/\\(.)/g, '$1') -const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') -const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') - -class Minimatch { - constructor (pattern, options) { - assertValidPattern(pattern) - - if (!options) options = {} +/** + * Convert object or string to a string of CSS styles delimited by a semicolon. + * + * @param {(Object.|string)} val + * @return {String} + */ - this.options = options - this.set = [] - this.pattern = pattern - this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || - options.allowWindowsEscape === false - if (this.windowsPathsNoEscape) { - this.pattern = this.pattern.replace(/\\/g, '/') +exports.style = pug_style; +function pug_style(val) { + if (!val) return ''; + if (typeof val === 'object') { + var out = ''; + for (var style in val) { + /* istanbul ignore else */ + if (pug_has_own_property.call(val, style)) { + out = out + style + ':' + val[style] + ';'; + } } - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial - - // make the set of regexps etc. - this.make() + return out; + } else { + return val + ''; } +} - debug () {} - - make () { - const pattern = this.pattern - const options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - let set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = (...args) => console.error(...args) - - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(s => s.split(slashSplit)) - - this.debug(this.pattern, set) - - // glob --> regexps - set = set.map((s, si, set) => s.map(this.parse, this)) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(s => s.indexOf(false) === -1) - - this.debug(this.pattern, set) - - this.set = set +/** + * Render the given attribute. + * + * @param {String} key + * @param {String} val + * @param {Boolean} escaped + * @param {Boolean} terse + * @return {String} + */ +exports.attr = pug_attr; +function pug_attr(key, val, escaped, terse) { + if ( + val === false || + val == null || + (!val && (key === 'class' || key === 'style')) + ) { + return ''; } - - parseNegate () { - if (this.options.nonegate) return - - const pattern = this.pattern - let negate = false - let negateOffset = 0 - - for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { - negate = !negate - negateOffset++ + if (val === true) { + return ' ' + (terse ? key : key + '="' + key + '"'); + } + var type = typeof val; + if ( + (type === 'object' || type === 'function') && + typeof val.toJSON === 'function' + ) { + val = val.toJSON(); + } + if (typeof val !== 'string') { + val = JSON.stringify(val); + if (!escaped && val.indexOf('"') !== -1) { + return ' ' + key + "='" + val.replace(/'/g, ''') + "'"; } - - if (negateOffset) this.pattern = pattern.slice(negateOffset) - this.negate = negate } + if (escaped) val = pug_escape(val); + return ' ' + key + '="' + val + '"'; +} - // set partial to true to test if, for example, - // "/a/b" matches the start of "/*/b/*/d" - // Partial means, if you run out of file before you run - // out of pattern, then that's fine, as long as all - // the parts match. - matchOne (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } +/** + * Render the given attributes object. + * + * @param {Object} obj + * @param {Object} terse whether to use HTML5 terse boolean attributes + * @return {String} + */ +exports.attrs = pug_attrs; +function pug_attrs(obj, terse) { + var attrs = ''; - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + for (var key in obj) { + if (pug_has_own_property.call(obj, key)) { + var val = obj[key]; - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false + if ('class' === key) { + val = pug_classes(val); + attrs = pug_attr(key, val, false, terse) + attrs; + continue; } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - hit = f === p - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + if ('style' === key) { + val = pug_style(val); } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else /* istanbul ignore else */ if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - return (fi === fl - 1) && (file[fi] === '') + attrs += pug_attr(key, val, false, terse); } - - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') - } - - braceExpand () { - return braceExpand(this.pattern, this.options) } - parse (pattern, isSub) { - assertValidPattern(pattern) - - const options = this.options - - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' + return attrs; +} - let re = '' - let hasMagic = false - let escaping = false - // ? => one single character - const patternListStack = [] - const negativeLists = [] - let stateChar - let inClass = false - let reClassStart = -1 - let classStart = -1 - let cs - let pl - let sp - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. However, if the pattern - // starts with ., then traversal patterns can match. - let dotTravAllowed = pattern.charAt(0) === '.' - let dotFileAllowed = options.dot || dotTravAllowed - const patternStart = () => - dotTravAllowed - ? '' - : dotFileAllowed - ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' - : '(?!\\.)' - const subPatternStart = (p) => - p.charAt(0) === '.' - ? '' - : options.dot - ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' - : '(?!\\.)' +/** + * Escape the given string of `html`. + * + * @param {String} html + * @return {String} + * @api private + */ +var pug_match_html = /["&<>]/; +exports.escape = pug_escape; +function pug_escape(_html) { + var html = '' + _html; + var regexResult = pug_match_html.exec(html); + if (!regexResult) return _html; - const clearStateChar = () => { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - this.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } + var result = ''; + var i, lastIndex, escape; + for (i = regexResult.index, lastIndex = 0; i < html.length; i++) { + switch (html.charCodeAt(i)) { + case 34: + escape = '"'; + break; + case 38: + escape = '&'; + break; + case 60: + escape = '<'; + break; + case 62: + escape = '>'; + break; + default: + continue; } + if (lastIndex !== i) result += html.substring(lastIndex, i); + lastIndex = i + 1; + result += escape; + } + if (lastIndex !== i) return result + html.substring(lastIndex, i); + else return result; +} - for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping) { - /* istanbul ignore next - completely not allowed, even escaped. */ - if (c === '/') { - return false - } - - if (reSpecials[c]) { - re += '\\' - } - re += c - escaping = false - continue - } - - switch (c) { - /* istanbul ignore next */ - case '/': { - // Should already be path-split by now. - return false - } - - case '\\': - if (inClass && pattern.charAt(i + 1) === '-') { - re += c - continue - } - - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - this.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': { - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - const plEntry = { - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close, - } - this.debug(this.pattern, '\t', plEntry) - patternListStack.push(plEntry) - // negation is (?:(?!(?:js)(?:))[^/]*) - re += plEntry.open - // next entry starts with a dot maybe? - if (plEntry.start === 0 && plEntry.type !== '!') { - dotTravAllowed = true - re += subPatternStart(pattern.slice(i + 1)) - } - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - } - - case ')': { - const plEntry = patternListStack[patternListStack.length - 1] - if (inClass || !plEntry) { - re += '\\)' - continue - } - patternListStack.pop() - - // closing an extglob - clearStateChar() - hasMagic = true - pl = plEntry - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(Object.assign(pl, { reEnd: re.length })) - } - continue - } - - case '|': { - const plEntry = patternListStack[patternListStack.length - 1] - if (inClass || !plEntry) { - re += '\\|' - continue - } - - clearStateChar() - re += '|' - // next subpattern can start with a dot? - if (plEntry.start === 0 && plEntry.type !== '!') { - dotTravAllowed = true - re += subPatternStart(pattern.slice(i + 1)) - } - continue - } - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() +/** + * Re-throw the given `err` in context to the + * the pug in `filename` at the given `lineno`. + * + * @param {Error} err + * @param {String} filename + * @param {String} lineno + * @param {String} str original source + * @api private + */ - if (inClass) { - re += '\\' + c - continue - } +exports.rethrow = pug_rethrow; +function pug_rethrow(err, filename, lineno, str) { + if (!(err instanceof Error)) throw err; + if ((typeof window != 'undefined' || !filename) && !str) { + err.message += ' on line ' + lineno; + throw err; + } + var context, lines, start, end; + try { + str = str || (__nccwpck_require__(57147).readFileSync)(filename, {encoding: 'utf8'}); + context = 3; + lines = str.split('\n'); + start = Math.max(lineno - context, 0); + end = Math.min(lines.length, lineno + context); + } catch (ex) { + err.message += + ' - could not read from ' + filename + ' (' + ex.message + ')'; + pug_rethrow(err, null, lineno); + return; + } - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + // Error context + context = lines + .slice(start, end) + .map(function(line, i) { + var curr = i + start + 1; + return (curr == lineno ? ' > ' : ' ') + curr + '| ' + line; + }) + .join('\n'); - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - continue - } + // Alter exception message + err.path = filename; + try { + err.message = + (filename || 'Pug') + + ':' + + lineno + + '\n' + + context + + '\n\n' + + err.message; + } catch (e) {} + throw err; +} - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + braExpEscape(charUnescape(cs)) + ']') - // looks good, finish up the class. - re += c - } catch (er) { - // out of order ranges in JS are errors, but in glob syntax, - // they're just a range that matches nothing. - re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever - } - hasMagic = true - inClass = false - continue - default: - // swallow any state char that wasn't consumed - clearStateChar() +/***/ }), - if (reSpecials[c] && !(c === '^' && inClass)) { - re += '\\' - } +/***/ 41222: +/***/ ((module) => { - re += c - break +module.exports = { + "has_own_property": [], + "merge": [ + "style" + ], + "classes_array": [ + "classes", + "escape" + ], + "classes_object": [ + "has_own_property" + ], + "classes": [ + "classes_array", + "classes_object" + ], + "style": [ + "has_own_property" + ], + "attr": [ + "escape" + ], + "attrs": [ + "attr", + "classes", + "has_own_property", + "style" + ], + "match_html": [], + "escape": [ + "match_html" + ], + "rethrow": [] +} - } // switch - } // for - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.slice(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substring(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } +/***/ }), - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - let tail - tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { - /* istanbul ignore else - should already be done */ - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } +/***/ 373: +/***/ ((module) => { - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +module.exports = { + "dependencies": true, + "internals": true, + "has_own_property": true, + "classes_array": true, + "classes_object": true, + "match_html": true +} - this.debug('tail=%j\n %s', tail, tail, pl, re) - const t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } +/***/ }), - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +/***/ 21003: +/***/ ((module) => { - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - const addPatternStart = addPatternStartSet[re.charAt(0)] +module.exports = { + "has_own_property": "var pug_has_own_property=Object.prototype.hasOwnProperty;", + "merge": "function pug_merge(e,r){if(1===arguments.length){for(var t=e[0],g=1;g]/;", + "escape": "function pug_escape(e){var a=\"\"+e,t=pug_match_html.exec(a);if(!t)return e;var r,c,n,s=\"\";for(r=t.index,c=0;r \":\" \")+t+\"| \"+e}).join(\"\\n\"),e.path=n;try{e.message=(n||\"Pug\")+\":\"+r+\"\\n\"+o+\"\\n\\n\"+e.message}catch(e){}throw e}" +} - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (let n = negativeLists.length - 1; n > -1; n--) { - const nl = negativeLists[n] - const nlBefore = re.slice(0, nl.reStart) - const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - let nlAfter = re.slice(nl.reEnd) - const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter +/***/ }), - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - const closeParensBefore = nlBefore.split(')').length - const openParensBefore = nlBefore.split('(').length - closeParensBefore - let cleanAfter = nlAfter - for (let i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter +/***/ 60010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' +var runtime = __nccwpck_require__(27596); - re = nlBefore + nlFirst + nlAfter + dollar + nlLast - } +module.exports = wrap; +function wrap(template, templateName) { + templateName = templateName || 'template'; + return Function( + 'pug', + template + '\n' + 'return ' + templateName + ';' + )(runtime); +} - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - if (addPatternStart) { - re = patternStart() + re - } +/***/ }), - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } +/***/ 45413: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // if it's nocase, and the lcase/uppercase don't match, it's magic - if (options.nocase && !hasMagic) { - hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() - } +"use strict"; - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - const flags = options.nocase ? 'i' : '' - try { - return Object.assign(new RegExp('^' + re + '$', flags), { - _glob: pattern, - _src: re, - }) - } catch (er) /* istanbul ignore next - should be impossible */ { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - } +var error = __nccwpck_require__(11449); - makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +module.exports = stripComments; - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - const set = this.set +function unexpectedToken(type, occasion, filename, line) { + var msg = '`' + type + '` encountered when ' + occasion; + throw error('UNEXPECTED_TOKEN', msg, {filename: filename, line: line}); +} - if (!set.length) { - this.regexp = false - return this.regexp - } - const options = this.options +function stripComments(input, options) { + options = options || {}; - const twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - const flags = options.nocase ? 'i' : '' + // Default: strip unbuffered comments and leave buffered ones alone + var stripUnbuffered = options.stripUnbuffered !== false; + var stripBuffered = options.stripBuffered === true; + var filename = options.filename; - // coalesce globstars and regexpify non-globstar patterns - // if it's the only item, then we just do one twoStar - // if it's the first, and there are more, prepend (\/|twoStar\/)? to next - // if it's the last, append (\/twoStar|) to previous - // if it's in the middle, append (\/|\/twoStar\/) to previous - // then filter out GLOBSTAR symbols - let re = set.map(pattern => { - pattern = pattern.map(p => - typeof p === 'string' ? regExpEscape(p) - : p === GLOBSTAR ? GLOBSTAR - : p._src - ).reduce((set, p) => { - if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { - set.push(p) + var out = []; + // If we have encountered a comment token and are not sure if we have gotten + // out of the comment or not + var inComment = false; + // If we are sure that we are in a block comment and all tokens except + // `end-pipeless-text` should be ignored + var inPipelessText = false; + + return input.filter(function(tok) { + switch (tok.type) { + case 'comment': + if (inComment) { + unexpectedToken( + 'comment', + 'already in a comment', + filename, + tok.line + ); + } else { + inComment = tok.buffer ? stripBuffered : stripUnbuffered; + return !inComment; } - return set - }, []) - pattern.forEach((p, i) => { - if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { - return + case 'start-pipeless-text': + if (!inComment) return true; + if (inPipelessText) { + unexpectedToken( + 'start-pipeless-text', + 'already in pipeless text mode', + filename, + tok.line + ); } - if (i === 0) { - if (pattern.length > 1) { - pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] - } else { - pattern[i] = twoStar - } - } else if (i === pattern.length - 1) { - pattern[i-1] += '(?:\\\/|' + twoStar + ')?' - } else { - pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] - pattern[i+1] = GLOBSTAR + inPipelessText = true; + return false; + case 'end-pipeless-text': + if (!inComment) return true; + if (!inPipelessText) { + unexpectedToken( + 'end-pipeless-text', + 'not in pipeless text mode', + filename, + tok.line + ); } - }) - return pattern.filter(p => p !== GLOBSTAR).join('/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false + inPipelessText = false; + inComment = false; + return false; + // There might be a `text` right after `comment` but before + // `start-pipeless-text`. Treat it accordingly. + case 'text': + return !inComment; + default: + if (inPipelessText) return false; + inComment = false; + return true; } - return this.regexp - } + }); +} - match (f, partial = this.partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - if (f === '/' && partial) return true +/***/ }), - const options = this.options +/***/ 60283: +/***/ ((module) => { - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } +"use strict"; - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. +module.exports = walkAST; +function walkAST(ast, before, after, options) { + if (after && typeof after === 'object' && typeof options === 'undefined') { + options = after; + after = null; + } + options = options || {includeDependencies: false}; + var parents = (options.parents = options.parents || []); - const set = this.set - this.debug(this.pattern, 'set', set) + var replace = function replace(replacement) { + if (Array.isArray(replacement) && !replace.arrayAllowed) { + throw new Error( + 'replace() can only be called with an array if the last parent is a Block or NamedBlock' + ); + } + ast = replacement; + }; + replace.arrayAllowed = + parents[0] && + (/^(Named)?Block$/.test(parents[0].type) || + (parents[0].type === 'RawInclude' && ast.type === 'IncludeFilter')); - // Find the basename of the path by looking for the last non-empty segment - let filename - for (let i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break + if (before) { + var result = before(ast, replace); + if (result === false) { + return ast; + } else if (Array.isArray(ast)) { + // return right here to skip after() call on array + return walkAndMergeNodes(ast); } + } - for (let i = 0; i < set.length; i++) { - const pattern = set[i] - let file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] + parents.unshift(ast); + + switch (ast.type) { + case 'NamedBlock': + case 'Block': + ast.nodes = walkAndMergeNodes(ast.nodes); + break; + case 'Case': + case 'Filter': + case 'Mixin': + case 'Tag': + case 'InterpolatedTag': + case 'When': + case 'Code': + case 'While': + if (ast.block) { + ast.block = walkAST(ast.block, before, after, options); } - const hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + break; + case 'Each': + if (ast.block) { + ast.block = walkAST(ast.block, before, after, options); } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate + if (ast.alternate) { + ast.alternate = walkAST(ast.alternate, before, after, options); + } + break; + case 'EachOf': + if (ast.block) { + ast.block = walkAST(ast.block, before, after, options); + } + break; + case 'Conditional': + if (ast.consequent) { + ast.consequent = walkAST(ast.consequent, before, after, options); + } + if (ast.alternate) { + ast.alternate = walkAST(ast.alternate, before, after, options); + } + break; + case 'Include': + walkAST(ast.block, before, after, options); + walkAST(ast.file, before, after, options); + break; + case 'Extends': + walkAST(ast.file, before, after, options); + break; + case 'RawInclude': + ast.filters = walkAndMergeNodes(ast.filters); + walkAST(ast.file, before, after, options); + break; + case 'Attrs': + case 'BlockComment': + case 'Comment': + case 'Doctype': + case 'IncludeFilter': + case 'MixinBlock': + case 'YieldBlock': + case 'Text': + break; + case 'FileReference': + if (options.includeDependencies && ast.ast) { + walkAST(ast.ast, before, after, options); + } + break; + default: + throw new Error('Unexpected node type ' + ast.type); + break; } - static defaults (def) { - return minimatch.defaults(def).Minimatch + parents.shift(); + + after && after(ast, replace); + return ast; + + function walkAndMergeNodes(nodes) { + return nodes.reduce(function(nodes, node) { + var result = walkAST(node, before, after, options); + if (Array.isArray(result)) { + return nodes.concat(result); + } else { + return nodes.concat([result]); + } + }, []); } } -minimatch.Minimatch = Minimatch - /***/ }), -/***/ 96976: -/***/ ((module) => { +/***/ 40316: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; + + /*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. + * Pug + * Copyright(c) 2010 TJ Holowaychuk + * MIT Licensed */ +/** + * Module dependencies. + */ +var fs = __nccwpck_require__(57147); +var path = __nccwpck_require__(71017); +var lex = __nccwpck_require__(32428); +var stripComments = __nccwpck_require__(45413); +var parse = __nccwpck_require__(40558); +var load = __nccwpck_require__(44254); +var filters = __nccwpck_require__(69309); +var link = __nccwpck_require__(63234); +var generateCode = __nccwpck_require__(90331); +var runtime = __nccwpck_require__(27596); +var runtimeWrap = __nccwpck_require__(60010); /** - * Results cache + * Name for detection */ -var res = ''; -var cache; +exports.name = 'Pug'; /** - * Expose `repeat` + * Pug runtime helpers. */ -module.exports = repeat; +exports.runtime = runtime; /** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` - * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public + * Template function cache. */ -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } - - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; +exports.cache = {}; - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } else if (res.length >= max) { - return res.substr(0, max); - } +function applyPlugins(value, options, plugins, name) { + return plugins.reduce(function(value, plugin) { + return plugin[name] ? plugin[name](value, options) : value; + }, value); +} - while (max > res.length && num > 1) { - if (num & 1) { - res += str; - } +function findReplacementFunc(plugins, name) { + var eligiblePlugins = plugins.filter(function(plugin) { + return plugin[name]; + }); - num >>= 1; - str += str; + if (eligiblePlugins.length > 1) { + throw new Error('Two or more plugins all implement ' + name + ' method.'); + } else if (eligiblePlugins.length) { + return eligiblePlugins[0][name].bind(eligiblePlugins[0]); } - - res += str; - res = res.substr(0, max); - return res; + return null; } +/** + * Object for global custom filters. Note that you can also just pass a `filters` + * option to any other method. + */ +exports.filters = {}; -/***/ }), - -/***/ 65444: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/** + * Compile the given `str` of pug and return a function body. + * + * @param {String} str + * @param {Object} options + * @return {Object} + * @api private + */ +function compileBody(str, options) { + var debug_sources = {}; + debug_sources[options.filename] = str; + var dependencies = []; + var plugins = options.plugins || []; + var ast = load.string(str, { + filename: options.filename, + basedir: options.basedir, + lex: function(str, options) { + var lexOptions = {}; + Object.keys(options).forEach(function(key) { + lexOptions[key] = options[key]; + }); + lexOptions.plugins = plugins + .filter(function(plugin) { + return !!plugin.lex; + }) + .map(function(plugin) { + return plugin.lex; + }); + var contents = applyPlugins( + str, + {filename: options.filename}, + plugins, + 'preLex' + ); + return applyPlugins( + lex(contents, lexOptions), + options, + plugins, + 'postLex' + ); + }, + parse: function(tokens, options) { + tokens = tokens.map(function(token) { + if (token.type === 'path' && path.extname(token.val) === '') { + return { + type: 'path', + loc: token.loc, + val: token.val + '.pug', + }; + } + return token; + }); + tokens = stripComments(tokens, options); + tokens = applyPlugins(tokens, options, plugins, 'preParse'); + var parseOptions = {}; + Object.keys(options).forEach(function(key) { + parseOptions[key] = options[key]; + }); + parseOptions.plugins = plugins + .filter(function(plugin) { + return !!plugin.parse; + }) + .map(function(plugin) { + return plugin.parse; + }); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'abap', - init: function init(Prism) { - Prism.languages.abap = { - comment: /^\*.*/m, - string: /(`|')(?:\\.|(?!\1)[^\\\r\n])*\1/m, - 'string-template': { - pattern: /([|}])(?:\\.|[^\\|{\r\n])*(?=[|{])/, - lookbehind: true, - alias: 'string' - }, - /* End Of Line comments should not interfere with strings when the - quote character occurs within them. We assume a string being highlighted - inside an EOL comment is more acceptable than the opposite. - */ - 'eol-comment': { - pattern: /(^|\s)".*/m, - lookbehind: true, - alias: 'comment' - }, - keyword: { - pattern: /(\s|\.|^)(?:SCIENTIFIC_WITH_LEADING_ZERO|SCALE_PRESERVING_SCIENTIFIC|RMC_COMMUNICATION_FAILURE|END-ENHANCEMENT-SECTION|MULTIPLY-CORRESPONDING|SUBTRACT-CORRESPONDING|VERIFICATION-MESSAGE|DIVIDE-CORRESPONDING|ENHANCEMENT-SECTION|CURRENCY_CONVERSION|RMC_SYSTEM_FAILURE|START-OF-SELECTION|MOVE-CORRESPONDING|RMC_INVALID_STATUS|CUSTOMER-FUNCTION|END-OF-DEFINITION|ENHANCEMENT-POINT|SYSTEM-EXCEPTIONS|ADD-CORRESPONDING|SCALE_PRESERVING|SELECTION-SCREEN|CURSOR-SELECTION|END-OF-SELECTION|LOAD-OF-PROGRAM|SCROLL-BOUNDARY|SELECTION-TABLE|EXCEPTION-TABLE|IMPLEMENTATIONS|PARAMETER-TABLE|RIGHT-JUSTIFIED|UNIT_CONVERSION|AUTHORITY-CHECK|LIST-PROCESSING|SIGN_AS_POSTFIX|COL_BACKGROUND|IMPLEMENTATION|INTERFACE-POOL|TRANSFORMATION|IDENTIFICATION|ENDENHANCEMENT|LINE-SELECTION|INITIALIZATION|LEFT-JUSTIFIED|SELECT-OPTIONS|SELECTION-SETS|COMMUNICATION|CORRESPONDING|DECIMAL_SHIFT|PRINT-CONTROL|VALUE-REQUEST|CHAIN-REQUEST|FUNCTION-POOL|FIELD-SYMBOLS|FUNCTIONALITY|INVERTED-DATE|SELECTION-SET|CLASS-METHODS|OUTPUT-LENGTH|CLASS-CODING|COL_NEGATIVE|ERRORMESSAGE|FIELD-GROUPS|HELP-REQUEST|NO-EXTENSION|NO-TOPOFPAGE|REDEFINITION|DISPLAY-MODE|ENDINTERFACE|EXIT-COMMAND|FIELD-SYMBOL|NO-SCROLLING|SHORTDUMP-ID|ACCESSPOLICY|CLASS-EVENTS|COL_POSITIVE|DECLARATIONS|ENHANCEMENTS|FILTER-TABLE|SWITCHSTATES|SYNTAX-CHECK|TRANSPORTING|ASYNCHRONOUS|SYNTAX-TRACE|TOKENIZATION|USER-COMMAND|WITH-HEADING|ABAP-SOURCE|BREAK-POINT|CHAIN-INPUT|COMPRESSION|FIXED-POINT|NEW-SECTION|NON-UNICODE|OCCURRENCES|RESPONSIBLE|SYSTEM-CALL|TRACE-TABLE|ABBREVIATED|CHAR-TO-HEX|END-OF-FILE|ENDFUNCTION|ENVIRONMENT|ASSOCIATION|COL_HEADING|EDITOR-CALL|END-OF-PAGE|ENGINEERING|IMPLEMENTED|INTENSIFIED|RADIOBUTTON|SYSTEM-EXIT|TOP-OF-PAGE|TRANSACTION|APPLICATION|CONCATENATE|DESTINATION|ENHANCEMENT|IMMEDIATELY|NO-GROUPING|PRECOMPILED|REPLACEMENT|TITLE-LINES|ACTIVATION|BYTE-ORDER|CLASS-POOL|CONNECTION|CONVERSION|DEFINITION|DEPARTMENT|EXPIRATION|INHERITING|MESSAGE-ID|NO-HEADING|PERFORMING|QUEUE-ONLY|RIGHTSPACE|SCIENTIFIC|STATUSINFO|STRUCTURES|SYNCPOINTS|WITH-TITLE|ATTRIBUTES|BOUNDARIES|CLASS-DATA|COL_NORMAL|DD\/MM\/YYYY|DESCENDING|INTERFACES|LINE-COUNT|MM\/DD\/YYYY|NON-UNIQUE|PRESERVING|SELECTIONS|STATEMENTS|SUBROUTINE|TRUNCATION|TYPE-POOLS|ARITHMETIC|BACKGROUND|ENDPROVIDE|EXCEPTIONS|IDENTIFIER|INDEX-LINE|OBLIGATORY|PARAMETERS|PERCENTAGE|PUSHBUTTON|RESOLUTION|COMPONENTS|DEALLOCATE|DISCONNECT|DUPLICATES|FIRST-LINE|HEAD-LINES|NO-DISPLAY|OCCURRENCE|RESPECTING|RETURNCODE|SUBMATCHES|TRACE-FILE|ASCENDING|BYPASSING|ENDMODULE|EXCEPTION|EXCLUDING|EXPORTING|INCREMENT|MATCHCODE|PARAMETER|PARTIALLY|PREFERRED|REFERENCE|REPLACING|RETURNING|SELECTION|SEPARATED|SPECIFIED|STATEMENT|TIMESTAMP|TYPE-POOL|ACCEPTING|APPENDAGE|ASSIGNING|COL_GROUP|COMPARING|CONSTANTS|DANGEROUS|IMPORTING|INSTANCES|LEFTSPACE|LOG-POINT|QUICKINFO|READ-ONLY|SCROLLING|SQLSCRIPT|STEP-LOOP|TOP-LINES|TRANSLATE|APPENDING|AUTHORITY|CHARACTER|COMPONENT|CONDITION|DIRECTORY|DUPLICATE|MESSAGING|RECEIVING|SUBSCREEN|ACCORDING|COL_TOTAL|END-LINES|ENDMETHOD|ENDSELECT|EXPANDING|EXTENSION|INCLUDING|INFOTYPES|INTERFACE|INTERVALS|LINE-SIZE|PF-STATUS|PROCEDURE|PROTECTED|REQUESTED|RESUMABLE|RIGHTPLUS|SAP-SPOOL|SECONDARY|STRUCTURE|SUBSTRING|TABLEVIEW|NUMOFCHAR|ADJACENT|ANALYSIS|ASSIGNED|BACKWARD|CHANNELS|CHECKBOX|CONTINUE|CRITICAL|DATAINFO|DD\/MM\/YY|DURATION|ENCODING|ENDCLASS|FUNCTION|LEFTPLUS|LINEFEED|MM\/DD\/YY|OVERFLOW|RECEIVED|SKIPPING|SORTABLE|STANDARD|SUBTRACT|SUPPRESS|TABSTRIP|TITLEBAR|TRUNCATE|UNASSIGN|WHENEVER|ANALYZER|COALESCE|COMMENTS|CONDENSE|DECIMALS|DEFERRED|ENDWHILE|EXPLICIT|KEYWORDS|MESSAGES|POSITION|PRIORITY|RECEIVER|RENAMING|TIMEZONE|TRAILING|ALLOCATE|CENTERED|CIRCULAR|CONTROLS|CURRENCY|DELETING|DESCRIBE|DISTANCE|ENDCATCH|EXPONENT|EXTENDED|GENERATE|IGNORING|INCLUDES|INTERNAL|MAJOR-ID|MODIFIER|NEW-LINE|OPTIONAL|PROPERTY|ROLLBACK|STARTING|SUPPLIED|ABSTRACT|CHANGING|CONTEXTS|CREATING|CUSTOMER|DATABASE|DAYLIGHT|DEFINING|DISTINCT|DIVISION|ENABLING|ENDCHAIN|ESCAPING|HARMLESS|IMPLICIT|INACTIVE|LANGUAGE|MINOR-ID|MULTIPLY|NEW-PAGE|NO-TITLE|POS_HIGH|SEPARATE|TEXTPOOL|TRANSFER|SELECTOR|DBMAXLEN|ITERATOR|SELECTOR|ARCHIVE|BIT-XOR|BYTE-CO|COLLECT|COMMENT|CURRENT|DEFAULT|DISPLAY|ENDFORM|EXTRACT|LEADING|LISTBOX|LOCATOR|MEMBERS|METHODS|NESTING|POS_LOW|PROCESS|PROVIDE|RAISING|RESERVE|SECONDS|SUMMARY|VISIBLE|BETWEEN|BIT-AND|BYTE-CS|CLEANUP|COMPUTE|CONTROL|CONVERT|DATASET|ENDCASE|FORWARD|HEADERS|HOTSPOT|INCLUDE|INVERSE|KEEPING|NO-ZERO|OBJECTS|OVERLAY|PADDING|PATTERN|PROGRAM|REFRESH|SECTION|SUMMING|TESTING|VERSION|WINDOWS|WITHOUT|BIT-NOT|BYTE-CA|BYTE-NA|CASTING|CONTEXT|COUNTRY|DYNAMIC|ENABLED|ENDLOOP|EXECUTE|FRIENDS|HANDLER|HEADING|INITIAL|\*-INPUT|LOGFILE|MAXIMUM|MINIMUM|NO-GAPS|NO-SIGN|PRAGMAS|PRIMARY|PRIVATE|REDUCED|REPLACE|REQUEST|RESULTS|UNICODE|WARNING|ALIASES|BYTE-CN|BYTE-NS|CALLING|COL_KEY|COLUMNS|CONNECT|ENDEXEC|ENTRIES|EXCLUDE|FILTERS|FURTHER|HELP-ID|LOGICAL|MAPPING|MESSAGE|NAMETAB|OPTIONS|PACKAGE|PERFORM|RECEIVE|STATICS|VARYING|BINDING|CHARLEN|GREATER|XSTRLEN|ACCEPT|APPEND|DETAIL|ELSEIF|ENDING|ENDTRY|FORMAT|FRAMES|GIVING|HASHED|HEADER|IMPORT|INSERT|MARGIN|MODULE|NATIVE|OBJECT|OFFSET|REMOTE|RESUME|SAVING|SIMPLE|SUBMIT|TABBED|TOKENS|UNIQUE|UNPACK|UPDATE|WINDOW|YELLOW|ACTUAL|ASPECT|CENTER|CURSOR|DELETE|DIALOG|DIVIDE|DURING|ERRORS|EVENTS|EXTEND|FILTER|HANDLE|HAVING|IGNORE|LITTLE|MEMORY|NO-GAP|OCCURS|OPTION|PERSON|PLACES|PUBLIC|REDUCE|REPORT|RESULT|SINGLE|SORTED|SWITCH|SYNTAX|TARGET|VALUES|WRITER|ASSERT|BLOCKS|BOUNDS|BUFFER|CHANGE|COLUMN|COMMIT|CONCAT|COPIES|CREATE|DDMMYY|DEFINE|ENDIAN|ESCAPE|EXPAND|KERNEL|LAYOUT|LEGACY|LEVELS|MMDDYY|NUMBER|OUTPUT|RANGES|READER|RETURN|SCREEN|SEARCH|SELECT|SHARED|SOURCE|STABLE|STATIC|SUBKEY|SUFFIX|TABLES|UNWIND|YYMMDD|ASSIGN|BACKUP|BEFORE|BINARY|BIT-OR|BLANKS|CLIENT|CODING|COMMON|DEMAND|DYNPRO|EXCEPT|EXISTS|EXPORT|FIELDS|GLOBAL|GROUPS|LENGTH|LOCALE|MEDIUM|METHOD|MODIFY|NESTED|OTHERS|REJECT|SCROLL|SUPPLY|SYMBOL|ENDFOR|STRLEN|ALIGN|BEGIN|BOUND|ENDAT|ENTRY|EVENT|FINAL|FLUSH|GRANT|INNER|SHORT|USING|WRITE|AFTER|BLACK|BLOCK|CLOCK|COLOR|COUNT|DUMMY|EMPTY|ENDDO|ENDON|GREEN|INDEX|INOUT|LEAVE|LEVEL|LINES|MODIF|ORDER|OUTER|RANGE|RESET|RETRY|RIGHT|SMART|SPLIT|STYLE|TABLE|THROW|UNDER|UNTIL|UPPER|UTF-8|WHERE|ALIAS|BLANK|CLEAR|CLOSE|EXACT|FETCH|FIRST|FOUND|GROUP|LLANG|LOCAL|OTHER|REGEX|SPOOL|TITLE|TYPES|VALID|WHILE|ALPHA|BOXED|CATCH|CHAIN|CHECK|CLASS|COVER|ENDIF|EQUIV|FIELD|FLOOR|FRAME|INPUT|LOWER|MATCH|NODES|PAGES|PRINT|RAISE|ROUND|SHIFT|SPACE|SPOTS|STAMP|STATE|TASKS|TIMES|TRMAC|ULINE|UNION|VALUE|WIDTH|EQUAL|LOG10|TRUNC|BLOB|CASE|CEIL|CLOB|COND|EXIT|FILE|GAPS|HOLD|INCL|INTO|KEEP|KEYS|LAST|LINE|LONG|LPAD|MAIL|MODE|OPEN|PINK|READ|ROWS|TEST|THEN|ZERO|AREA|BACK|BADI|BYTE|CAST|EDIT|EXEC|FAIL|FIND|FKEQ|FONT|FREE|GKEQ|HIDE|INIT|ITNO|LATE|LOOP|MAIN|MARK|MOVE|NEXT|NULL|RISK|ROLE|UNIT|WAIT|ZONE|BASE|CALL|CODE|DATA|DATE|FKGE|GKGE|HIGH|KIND|LEFT|LIST|MASK|MESH|NAME|NODE|PACK|PAGE|POOL|SEND|SIGN|SIZE|SOME|STOP|TASK|TEXT|TIME|USER|VARY|WITH|WORD|BLUE|CONV|COPY|DEEP|ELSE|FORM|FROM|HINT|ICON|JOIN|LIKE|LOAD|ONLY|PART|SCAN|SKIP|SORT|TYPE|UNIX|VIEW|WHEN|WORK|ACOS|ASIN|ATAN|COSH|EACH|FRAC|LESS|RTTI|SINH|SQRT|TANH|AVG|BIT|DIV|ISO|LET|OUT|PAD|SQL|ALL|CI_|CPI|END|LOB|LPI|MAX|MIN|NEW|OLE|RUN|SET|\?TO|YES|ABS|ADD|AND|BIG|FOR|HDB|JOB|LOW|NOT|SAP|TRY|VIA|XML|ANY|GET|IDS|KEY|MOD|OFF|PUT|RAW|RED|REF|SUM|TAB|XSD|CNT|COS|EXP|LOG|SIN|TAN|XOR|AT|CO|CP|DO|GT|ID|IF|NS|OR|BT|CA|CS|GE|NA|NB|EQ|IN|LT|NE|NO|OF|ON|PF|TO|AS|BY|CN|IS|LE|NP|UP|E|I|M|O|Z|C|X)\b/i, - lookbehind: true - }, - /* Numbers can be only integers. Decimal or Hex appear only as strings */ - number: /\b\d+\b/, - /* Operators must always be surrounded by whitespace, they cannot be put - adjacent to operands. - */ - operator: { - pattern: /(\s)(?:\*\*?|<[=>]?|>=?|\?=|[-+\/=])(?=\s)/, - lookbehind: true - }, - 'string-operator': { - pattern: /(\s)&&?(?=\s)/, - lookbehind: true, - /* The official editor highlights */ - alias: 'keyword' - }, - 'token-operator': [{ - /* Special operators used to access structure components, class methods/attributes, etc. */ - pattern: /(\w)(?:->?|=>|[~|{}])(?=\w)/, - lookbehind: true, - alias: 'punctuation' - }, { - /* Special tokens used do delimit string templates */ - pattern: /[|{}]/, - alias: 'punctuation' - }], - punctuation: /[,.:()]/ - }; - } -}; + return applyPlugins( + applyPlugins( + parse(tokens, parseOptions), + options, + plugins, + 'postParse' + ), + options, + plugins, + 'preLoad' + ); + }, + resolve: function(filename, source, loadOptions) { + var replacementFunc = findReplacementFunc(plugins, 'resolve'); + if (replacementFunc) { + return replacementFunc(filename, source, options); + } -/***/ }), + return load.resolve(filename, source, loadOptions); + }, + read: function(filename, loadOptions) { + dependencies.push(filename); -/***/ 21019: -/***/ ((__unused_webpack_module, exports) => { + var contents; -"use strict"; + var replacementFunc = findReplacementFunc(plugins, 'read'); + if (replacementFunc) { + contents = replacementFunc(filename, options); + } else { + contents = load.read(filename, loadOptions); + } + debug_sources[filename] = Buffer.isBuffer(contents) + ? contents.toString('utf8') + : contents; + return contents; + }, + }); + ast = applyPlugins(ast, options, plugins, 'postLoad'); + ast = applyPlugins(ast, options, plugins, 'preFilters'); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'actionscript', - init: function init(Prism) { - Prism.languages.actionscript = Prism.languages.extend('javascript', { - keyword: /\b(?:as|break|case|catch|class|const|default|delete|do|else|extends|finally|for|function|if|implements|import|in|instanceof|interface|internal|is|native|new|null|package|private|protected|public|return|super|switch|this|throw|try|typeof|use|var|void|while|with|dynamic|each|final|get|include|namespace|native|override|set|static)\b/, - operator: /\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<>?>?|[!=]=?)=?|[~?@]/ + var filtersSet = {}; + Object.keys(exports.filters).forEach(function(key) { + filtersSet[key] = exports.filters[key]; + }); + if (options.filters) { + Object.keys(options.filters).forEach(function(key) { + filtersSet[key] = options.filters[key]; }); - Prism.languages.actionscript['class-name'].alias = 'function'; - - if (Prism.languages.markup) { - Prism.languages.insertBefore('actionscript', 'string', { - xml: { - pattern: /(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\[\s\S]|(?!\2)[^\\])*\2)*\s*\/?>/, - lookbehind: true, - inside: { - rest: Prism.languages.markup - } - } - }); - } } -}; - -/***/ }), - -/***/ 99040: -/***/ ((__unused_webpack_module, exports) => { + ast = filters.handleFilters( + ast, + filtersSet, + options.filterOptions, + options.filterAliases + ); -"use strict"; + ast = applyPlugins(ast, options, plugins, 'postFilters'); + ast = applyPlugins(ast, options, plugins, 'preLink'); + ast = link(ast); + ast = applyPlugins(ast, options, plugins, 'postLink'); + // Compile + ast = applyPlugins(ast, options, plugins, 'preCodeGen'); + var js = (findReplacementFunc(plugins, 'generateCode') || generateCode)(ast, { + pretty: options.pretty, + compileDebug: options.compileDebug, + doctype: options.doctype, + inlineRuntimeFunctions: options.inlineRuntimeFunctions, + globals: options.globals, + self: options.self, + includeSources: options.includeSources ? debug_sources : false, + templateName: options.templateName, + }); + js = applyPlugins(js, options, plugins, 'postCodeGen'); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'ada', - init: function init(Prism) { - Prism.languages.ada = { - comment: /--.*/, - string: /"(?:""|[^"\r\f\n])*"/i, - number: [{ - pattern: /\b\d(?:_?\d)*#[\dA-F](?:_?[\dA-F])*(?:\.[\dA-F](?:_?[\dA-F])*)?#(?:E[+-]?\d(?:_?\d)*)?/i - }, { - pattern: /\b\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:E[+-]?\d(?:_?\d)*)?\b/i - }], - 'attr-name': /\b'\w+/i, - keyword: /\b(?:abort|abs|abstract|accept|access|aliased|all|and|array|at|begin|body|case|constant|declare|delay|delta|digits|do|else|new|return|elsif|end|entry|exception|exit|for|function|generic|goto|if|in|interface|is|limited|loop|mod|not|null|of|others|out|overriding|package|pragma|private|procedure|protected|raise|range|record|rem|renames|requeue|reverse|select|separate|some|subtype|synchronized|tagged|task|terminate|then|type|until|use|when|while|with|xor)\b/i, - boolean: /\b(?:true|false)\b/i, - operator: /<[=>]?|>=?|=>?|:=|\/=?|\*\*?|[&+-]/, - punctuation: /\.\.?|[,;():]/, - char: /'.'/, - variable: /\b[a-z](?:[_a-z\d])*\b/i - }; + // Debug compiler + if (options.debug) { + console.error( + '\nCompiled Function:\n\n\u001b[90m%s\u001b[0m', + js.replace(/^/gm, ' ') + ); } -}; - -/***/ }), - -/***/ 70629: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + return {body: js, dependencies: dependencies}; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'apacheconf', - init: function init(Prism) { - Prism.languages.apacheconf = { - comment: /#.*/, - 'directive-inline': { - pattern: /^(\s*)\b(?:AcceptFilter|AcceptPathInfo|AccessFileName|Action|AddAlt|AddAltByEncoding|AddAltByType|AddCharset|AddDefaultCharset|AddDescription|AddEncoding|AddHandler|AddIcon|AddIconByEncoding|AddIconByType|AddInputFilter|AddLanguage|AddModuleInfo|AddOutputFilter|AddOutputFilterByType|AddType|Alias|AliasMatch|Allow|AllowCONNECT|AllowEncodedSlashes|AllowMethods|AllowOverride|AllowOverrideList|Anonymous|Anonymous_LogEmail|Anonymous_MustGiveEmail|Anonymous_NoUserID|Anonymous_VerifyEmail|AsyncRequestWorkerFactor|AuthBasicAuthoritative|AuthBasicFake|AuthBasicProvider|AuthBasicUseDigestAlgorithm|AuthDBDUserPWQuery|AuthDBDUserRealmQuery|AuthDBMGroupFile|AuthDBMType|AuthDBMUserFile|AuthDigestAlgorithm|AuthDigestDomain|AuthDigestNonceLifetime|AuthDigestProvider|AuthDigestQop|AuthDigestShmemSize|AuthFormAuthoritative|AuthFormBody|AuthFormDisableNoStore|AuthFormFakeBasicAuth|AuthFormLocation|AuthFormLoginRequiredLocation|AuthFormLoginSuccessLocation|AuthFormLogoutLocation|AuthFormMethod|AuthFormMimetype|AuthFormPassword|AuthFormProvider|AuthFormSitePassphrase|AuthFormSize|AuthFormUsername|AuthGroupFile|AuthLDAPAuthorizePrefix|AuthLDAPBindAuthoritative|AuthLDAPBindDN|AuthLDAPBindPassword|AuthLDAPCharsetConfig|AuthLDAPCompareAsUser|AuthLDAPCompareDNOnServer|AuthLDAPDereferenceAliases|AuthLDAPGroupAttribute|AuthLDAPGroupAttributeIsDN|AuthLDAPInitialBindAsUser|AuthLDAPInitialBindPattern|AuthLDAPMaxSubGroupDepth|AuthLDAPRemoteUserAttribute|AuthLDAPRemoteUserIsDN|AuthLDAPSearchAsUser|AuthLDAPSubGroupAttribute|AuthLDAPSubGroupClass|AuthLDAPUrl|AuthMerging|AuthName|AuthnCacheContext|AuthnCacheEnable|AuthnCacheProvideFor|AuthnCacheSOCache|AuthnCacheTimeout|AuthnzFcgiCheckAuthnProvider|AuthnzFcgiDefineProvider|AuthType|AuthUserFile|AuthzDBDLoginToReferer|AuthzDBDQuery|AuthzDBDRedirectQuery|AuthzDBMType|AuthzSendForbiddenOnFailure|BalancerGrowth|BalancerInherit|BalancerMember|BalancerPersist|BrowserMatch|BrowserMatchNoCase|BufferedLogs|BufferSize|CacheDefaultExpire|CacheDetailHeader|CacheDirLength|CacheDirLevels|CacheDisable|CacheEnable|CacheFile|CacheHeader|CacheIgnoreCacheControl|CacheIgnoreHeaders|CacheIgnoreNoLastMod|CacheIgnoreQueryString|CacheIgnoreURLSessionIdentifiers|CacheKeyBaseURL|CacheLastModifiedFactor|CacheLock|CacheLockMaxAge|CacheLockPath|CacheMaxExpire|CacheMaxFileSize|CacheMinExpire|CacheMinFileSize|CacheNegotiatedDocs|CacheQuickHandler|CacheReadSize|CacheReadTime|CacheRoot|CacheSocache|CacheSocacheMaxSize|CacheSocacheMaxTime|CacheSocacheMinTime|CacheSocacheReadSize|CacheSocacheReadTime|CacheStaleOnError|CacheStoreExpired|CacheStoreNoStore|CacheStorePrivate|CGIDScriptTimeout|CGIMapExtension|CharsetDefault|CharsetOptions|CharsetSourceEnc|CheckCaseOnly|CheckSpelling|ChrootDir|ContentDigest|CookieDomain|CookieExpires|CookieName|CookieStyle|CookieTracking|CoreDumpDirectory|CustomLog|Dav|DavDepthInfinity|DavGenericLockDB|DavLockDB|DavMinTimeout|DBDExptime|DBDInitSQL|DBDKeep|DBDMax|DBDMin|DBDParams|DBDPersist|DBDPrepareSQL|DBDriver|DefaultIcon|DefaultLanguage|DefaultRuntimeDir|DefaultType|Define|DeflateBufferSize|DeflateCompressionLevel|DeflateFilterNote|DeflateInflateLimitRequestBody|DeflateInflateRatioBurst|DeflateInflateRatioLimit|DeflateMemLevel|DeflateWindowSize|Deny|DirectoryCheckHandler|DirectoryIndex|DirectoryIndexRedirect|DirectorySlash|DocumentRoot|DTracePrivileges|DumpIOInput|DumpIOOutput|EnableExceptionHook|EnableMMAP|EnableSendfile|Error|ErrorDocument|ErrorLog|ErrorLogFormat|Example|ExpiresActive|ExpiresByType|ExpiresDefault|ExtendedStatus|ExtFilterDefine|ExtFilterOptions|FallbackResource|FileETag|FilterChain|FilterDeclare|FilterProtocol|FilterProvider|FilterTrace|ForceLanguagePriority|ForceType|ForensicLog|GprofDir|GracefulShutdownTimeout|Group|Header|HeaderName|HeartbeatAddress|HeartbeatListen|HeartbeatMaxServers|HeartbeatStorage|HeartbeatStorage|HostnameLookups|IdentityCheck|IdentityCheckTimeout|ImapBase|ImapDefault|ImapMenu|Include|IncludeOptional|IndexHeadInsert|IndexIgnore|IndexIgnoreReset|IndexOptions|IndexOrderDefault|IndexStyleSheet|InputSed|ISAPIAppendLogToErrors|ISAPIAppendLogToQuery|ISAPICacheFile|ISAPIFakeAsync|ISAPILogNotSupported|ISAPIReadAheadBuffer|KeepAlive|KeepAliveTimeout|KeptBodySize|LanguagePriority|LDAPCacheEntries|LDAPCacheTTL|LDAPConnectionPoolTTL|LDAPConnectionTimeout|LDAPLibraryDebug|LDAPOpCacheEntries|LDAPOpCacheTTL|LDAPReferralHopLimit|LDAPReferrals|LDAPRetries|LDAPRetryDelay|LDAPSharedCacheFile|LDAPSharedCacheSize|LDAPTimeout|LDAPTrustedClientCert|LDAPTrustedGlobalCert|LDAPTrustedMode|LDAPVerifyServerCert|LimitInternalRecursion|LimitRequestBody|LimitRequestFields|LimitRequestFieldSize|LimitRequestLine|LimitXMLRequestBody|Listen|ListenBackLog|LoadFile|LoadModule|LogFormat|LogLevel|LogMessage|LuaAuthzProvider|LuaCodeCache|LuaHookAccessChecker|LuaHookAuthChecker|LuaHookCheckUserID|LuaHookFixups|LuaHookInsertFilter|LuaHookLog|LuaHookMapToStorage|LuaHookTranslateName|LuaHookTypeChecker|LuaInherit|LuaInputFilter|LuaMapHandler|LuaOutputFilter|LuaPackageCPath|LuaPackagePath|LuaQuickHandler|LuaRoot|LuaScope|MaxConnectionsPerChild|MaxKeepAliveRequests|MaxMemFree|MaxRangeOverlaps|MaxRangeReversals|MaxRanges|MaxRequestWorkers|MaxSpareServers|MaxSpareThreads|MaxThreads|MergeTrailers|MetaDir|MetaFiles|MetaSuffix|MimeMagicFile|MinSpareServers|MinSpareThreads|MMapFile|ModemStandard|ModMimeUsePathInfo|MultiviewsMatch|Mutex|NameVirtualHost|NoProxy|NWSSLTrustedCerts|NWSSLUpgradeable|Options|Order|OutputSed|PassEnv|PidFile|PrivilegesMode|Protocol|ProtocolEcho|ProxyAddHeaders|ProxyBadHeader|ProxyBlock|ProxyDomain|ProxyErrorOverride|ProxyExpressDBMFile|ProxyExpressDBMType|ProxyExpressEnable|ProxyFtpDirCharset|ProxyFtpEscapeWildcards|ProxyFtpListOnWildcard|ProxyHTMLBufSize|ProxyHTMLCharsetOut|ProxyHTMLDocType|ProxyHTMLEnable|ProxyHTMLEvents|ProxyHTMLExtended|ProxyHTMLFixups|ProxyHTMLInterp|ProxyHTMLLinks|ProxyHTMLMeta|ProxyHTMLStripComments|ProxyHTMLURLMap|ProxyIOBufferSize|ProxyMaxForwards|ProxyPass|ProxyPassInherit|ProxyPassInterpolateEnv|ProxyPassMatch|ProxyPassReverse|ProxyPassReverseCookieDomain|ProxyPassReverseCookiePath|ProxyPreserveHost|ProxyReceiveBufferSize|ProxyRemote|ProxyRemoteMatch|ProxyRequests|ProxySCGIInternalRedirect|ProxySCGISendfile|ProxySet|ProxySourceAddress|ProxyStatus|ProxyTimeout|ProxyVia|ReadmeName|ReceiveBufferSize|Redirect|RedirectMatch|RedirectPermanent|RedirectTemp|ReflectorHeader|RemoteIPHeader|RemoteIPInternalProxy|RemoteIPInternalProxyList|RemoteIPProxiesHeader|RemoteIPTrustedProxy|RemoteIPTrustedProxyList|RemoveCharset|RemoveEncoding|RemoveHandler|RemoveInputFilter|RemoveLanguage|RemoveOutputFilter|RemoveType|RequestHeader|RequestReadTimeout|Require|RewriteBase|RewriteCond|RewriteEngine|RewriteMap|RewriteOptions|RewriteRule|RLimitCPU|RLimitMEM|RLimitNPROC|Satisfy|ScoreBoardFile|Script|ScriptAlias|ScriptAliasMatch|ScriptInterpreterSource|ScriptLog|ScriptLogBuffer|ScriptLogLength|ScriptSock|SecureListen|SeeRequestTail|SendBufferSize|ServerAdmin|ServerAlias|ServerLimit|ServerName|ServerPath|ServerRoot|ServerSignature|ServerTokens|Session|SessionCookieName|SessionCookieName2|SessionCookieRemove|SessionCryptoCipher|SessionCryptoDriver|SessionCryptoPassphrase|SessionCryptoPassphraseFile|SessionDBDCookieName|SessionDBDCookieName2|SessionDBDCookieRemove|SessionDBDDeleteLabel|SessionDBDInsertLabel|SessionDBDPerUser|SessionDBDSelectLabel|SessionDBDUpdateLabel|SessionEnv|SessionExclude|SessionHeader|SessionInclude|SessionMaxAge|SetEnv|SetEnvIf|SetEnvIfExpr|SetEnvIfNoCase|SetHandler|SetInputFilter|SetOutputFilter|SSIEndTag|SSIErrorMsg|SSIETag|SSILastModified|SSILegacyExprParser|SSIStartTag|SSITimeFormat|SSIUndefinedEcho|SSLCACertificateFile|SSLCACertificatePath|SSLCADNRequestFile|SSLCADNRequestPath|SSLCARevocationCheck|SSLCARevocationFile|SSLCARevocationPath|SSLCertificateChainFile|SSLCertificateFile|SSLCertificateKeyFile|SSLCipherSuite|SSLCompression|SSLCryptoDevice|SSLEngine|SSLFIPS|SSLHonorCipherOrder|SSLInsecureRenegotiation|SSLOCSPDefaultResponder|SSLOCSPEnable|SSLOCSPOverrideResponder|SSLOCSPResponderTimeout|SSLOCSPResponseMaxAge|SSLOCSPResponseTimeSkew|SSLOCSPUseRequestNonce|SSLOpenSSLConfCmd|SSLOptions|SSLPassPhraseDialog|SSLProtocol|SSLProxyCACertificateFile|SSLProxyCACertificatePath|SSLProxyCARevocationCheck|SSLProxyCARevocationFile|SSLProxyCARevocationPath|SSLProxyCheckPeerCN|SSLProxyCheckPeerExpire|SSLProxyCheckPeerName|SSLProxyCipherSuite|SSLProxyEngine|SSLProxyMachineCertificateChainFile|SSLProxyMachineCertificateFile|SSLProxyMachineCertificatePath|SSLProxyProtocol|SSLProxyVerify|SSLProxyVerifyDepth|SSLRandomSeed|SSLRenegBufferSize|SSLRequire|SSLRequireSSL|SSLSessionCache|SSLSessionCacheTimeout|SSLSessionTicketKeyFile|SSLSRPUnknownUserSeed|SSLSRPVerifierFile|SSLStaplingCache|SSLStaplingErrorCacheTimeout|SSLStaplingFakeTryLater|SSLStaplingForceURL|SSLStaplingResponderTimeout|SSLStaplingResponseMaxAge|SSLStaplingResponseTimeSkew|SSLStaplingReturnResponderErrors|SSLStaplingStandardCacheTimeout|SSLStrictSNIVHostCheck|SSLUserName|SSLUseStapling|SSLVerifyClient|SSLVerifyDepth|StartServers|StartThreads|Substitute|Suexec|SuexecUserGroup|ThreadLimit|ThreadsPerChild|ThreadStackSize|TimeOut|TraceEnable|TransferLog|TypesConfig|UnDefine|UndefMacro|UnsetEnv|Use|UseCanonicalName|UseCanonicalPhysicalPort|User|UserDir|VHostCGIMode|VHostCGIPrivs|VHostGroup|VHostPrivs|VHostSecure|VHostUser|VirtualDocumentRoot|VirtualDocumentRootIP|VirtualScriptAlias|VirtualScriptAliasIP|WatchdogInterval|XBitHack|xml2EncAlias|xml2EncDefault|xml2StartParse)\b/im, - lookbehind: true, - alias: 'property' - }, - 'directive-block': { - pattern: /<\/?\b(?:AuthnProviderAlias|AuthzProviderAlias|Directory|DirectoryMatch|Else|ElseIf|Files|FilesMatch|If|IfDefine|IfModule|IfVersion|Limit|LimitExcept|Location|LocationMatch|Macro|Proxy|RequireAll|RequireAny|RequireNone|VirtualHost)\b *.*>/i, - inside: { - 'directive-block': { - pattern: /^<\/?\w+/, - inside: { - punctuation: /^<\/?/ - }, - alias: 'tag' - }, - 'directive-block-parameter': { - pattern: /.*[^>]/, - inside: { - punctuation: /:/, - string: { - pattern: /("|').*\1/, - inside: { - variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/ - } - } - }, - alias: 'attr-value' - }, - punctuation: />/ - }, - alias: 'tag' - }, - 'directive-flags': { - pattern: /\[(?:\w,?)+\]/, - alias: 'keyword' - }, - string: { - pattern: /("|').*\1/, - inside: { - variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/ - } - }, - variable: /[$%]\{?(?:\w\.?[-+:]?)+\}?/, - regex: /\^?.*\$|\^.*\$?/ - }; +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `str` is not set, the file specified in `options.filename` will be read. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @param {Object} options + * @param {String=} str + * @return {Function} + * @api private + */ +function handleTemplateCache(options, str) { + var key = options.filename; + if (options.cache && exports.cache[key]) { + return exports.cache[key]; + } else { + if (str === undefined) str = fs.readFileSync(options.filename, 'utf8'); + var templ = exports.compile(str, options); + if (options.cache) exports.cache[key] = templ; + return templ; } -}; - -/***/ }), - -/***/ 13529: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +} +/** + * Compile a `Function` representation of the given pug `str`. + * + * Options: + * + * - `compileDebug` when `false` debugging code is stripped from the compiled + template, when it is explicitly `true`, the source code is included in + the compiled template for better accuracy. + * - `filename` used to improve errors when `compileDebug` is not `false` and to resolve imports/extends + * + * @param {String} str + * @param {Options} options + * @return {Function} + * @api public + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'apl', - init: function init(Prism) { - Prism.languages.apl = { - comment: /(?:⍝|#[! ]).*$/m, - string: { - pattern: /'(?:[^'\r\n]|'')*'/, - greedy: true - }, - number: /¯?(?:\d*\.?\d+(?:e[+¯]?\d+)?|¯|∞)(?:j¯?(?:\d*\.?\d+(?:e[+¯]?\d+)?|¯|∞))?/i, - statement: /:[A-Z][a-z][A-Za-z]*\b/, - 'system-function': { - pattern: /⎕[A-Z]+/i, - alias: 'function' - }, - constant: /[⍬⌾#⎕⍞]/, - function: /[-+×÷⌈⌊∣|⍳⍸?*⍟○!⌹<≤=>≥≠≡≢∊⍷∪∩~∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⊆⊇⌷⍋⍒⊤⊥⍕⍎⊣⊢⍁⍂≈⍯↗¤→]/, - 'monadic-operator': { - pattern: /[\\\/⌿⍀¨⍨⌶&∥]/, - alias: 'operator' - }, - 'dyadic-operator': { - pattern: /[.⍣⍠⍤∘⌸@⌺]/, - alias: 'operator' - }, - assignment: { - pattern: /←/, - alias: 'keyword' - }, - punctuation: /[\[;\]()◇⋄]/, - dfn: { - pattern: /[{}⍺⍵⍶⍹∇⍫:]/, - alias: 'builtin' - } - }; - } -}; +exports.compile = function(str, options) { + var options = options || {}; -/***/ }), + str = String(str); -/***/ 95394: -/***/ ((__unused_webpack_module, exports) => { + var parsed = compileBody(str, { + compileDebug: options.compileDebug !== false, + filename: options.filename, + basedir: options.basedir, + pretty: options.pretty, + doctype: options.doctype, + inlineRuntimeFunctions: options.inlineRuntimeFunctions, + globals: options.globals, + self: options.self, + includeSources: options.compileDebug === true, + debug: options.debug, + templateName: 'template', + filters: options.filters, + filterOptions: options.filterOptions, + filterAliases: options.filterAliases, + plugins: options.plugins, + }); -"use strict"; + var res = options.inlineRuntimeFunctions + ? new Function('', parsed.body + ';return template;')() + : runtimeWrap(parsed.body); + res.dependencies = parsed.dependencies; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'applescript', - init: function init(Prism) { - Prism.languages.applescript = { - comment: [ - // Allow one level of nesting - /\(\*(?:\(\*[\s\S]*?\*\)|[\s\S])*?\*\)/, /--.+/, /#.+/], - string: /"(?:\\.|[^"\\\r\n])*"/, - number: /(?:\b\d+\.?\d*|\B\.\d+)(?:e-?\d+)?\b/i, - operator: [/[&=≠≤≥*+\-\/÷^]|[<>]=?/, /\b(?:(?:start|begin|end)s? with|(?:(?:does not|doesn't) contain|contains?)|(?:is|isn't|is not) (?:in|contained by)|(?:(?:is|isn't|is not) )?(?:greater|less) than(?: or equal)?(?: to)?|(?:(?:does not|doesn't) come|comes) (?:before|after)|(?:is|isn't|is not) equal(?: to)?|(?:(?:does not|doesn't) equal|equals|equal to|isn't|is not)|(?:a )?(?:ref(?: to)?|reference to)|(?:and|or|div|mod|as|not))\b/], - keyword: /\b(?:about|above|after|against|apart from|around|aside from|at|back|before|beginning|behind|below|beneath|beside|between|but|by|considering|continue|copy|does|eighth|else|end|equal|error|every|exit|false|fifth|first|for|fourth|from|front|get|given|global|if|ignoring|in|instead of|into|is|it|its|last|local|me|middle|my|ninth|of|on|onto|out of|over|prop|property|put|repeat|return|returning|second|set|seventh|since|sixth|some|tell|tenth|that|the|then|third|through|thru|timeout|times|to|transaction|true|try|until|where|while|whose|with|without)\b/, - class: { - pattern: /\b(?:alias|application|boolean|class|constant|date|file|integer|list|number|POSIX file|real|record|reference|RGB color|script|text|centimetres|centimeters|feet|inches|kilometres|kilometers|metres|meters|miles|yards|square feet|square kilometres|square kilometers|square metres|square meters|square miles|square yards|cubic centimetres|cubic centimeters|cubic feet|cubic inches|cubic metres|cubic meters|cubic yards|gallons|litres|liters|quarts|grams|kilograms|ounces|pounds|degrees Celsius|degrees Fahrenheit|degrees Kelvin)\b/, - alias: 'builtin' - }, - punctuation: /[{}():,¬«»《》]/ - }; - } + return res; }; -/***/ }), +/** + * Compile a JavaScript source representation of the given pug `str`. + * + * Options: + * + * - `compileDebug` When it is `true`, the source code is included in + * the compiled template for better error messages. + * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends + * - `name` the name of the resulting function (defaults to "template") + * - `module` when it is explicitly `true`, the source code include export module syntax + * + * @param {String} str + * @param {Options} options + * @return {Object} + * @api public + */ -/***/ 56245: -/***/ ((__unused_webpack_module, exports) => { +exports.compileClientWithDependenciesTracked = function(str, options) { + var options = options || {}; -"use strict"; + str = String(str); + var parsed = compileBody(str, { + compileDebug: options.compileDebug, + filename: options.filename, + basedir: options.basedir, + pretty: options.pretty, + doctype: options.doctype, + inlineRuntimeFunctions: options.inlineRuntimeFunctions !== false, + globals: options.globals, + self: options.self, + includeSources: options.compileDebug, + debug: options.debug, + templateName: options.name || 'template', + filters: options.filters, + filterOptions: options.filterOptions, + filterAliases: options.filterAliases, + plugins: options.plugins, + }); + var body = parsed.body; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'arff', - init: function init(Prism) { - Prism.languages.arff = { - comment: /%.*/, - string: { - pattern: /(["'])(?:\\.|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - keyword: /@(?:attribute|data|end|relation)\b/i, - number: /\b\d+(?:\.\d+)?\b/, - punctuation: /[{},]/ - }; + if (options.module) { + if (options.inlineRuntimeFunctions === false) { + body = 'var pug = require("pug-runtime");' + body; + } + body += ' module.exports = ' + (options.name || 'template') + ';'; } -}; - -/***/ }), - -/***/ 86002: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'asciidoc', - init: function init(Prism) { - (function (Prism) { - var attributes = { - pattern: /(^[ \t]*)\[(?!\[)(?:(["'$`])(?:(?!\2)[^\\]|\\.)*\2|\[(?:[^\]\\]|\\.)*\]|[^\]\\]|\\.)*\]/m, - lookbehind: true, - inside: { - quoted: { - pattern: /([$`])(?:(?!\1)[^\\]|\\.)*\1/, - inside: { - punctuation: /^[$`]|[$`]$/ - } - }, - interpreted: { - pattern: /'(?:[^'\\]|\\.)*'/, - inside: { - punctuation: /^'|'$/ - // See rest below - } - }, - string: /"(?:[^"\\]|\\.)*"/, - variable: /\w+(?==)/, - punctuation: /^\[|\]$|,/, - operator: /=/, - // The negative look-ahead prevents blank matches - 'attr-value': /(?!^\s+$).+/ - } - }; - Prism.languages.asciidoc = { - 'comment-block': { - pattern: /^(\/{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1/m, - alias: 'comment' - }, - table: { - pattern: /^\|={3,}(?:(?:\r?\n|\r).*)*?(?:\r?\n|\r)\|={3,}$/m, - inside: { - specifiers: { - pattern: /(?!\|)(?:(?:(?:\d+(?:\.\d+)?|\.\d+)[+*])?(?:[<^>](?:\.[<^>])?|\.[<^>])?[a-z]*)(?=\|)/, - alias: 'attr-value' - }, - punctuation: { - pattern: /(^|[^\\])[|!]=*/, - lookbehind: true - } - // See rest below - } - }, - - 'passthrough-block': { - pattern: /^(\+{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m, - inside: { - punctuation: /^\++|\++$/ - // See rest below - } - }, - // Literal blocks and listing blocks - 'literal-block': { - pattern: /^(-{4,}|\.{4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m, - inside: { - punctuation: /^(?:-+|\.+)|(?:-+|\.+)$/ - // See rest below - } - }, - // Sidebar blocks, quote blocks, example blocks and open blocks - 'other-block': { - pattern: /^(--|\*{4,}|_{4,}|={4,})(?:\r?\n|\r)(?:[\s\S]*(?:\r?\n|\r))??\1$/m, - inside: { - punctuation: /^(?:-+|\*+|_+|=+)|(?:-+|\*+|_+|=+)$/ - // See rest below - } - }, - - // list-punctuation and list-label must appear before indented-block - 'list-punctuation': { - pattern: /(^[ \t]*)(?:-|\*{1,5}|\.{1,5}|(?:[a-z]|\d+)\.|[xvi]+\))(?= )/im, - lookbehind: true, - alias: 'punctuation' - }, - 'list-label': { - pattern: /(^[ \t]*)[a-z\d].+(?::{2,4}|;;)(?=\s)/im, - lookbehind: true, - alias: 'symbol' - }, - 'indented-block': { - pattern: /((\r?\n|\r)\2)([ \t]+)\S.*(?:(?:\r?\n|\r)\3.+)*(?=\2{2}|$)/, - lookbehind: true - }, - - comment: /^\/\/.*/m, - title: { - pattern: /^.+(?:\r?\n|\r)(?:={3,}|-{3,}|~{3,}|\^{3,}|\+{3,})$|^={1,5} +.+|^\.(?![\s.]).*/m, - alias: 'important', - inside: { - punctuation: /^(?:\.|=+)|(?:=+|-+|~+|\^+|\++)$/ - // See rest below - } - }, - 'attribute-entry': { - pattern: /^:[^:\r\n]+:(?: .*?(?: \+(?:\r?\n|\r).*?)*)?$/m, - alias: 'tag' - }, - attributes: attributes, - hr: { - pattern: /^'{3,}$/m, - alias: 'punctuation' - }, - 'page-break': { - pattern: /^<{3,}$/m, - alias: 'punctuation' - }, - admonition: { - pattern: /^(?:TIP|NOTE|IMPORTANT|WARNING|CAUTION):/m, - alias: 'keyword' - }, - callout: [{ - pattern: /(^[ \t]*)/m, - lookbehind: true, - alias: 'symbol' - }, { - pattern: /<\d+>/, - alias: 'symbol' - }], - macro: { - pattern: /\b[a-z\d][a-z\d-]*::?(?:(?:\S+)??\[(?:[^\]\\"]|(["'])(?:(?!\1)[^\\]|\\.)*\1|\\.)*\])/, - inside: { - function: /^[a-z\d-]+(?=:)/, - punctuation: /^::?/, - attributes: { - pattern: /(?:\[(?:[^\]\\"]|(["'])(?:(?!\1)[^\\]|\\.)*\1|\\.)*\])/, - inside: attributes.inside - } - } - }, - inline: { - /* - The initial look-behind prevents the highlighting of escaped quoted text. - Quoted text can be multi-line but cannot span an empty line. - All quoted text can have attributes before [foobar, 'foobar', baz="bar"]. - First, we handle the constrained quotes. - Those must be bounded by non-word chars and cannot have spaces between the delimiter and the first char. - They are, in order: _emphasis_, ``double quotes'', `single quotes', `monospace`, 'emphasis', *strong*, +monospace+ and #unquoted# - Then we handle the unconstrained quotes. - Those do not have the restrictions of the constrained quotes. - They are, in order: __emphasis__, **strong**, ++monospace++, +++passthrough+++, ##unquoted##, $$passthrough$$, ~subscript~, ^superscript^, {attribute-reference}, [[anchor]], [[[bibliography anchor]]], <>, (((indexes))) and ((indexes)) - */ - pattern: /(^|[^\\])(?:(?:\B\[(?:[^\]\\"]|(["'])(?:(?!\2)[^\\]|\\.)*\2|\\.)*\])?(?:\b_(?!\s)(?: _|[^_\\\r\n]|\\.)+(?:(?:\r?\n|\r)(?: _|[^_\\\r\n]|\\.)+)*_\b|\B``(?!\s).+?(?:(?:\r?\n|\r).+?)*''\B|\B`(?!\s)(?: ['`]|.)+?(?:(?:\r?\n|\r)(?: ['`]|.)+?)*['`]\B|\B(['*+#])(?!\s)(?: \3|(?!\3)[^\\\r\n]|\\.)+(?:(?:\r?\n|\r)(?: \3|(?!\3)[^\\\r\n]|\\.)+)*\3\B)|(?:\[(?:[^\]\\"]|(["'])(?:(?!\4)[^\\]|\\.)*\4|\\.)*\])?(?:(__|\*\*|\+\+\+?|##|\$\$|[~^]).+?(?:(?:\r?\n|\r).+?)*\5|\{[^}\r\n]+\}|\[\[\[?.+?(?:(?:\r?\n|\r).+?)*\]?\]\]|<<.+?(?:(?:\r?\n|\r).+?)*>>|\(\(\(?.+?(?:(?:\r?\n|\r).+?)*\)?\)\)))/m, - lookbehind: true, - inside: { - attributes: attributes, - url: { - pattern: /^(?:\[\[\[?.+?\]?\]\]|<<.+?>>)$/, - inside: { - punctuation: /^(?:\[\[\[?|<<)|(?:\]\]\]?|>>)$/ - } - }, - 'attribute-ref': { - pattern: /^\{.+\}$/, - inside: { - variable: { - pattern: /(^\{)[a-z\d,+_-]+/, - lookbehind: true - }, - operator: /^[=?!#%@$]|!(?=[:}])/, - punctuation: /^\{|\}$|::?/ - } - }, - italic: { - pattern: /^(['_])[\s\S]+\1$/, - inside: { - punctuation: /^(?:''?|__?)|(?:''?|__?)$/ - } - }, - bold: { - pattern: /^\*[\s\S]+\*$/, - inside: { - punctuation: /^\*\*?|\*\*?$/ - } - }, - punctuation: /^(?:``?|\+{1,3}|##?|\$\$|[~^]|\(\(\(?)|(?:''?|\+{1,3}|##?|\$\$|[~^`]|\)?\)\))$/ - } - }, - replacement: { - pattern: /\((?:C|TM|R)\)/, - alias: 'builtin' - }, - entity: /&#?[\da-z]{1,8};/i, - 'line-continuation': { - pattern: /(^| )\+$/m, - lookbehind: true, - alias: 'punctuation' - } - - // Allow some nesting. There is no recursion though, so cloning should not be needed. - };attributes.inside.interpreted.inside.rest = { - macro: Prism.languages.asciidoc.macro, - inline: Prism.languages.asciidoc.inline, - replacement: Prism.languages.asciidoc.replacement, - entity: Prism.languages.asciidoc.entity - }; + return {body: body, dependencies: parsed.dependencies}; +}; - Prism.languages.asciidoc['passthrough-block'].inside.rest = { - macro: Prism.languages.asciidoc.macro - }; +/** + * Compile a JavaScript source representation of the given pug `str`. + * + * Options: + * + * - `compileDebug` When it is `true`, the source code is included in + * the compiled template for better error messages. + * - `filename` used to improve errors when `compileDebug` is not `true` and to resolve imports/extends + * - `name` the name of the resulting function (defaults to "template") + * + * @param {String} str + * @param {Options} options + * @return {String} + * @api public + */ +exports.compileClient = function(str, options) { + return exports.compileClientWithDependenciesTracked(str, options).body; +}; - Prism.languages.asciidoc['literal-block'].inside.rest = { - callout: Prism.languages.asciidoc.callout - }; +/** + * Compile a `Function` representation of the given pug file. + * + * Options: + * + * - `compileDebug` when `false` debugging code is stripped from the compiled + template, when it is explicitly `true`, the source code is included in + the compiled template for better accuracy. + * + * @param {String} path + * @param {Options} options + * @return {Function} + * @api public + */ +exports.compileFile = function(path, options) { + options = options || {}; + options.filename = path; + return handleTemplateCache(options); +}; - Prism.languages.asciidoc.table.inside.rest = { - 'comment-block': Prism.languages.asciidoc['comment-block'], - 'passthrough-block': Prism.languages.asciidoc['passthrough-block'], - 'literal-block': Prism.languages.asciidoc['literal-block'], - 'other-block': Prism.languages.asciidoc['other-block'], - 'list-punctuation': Prism.languages.asciidoc['list-punctuation'], - 'indented-block': Prism.languages.asciidoc['indented-block'], - comment: Prism.languages.asciidoc.comment, - title: Prism.languages.asciidoc.title, - 'attribute-entry': Prism.languages.asciidoc['attribute-entry'], - attributes: Prism.languages.asciidoc.attributes, - hr: Prism.languages.asciidoc.hr, - 'page-break': Prism.languages.asciidoc['page-break'], - admonition: Prism.languages.asciidoc.admonition, - 'list-label': Prism.languages.asciidoc['list-label'], - callout: Prism.languages.asciidoc.callout, - macro: Prism.languages.asciidoc.macro, - inline: Prism.languages.asciidoc.inline, - replacement: Prism.languages.asciidoc.replacement, - entity: Prism.languages.asciidoc.entity, - 'line-continuation': Prism.languages.asciidoc['line-continuation'] - }; +/** + * Render the given `str` of pug. + * + * Options: + * + * - `cache` enable template caching + * - `filename` filename required for `include` / `extends` and caching + * + * @param {String} str + * @param {Object|Function} options or fn + * @param {Function|undefined} fn + * @returns {String} + * @api public + */ - Prism.languages.asciidoc['other-block'].inside.rest = { - table: Prism.languages.asciidoc.table, - 'list-punctuation': Prism.languages.asciidoc['list-punctuation'], - 'indented-block': Prism.languages.asciidoc['indented-block'], - comment: Prism.languages.asciidoc.comment, - 'attribute-entry': Prism.languages.asciidoc['attribute-entry'], - attributes: Prism.languages.asciidoc.attributes, - hr: Prism.languages.asciidoc.hr, - 'page-break': Prism.languages.asciidoc['page-break'], - admonition: Prism.languages.asciidoc.admonition, - 'list-label': Prism.languages.asciidoc['list-label'], - macro: Prism.languages.asciidoc.macro, - inline: Prism.languages.asciidoc.inline, - replacement: Prism.languages.asciidoc.replacement, - entity: Prism.languages.asciidoc.entity, - 'line-continuation': Prism.languages.asciidoc['line-continuation'] - }; +exports.render = function(str, options, fn) { + // support callback API + if ('function' == typeof options) { + (fn = options), (options = undefined); + } + if (typeof fn === 'function') { + var res; + try { + res = exports.render(str, options); + } catch (ex) { + return fn(ex); + } + return fn(null, res); + } - Prism.languages.asciidoc.title.inside.rest = { - macro: Prism.languages.asciidoc.macro, - inline: Prism.languages.asciidoc.inline, - replacement: Prism.languages.asciidoc.replacement, - entity: Prism.languages.asciidoc.entity + options = options || {}; - // Plugin to make entity title show the real entity, idea by Roman Komarov - };Prism.hooks.add('wrap', function (env) { - if (env.type === 'entity') { - env.attributes.title = env.content.replace(/&/, '&'); - } - }); - })(Prism); + // cache requires .filename + if (options.cache && !options.filename) { + throw new Error('the "filename" option is required for caching'); } -}; -/***/ }), + return handleTemplateCache(options, str)(options); +}; -/***/ 68737: -/***/ ((__unused_webpack_module, exports) => { +/** + * Render a Pug file at the given `path`. + * + * @param {String} path + * @param {Object|Function} options or callback + * @param {Function|undefined} fn + * @returns {String} + * @api public + */ -"use strict"; +exports.renderFile = function(path, options, fn) { + // support callback API + if ('function' == typeof options) { + (fn = options), (options = undefined); + } + if (typeof fn === 'function') { + var res; + try { + res = exports.renderFile(path, options); + } catch (ex) { + return fn(ex); + } + return fn(null, res); + } + options = options || {}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'asm6502', - init: function init(Prism) { - Prism.languages.asm6502 = { - comment: /;.*/, - directive: { - pattern: /\.\w+(?= )/, - alias: 'keyword' - }, - string: /(["'`])(?:\\.|(?!\1)[^\\\r\n])*\1/, - opcode: { - pattern: /\b(?:adc|and|asl|bcc|bcs|beq|bit|bmi|bne|bpl|brk|bvc|bvs|clc|cld|cli|clv|cmp|cpx|cpy|dec|dex|dey|eor|inc|inx|iny|jmp|jsr|lda|ldx|ldy|lsr|nop|ora|pha|php|pla|plp|rol|ror|rti|rts|sbc|sec|sed|sei|sta|stx|sty|tax|tay|tsx|txa|txs|tya|ADC|AND|ASL|BCC|BCS|BEQ|BIT|BMI|BNE|BPL|BRK|BVC|BVS|CLC|CLD|CLI|CLV|CMP|CPX|CPY|DEC|DEX|DEY|EOR|INC|INX|INY|JMP|JSR|LDA|LDX|LDY|LSR|NOP|ORA|PHA|PHP|PLA|PLP|ROL|ROR|RTI|RTS|SBC|SEC|SED|SEI|STA|STX|STY|TAX|TAY|TSX|TXA|TXS|TYA)\b/, - alias: 'property' - }, - hexnumber: { - pattern: /#?\$[\da-f]{2,4}/i, - alias: 'string' - }, - binarynumber: { - pattern: /#?%[01]+/, - alias: 'string' - }, - decimalnumber: { - pattern: /#?\d+/, - alias: 'string' - }, - register: { - pattern: /\b[xya]\b/i, - alias: 'variable' - } - }; - } + options.filename = path; + return handleTemplateCache(options)(options); }; -/***/ }), - -/***/ 16326: -/***/ ((__unused_webpack_module, exports) => { +/** + * Compile a Pug file at the given `path` for use on the client. + * + * @param {String} path + * @param {Object} options + * @returns {String} + * @api public + */ -"use strict"; +exports.compileFileClient = function(path, options) { + var key = path + ':client'; + options = options || {}; + options.filename = path; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'aspnet', - init: function init(Prism) { - Prism.languages.aspnet = Prism.languages.extend('markup', { - 'page-directive tag': { - pattern: /<%\s*@.*%>/i, - inside: { - 'page-directive tag': /<%\s*@\s*(?:Assembly|Control|Implements|Import|Master(?:Type)?|OutputCache|Page|PreviousPageType|Reference|Register)?|%>/i, - rest: Prism.languages.markup.tag.inside - } - }, - 'directive tag': { - pattern: /<%.*%>/i, - inside: { - 'directive tag': /<%\s*?[$=%#:]{0,2}|%>/i, - rest: Prism.languages.csharp - } - } - }); - // Regexp copied from prism-markup, with a negative look-ahead added - Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i; + if (options.cache && exports.cache[key]) { + return exports.cache[key]; + } - // match directives of attribute value foo="<% Bar %>" - Prism.languages.insertBefore('inside', 'punctuation', { - 'directive tag': Prism.languages.aspnet['directive tag'] - }, Prism.languages.aspnet.tag.inside['attr-value']); + var str = fs.readFileSync(options.filename, 'utf8'); + var out = exports.compileClient(str, options); + if (options.cache) exports.cache[key] = out; + return out; +}; - Prism.languages.insertBefore('aspnet', 'comment', { - 'asp comment': /<%--[\s\S]*?--%>/ - }); +/** + * Express support. + */ - // script runat="server" contains csharp, not javascript - Prism.languages.insertBefore('aspnet', Prism.languages.javascript ? 'script' : 'tag', { - 'asp script': { - pattern: /()[\s\S]*?(?=<\/script>)/i, - lookbehind: true, - inside: Prism.languages.csharp || {} - } - }); +exports.__express = function(path, options, fn) { + if ( + options.compileDebug == undefined && + process.env.NODE_ENV === 'production' + ) { + options.compileDebug = false; } + exports.renderFile(path, options, fn); }; -/***/ }), - -/***/ 3183: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/***/ }), +/***/ 18341: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'autohotkey', - init: function init(Prism) { - // NOTES - follows first-first highlight method, block is locked after highlight, different from SyntaxHl - Prism.languages.autohotkey = { - comment: { - pattern: /(^[^";\n]*("[^"\n]*?"[^"\n]*?)*)(?:;.*$|^\s*\/\*[\s\S]*\n\*\/)/m, - lookbehind: true - }, - string: /"(?:[^"\n\r]|"")*"/m, - function: /[^(); \t,\n+*\-=?>:\\\/<&%\[\]]+?(?=\()/m, // function - don't use .*\) in the end bcoz string locks it - tag: /^[ \t]*[^\s:]+?(?=:(?:[^:]|$))/m, // labels - variable: /%\w+%/, - number: /\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee]-?\d+)?/, - operator: /\?|\/\/?=?|:=|\|[=|]?|&[=&]?|\+[=+]?|-[=-]?|\*[=*]?|<(?:<=?|>|=)?|>>?=?|[.^!=~]=?|\b(?:AND|NOT|OR)\b/, - punctuation: /[{}[\]():,]/, - boolean: /\b(?:true|false)\b/, +var once = __nccwpck_require__(1223) +var eos = __nccwpck_require__(81205) +var fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes - selector: /\b(?:AutoTrim|BlockInput|Break|Click|ClipWait|Continue|Control|ControlClick|ControlFocus|ControlGet|ControlGetFocus|ControlGetPos|ControlGetText|ControlMove|ControlSend|ControlSendRaw|ControlSetText|CoordMode|Critical|DetectHiddenText|DetectHiddenWindows|Drive|DriveGet|DriveSpaceFree|EnvAdd|EnvDiv|EnvGet|EnvMult|EnvSet|EnvSub|EnvUpdate|Exit|ExitApp|FileAppend|FileCopy|FileCopyDir|FileCreateDir|FileCreateShortcut|FileDelete|FileEncoding|FileGetAttrib|FileGetShortcut|FileGetSize|FileGetTime|FileGetVersion|FileInstall|FileMove|FileMoveDir|FileRead|FileReadLine|FileRecycle|FileRecycleEmpty|FileRemoveDir|FileSelectFile|FileSelectFolder|FileSetAttrib|FileSetTime|FormatTime|GetKeyState|Gosub|Goto|GroupActivate|GroupAdd|GroupClose|GroupDeactivate|Gui|GuiControl|GuiControlGet|Hotkey|ImageSearch|IniDelete|IniRead|IniWrite|Input|InputBox|KeyWait|ListHotkeys|ListLines|ListVars|Loop|Menu|MouseClick|MouseClickDrag|MouseGetPos|MouseMove|MsgBox|OnExit|OutputDebug|Pause|PixelGetColor|PixelSearch|PostMessage|Process|Progress|Random|RegDelete|RegRead|RegWrite|Reload|Repeat|Return|Run|RunAs|RunWait|Send|SendEvent|SendInput|SendMessage|SendMode|SendPlay|SendRaw|SetBatchLines|SetCapslockState|SetControlDelay|SetDefaultMouseSpeed|SetEnv|SetFormat|SetKeyDelay|SetMouseDelay|SetNumlockState|SetScrollLockState|SetStoreCapslockMode|SetTimer|SetTitleMatchMode|SetWinDelay|SetWorkingDir|Shutdown|Sleep|Sort|SoundBeep|SoundGet|SoundGetWaveVolume|SoundPlay|SoundSet|SoundSetWaveVolume|SplashImage|SplashTextOff|SplashTextOn|SplitPath|StatusBarGetText|StatusBarWait|StringCaseSense|StringGetPos|StringLeft|StringLen|StringLower|StringMid|StringReplace|StringRight|StringSplit|StringTrimLeft|StringTrimRight|StringUpper|Suspend|SysGet|Thread|ToolTip|Transform|TrayTip|URLDownloadToFile|WinActivate|WinActivateBottom|WinClose|WinGet|WinGetActiveStats|WinGetActiveTitle|WinGetClass|WinGetPos|WinGetText|WinGetTitle|WinHide|WinKill|WinMaximize|WinMenuSelectItem|WinMinimize|WinMinimizeAll|WinMinimizeAllUndo|WinMove|WinRestore|WinSet|WinSetTitle|WinShow|WinWait|WinWaitActive|WinWaitClose|WinWaitNotActive)\b/i, +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) - constant: /\b(?:a_ahkpath|a_ahkversion|a_appdata|a_appdatacommon|a_autotrim|a_batchlines|a_caretx|a_carety|a_computername|a_controldelay|a_cursor|a_dd|a_ddd|a_dddd|a_defaultmousespeed|a_desktop|a_desktopcommon|a_detecthiddentext|a_detecthiddenwindows|a_endchar|a_eventinfo|a_exitreason|a_formatfloat|a_formatinteger|a_gui|a_guievent|a_guicontrol|a_guicontrolevent|a_guiheight|a_guiwidth|a_guix|a_guiy|a_hour|a_iconfile|a_iconhidden|a_iconnumber|a_icontip|a_index|a_ipaddress1|a_ipaddress2|a_ipaddress3|a_ipaddress4|a_isadmin|a_iscompiled|a_iscritical|a_ispaused|a_issuspended|a_isunicode|a_keydelay|a_language|a_lasterror|a_linefile|a_linenumber|a_loopfield|a_loopfileattrib|a_loopfiledir|a_loopfileext|a_loopfilefullpath|a_loopfilelongpath|a_loopfilename|a_loopfileshortname|a_loopfileshortpath|a_loopfilesize|a_loopfilesizekb|a_loopfilesizemb|a_loopfiletimeaccessed|a_loopfiletimecreated|a_loopfiletimemodified|a_loopreadline|a_loopregkey|a_loopregname|a_loopregsubkey|a_loopregtimemodified|a_loopregtype|a_mday|a_min|a_mm|a_mmm|a_mmmm|a_mon|a_mousedelay|a_msec|a_mydocuments|a_now|a_nowutc|a_numbatchlines|a_ostype|a_osversion|a_priorhotkey|programfiles|a_programfiles|a_programs|a_programscommon|a_screenheight|a_screenwidth|a_scriptdir|a_scriptfullpath|a_scriptname|a_sec|a_space|a_startmenu|a_startmenucommon|a_startup|a_startupcommon|a_stringcasesense|a_tab|a_temp|a_thisfunc|a_thishotkey|a_thislabel|a_thismenu|a_thismenuitem|a_thismenuitempos|a_tickcount|a_timeidle|a_timeidlephysical|a_timesincepriorhotkey|a_timesincethishotkey|a_titlematchmode|a_titlematchmodespeed|a_username|a_wday|a_windelay|a_windir|a_workingdir|a_yday|a_year|a_yweek|a_yyyy|clipboard|clipboardall|comspec|errorlevel)\b/i, +var isFn = function (fn) { + return typeof fn === 'function' +} - builtin: /\b(?:abs|acos|asc|asin|atan|ceil|chr|class|cos|dllcall|exp|fileexist|Fileopen|floor|il_add|il_create|il_destroy|instr|substr|isfunc|islabel|IsObject|ln|log|lv_add|lv_delete|lv_deletecol|lv_getcount|lv_getnext|lv_gettext|lv_insert|lv_insertcol|lv_modify|lv_modifycol|lv_setimagelist|mod|onmessage|numget|numput|registercallback|regexmatch|regexreplace|round|sin|tan|sqrt|strlen|sb_seticon|sb_setparts|sb_settext|strsplit|tv_add|tv_delete|tv_getchild|tv_getcount|tv_getnext|tv_get|tv_getparent|tv_getprev|tv_getselection|tv_gettext|tv_modify|varsetcapacity|winactive|winexist|__New|__Call|__Get|__Set)\b/i, +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} - symbol: /\b(?:alt|altdown|altup|appskey|backspace|browser_back|browser_favorites|browser_forward|browser_home|browser_refresh|browser_search|browser_stop|bs|capslock|ctrl|ctrlbreak|ctrldown|ctrlup|del|delete|down|end|enter|esc|escape|f1|f10|f11|f12|f13|f14|f15|f16|f17|f18|f19|f2|f20|f21|f22|f23|f24|f3|f4|f5|f6|f7|f8|f9|home|ins|insert|joy1|joy10|joy11|joy12|joy13|joy14|joy15|joy16|joy17|joy18|joy19|joy2|joy20|joy21|joy22|joy23|joy24|joy25|joy26|joy27|joy28|joy29|joy3|joy30|joy31|joy32|joy4|joy5|joy6|joy7|joy8|joy9|joyaxes|joybuttons|joyinfo|joyname|joypov|joyr|joyu|joyv|joyx|joyy|joyz|lalt|launch_app1|launch_app2|launch_mail|launch_media|lbutton|lcontrol|lctrl|left|lshift|lwin|lwindown|lwinup|mbutton|media_next|media_play_pause|media_prev|media_stop|numlock|numpad0|numpad1|numpad2|numpad3|numpad4|numpad5|numpad6|numpad7|numpad8|numpad9|numpadadd|numpadclear|numpaddel|numpaddiv|numpaddot|numpaddown|numpadend|numpadenter|numpadhome|numpadins|numpadleft|numpadmult|numpadpgdn|numpadpgup|numpadright|numpadsub|numpadup|pgdn|pgup|printscreen|ralt|rbutton|rcontrol|rctrl|right|rshift|rwin|rwindown|rwinup|scrolllock|shift|shiftdown|shiftup|space|tab|up|volume_down|volume_mute|volume_up|wheeldown|wheelleft|wheelright|wheelup|xbutton1|xbutton2)\b/i, +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} - important: /#\b(?:AllowSameLineComments|ClipboardTimeout|CommentFlag|ErrorStdOut|EscapeChar|HotkeyInterval|HotkeyModifierTimeout|Hotstring|IfWinActive|IfWinExist|IfWinNotActive|IfWinNotExist|Include|IncludeAgain|InstallKeybdHook|InstallMouseHook|KeyHistory|LTrim|MaxHotkeysPerInterval|MaxMem|MaxThreads|MaxThreadsBuffer|MaxThreadsPerHotkey|NoEnv|NoTrayIcon|Persistent|SingleInstance|UseHook|WinActivateForce)\b/i, +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) - keyword: /\b(?:Abort|AboveNormal|Add|ahk_class|ahk_group|ahk_id|ahk_pid|All|Alnum|Alpha|AltSubmit|AltTab|AltTabAndMenu|AltTabMenu|AltTabMenuDismiss|AlwaysOnTop|AutoSize|Background|BackgroundTrans|BelowNormal|between|BitAnd|BitNot|BitOr|BitShiftLeft|BitShiftRight|BitXOr|Bold|Border|Button|ByRef|Checkbox|Checked|CheckedGray|Choose|ChooseString|Close|Color|ComboBox|Contains|ControlList|Count|Date|DateTime|Days|DDL|Default|DeleteAll|Delimiter|Deref|Destroy|Digit|Disable|Disabled|DropDownList|Edit|Eject|Else|Enable|Enabled|Error|Exist|Expand|ExStyle|FileSystem|First|Flash|Float|FloatFast|Focus|Font|for|global|Grid|Group|GroupBox|GuiClose|GuiContextMenu|GuiDropFiles|GuiEscape|GuiSize|Hdr|Hidden|Hide|High|HKCC|HKCR|HKCU|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_LOCAL_MACHINE|HKEY_USERS|HKLM|HKU|Hours|HScroll|Icon|IconSmall|ID|IDLast|If|IfEqual|IfExist|IfGreater|IfGreaterOrEqual|IfInString|IfLess|IfLessOrEqual|IfMsgBox|IfNotEqual|IfNotExist|IfNotInString|IfWinActive|IfWinExist|IfWinNotActive|IfWinNotExist|Ignore|ImageList|in|Integer|IntegerFast|Interrupt|is|italic|Join|Label|LastFound|LastFoundExist|Limit|Lines|List|ListBox|ListView|local|Lock|Logoff|Low|Lower|Lowercase|MainWindow|Margin|Maximize|MaximizeBox|MaxSize|Minimize|MinimizeBox|MinMax|MinSize|Minutes|MonthCal|Mouse|Move|Multi|NA|No|NoActivate|NoDefault|NoHide|NoIcon|NoMainWindow|norm|Normal|NoSort|NoSortHdr|NoStandard|Not|NoTab|NoTimers|Number|Off|Ok|On|OwnDialogs|Owner|Parse|Password|Picture|Pixel|Pos|Pow|Priority|ProcessName|Radio|Range|Read|ReadOnly|Realtime|Redraw|REG_BINARY|REG_DWORD|REG_EXPAND_SZ|REG_MULTI_SZ|REG_SZ|Region|Relative|Rename|Report|Resize|Restore|Retry|RGB|Screen|Seconds|Section|Serial|SetLabel|ShiftAltTab|Show|Single|Slider|SortDesc|Standard|static|Status|StatusBar|StatusCD|strike|Style|Submit|SysMenu|Tab2|TabStop|Text|Theme|Tile|ToggleCheck|ToggleEnable|ToolWindow|Top|Topmost|TransColor|Transparent|Tray|TreeView|TryAgain|Type|UnCheck|underline|Unicode|Unlock|UpDown|Upper|Uppercase|UseErrorLevel|Vis|VisFirst|Visible|VScroll|Wait|WaitClose|WantCtrlA|WantF2|WantReturn|While|Wrap|Xdigit|xm|xp|xs|Yes|ym|yp|ys)\b/i - }; - } -}; + var closed = false + stream.on('close', function () { + closed = true + }) -/***/ }), + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) -/***/ 41502: -/***/ ((__unused_webpack_module, exports) => { + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true -"use strict"; + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + if (isFn(stream.destroy)) return stream.destroy() -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'autoit', - init: function init(Prism) { - Prism.languages.autoit = { - comment: [/;.*/, { - // The multi-line comments delimiters can actually be commented out with ";" - pattern: /(^\s*)#(?:comments-start|cs)[\s\S]*?^\s*#(?:comments-end|ce)/m, - lookbehind: true - }], - url: { - pattern: /(^\s*#include\s+)(?:<[^\r\n>]+>|"[^\r\n"]+")/m, - lookbehind: true - }, - string: { - pattern: /(["'])(?:\1\1|(?!\1)[^\r\n])*\1/, - greedy: true, - inside: { - variable: /([%$@])\w+\1/ - } - }, - directive: { - pattern: /(^\s*)#\w+/m, - lookbehind: true, - alias: 'keyword' - }, - function: /\b\w+(?=\()/, - // Variables and macros - variable: /[$@]\w+/, - keyword: /\b(?:Case|Const|Continue(?:Case|Loop)|Default|Dim|Do|Else(?:If)?|End(?:Func|If|Select|Switch|With)|Enum|Exit(?:Loop)?|For|Func|Global|If|In|Local|Next|Null|ReDim|Select|Static|Step|Switch|Then|To|Until|Volatile|WEnd|While|With)\b/i, - number: /\b(?:0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i, - boolean: /\b(?:True|False)\b/i, - operator: /<[=>]?|[-+*\/=&>]=?|[?^]|\b(?:And|Or|Not)\b/i, - punctuation: /[\[\]().,:]/ - }; + callback(err || new Error('stream was destroyed')) } -}; +} -/***/ }), +var call = function (fn) { + fn() +} -/***/ 15209: -/***/ ((__unused_webpack_module, exports) => { +var pipe = function (from, to) { + return from.pipe(to) +} -"use strict"; +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'bash', - init: function init(Prism) { - (function (Prism) { - var insideString = { - variable: [ - // Arithmetic Environment - { - pattern: /\$?\(\([\s\S]+?\)\)/, - inside: { - // If there is a $ sign at the beginning highlight $(( and )) as variable - variable: [{ - pattern: /(^\$\(\([\s\S]+)\)\)/, - lookbehind: true - }, /^\$\(\(/], - number: /\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee]-?\d+)?/, - // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic - operator: /--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/, - // If there is no $ sign at the beginning highlight (( and )) as punctuation - punctuation: /\(\(?|\)\)?|,|;/ - } - }, - // Command Substitution - { - pattern: /\$\([^)]+\)|`[^`]+`/, - greedy: true, - inside: { - variable: /^\$\(|^`|\)$|`$/ - } - }, /\$(?:[\w#?*!@]+|\{[^}]+\})/i] - }; + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) - Prism.languages.bash = { - shebang: { - pattern: /^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/, - alias: 'important' - }, - comment: { - pattern: /(^|[^"{\\])#.*/, - lookbehind: true - }, - string: [ - // Support for Here-Documents https://en.wikipedia.org/wiki/Here_document - { - pattern: /((?:^|[^<])<<\s*)["']?(\w+?)["']?\s*\r?\n(?:[\s\S])*?\r?\n\2/, - lookbehind: true, - greedy: true, - inside: insideString - }, { - pattern: /(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\1)[^\\])*\1/, - greedy: true, - inside: insideString - }], - variable: insideString.variable, - // Originally based on http://ss64.com/bash/ - function: { - pattern: /(^|[\s;|&])(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|[\s;|&])/, - lookbehind: true - }, - keyword: { - pattern: /(^|[\s;|&])(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|[\s;|&])/, - lookbehind: true - }, - boolean: { - pattern: /(^|[\s;|&])(?:true|false)(?=$|[\s;|&])/, - lookbehind: true - }, - operator: /&&?|\|\|?|==?|!=?|<<>|<=?|>=?|=~/, - punctuation: /\$?\(\(?|\)\)?|\.\.|[{}[\];]/ - }; + return streams.reduce(pipe) +} - var inside = insideString.variable[1].inside; - inside.string = Prism.languages.bash.string; - inside.function = Prism.languages.bash.function; - inside.keyword = Prism.languages.bash.keyword; - inside.boolean = Prism.languages.bash.boolean; - inside.operator = Prism.languages.bash.operator; - inside.punctuation = Prism.languages.bash.punctuation; +module.exports = pump - Prism.languages.shell = Prism.languages.bash; - })(Prism); - } -}; /***/ }), -/***/ 46676: -/***/ ((__unused_webpack_module, exports) => { +/***/ 89795: +/***/ ((module) => { -"use strict"; +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ +let promise +module.exports = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) + // reuse resolved promise, and allocate it lazily + : cb => (promise || (promise = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'basic', - init: function init(Prism) { - Prism.languages.basic = { - comment: { - pattern: /(?:!|REM\b).+/i, - inside: { - keyword: /^REM/i - } - }, - string: { - pattern: /"(?:""|[!#$%&'()*,\/:;<=>?^_ +\-.A-Z\d])*"/i, - greedy: true - }, - number: /(?:\b\d+\.?\d*|\B\.\d+)(?:E[+-]?\d+)?/i, - keyword: /\b(?:AS|BEEP|BLOAD|BSAVE|CALL(?: ABSOLUTE)?|CASE|CHAIN|CHDIR|CLEAR|CLOSE|CLS|COM|COMMON|CONST|DATA|DECLARE|DEF(?: FN| SEG|DBL|INT|LNG|SNG|STR)|DIM|DO|DOUBLE|ELSE|ELSEIF|END|ENVIRON|ERASE|ERROR|EXIT|FIELD|FILES|FOR|FUNCTION|GET|GOSUB|GOTO|IF|INPUT|INTEGER|IOCTL|KEY|KILL|LINE INPUT|LOCATE|LOCK|LONG|LOOP|LSET|MKDIR|NAME|NEXT|OFF|ON(?: COM| ERROR| KEY| TIMER)?|OPEN|OPTION BASE|OUT|POKE|PUT|READ|REDIM|REM|RESTORE|RESUME|RETURN|RMDIR|RSET|RUN|SHARED|SINGLE|SELECT CASE|SHELL|SLEEP|STATIC|STEP|STOP|STRING|SUB|SWAP|SYSTEM|THEN|TIMER|TO|TROFF|TRON|TYPE|UNLOCK|UNTIL|USING|VIEW PRINT|WAIT|WEND|WHILE|WRITE)(?:\$|\b)/i, - function: /\b(?:ABS|ACCESS|ACOS|ANGLE|AREA|ARITHMETIC|ARRAY|ASIN|ASK|AT|ATN|BASE|BEGIN|BREAK|CAUSE|CEIL|CHR|CLIP|COLLATE|COLOR|CON|COS|COSH|COT|CSC|DATE|DATUM|DEBUG|DECIMAL|DEF|DEG|DEGREES|DELETE|DET|DEVICE|DISPLAY|DOT|ELAPSED|EPS|ERASABLE|EXLINE|EXP|EXTERNAL|EXTYPE|FILETYPE|FIXED|FP|GO|GRAPH|HANDLER|IDN|IMAGE|IN|INT|INTERNAL|IP|IS|KEYED|LBOUND|LCASE|LEFT|LEN|LENGTH|LET|LINE|LINES|LOG|LOG10|LOG2|LTRIM|MARGIN|MAT|MAX|MAXNUM|MID|MIN|MISSING|MOD|NATIVE|NUL|NUMERIC|OF|OPTION|ORD|ORGANIZATION|OUTIN|OUTPUT|PI|POINT|POINTER|POINTS|POS|PRINT|PROGRAM|PROMPT|RAD|RADIANS|RANDOMIZE|RECORD|RECSIZE|RECTYPE|RELATIVE|REMAINDER|REPEAT|REST|RETRY|REWRITE|RIGHT|RND|ROUND|RTRIM|SAME|SEC|SELECT|SEQUENTIAL|SET|SETTER|SGN|SIN|SINH|SIZE|SKIP|SQR|STANDARD|STATUS|STR|STREAM|STYLE|TAB|TAN|TANH|TEMPLATE|TEXT|THERE|TIME|TIMEOUT|TRACE|TRANSFORM|TRUNCATE|UBOUND|UCASE|USE|VAL|VARIABLE|VIEWPORT|WHEN|WINDOW|WITH|ZER|ZONEWIDTH)(?:\$|\b)/i, - operator: /<[=>]?|>=?|[+\-*\/^=&]|\b(?:AND|EQV|IMP|NOT|OR|XOR)\b/i, - punctuation: /[,;:()]/ - }; - } -}; /***/ }), -/***/ 20986: -/***/ ((__unused_webpack_module, exports) => { +/***/ 80289: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'batch', - init: function init(Prism) { - (function (Prism) { - var variable = /%%?[~:\w]+%?|!\S+!/; - var parameter = { - pattern: /\/[a-z?]+(?=[ :]|$):?|-[a-z]\b|--[a-z-]+\b/im, - alias: 'attr-name', - inside: { - punctuation: /:/ - } - }; - var string = /"[^"]*"/; - var number = /(?:\b|-)\d+\b/; - - Prism.languages.batch = { - comment: [/^::.*/m, { - pattern: /((?:^|[&(])[ \t]*)rem\b(?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im, - lookbehind: true - }], - label: { - pattern: /^:.*/m, - alias: 'property' - }, - command: [{ - // FOR command - pattern: /((?:^|[&(])[ \t]*)for(?: ?\/[a-z?](?:[ :](?:"[^"]*"|\S+))?)* \S+ in \([^)]+\) do/im, - lookbehind: true, - inside: { - keyword: /^for\b|\b(?:in|do)\b/i, - string: string, - parameter: parameter, - variable: variable, - number: number, - punctuation: /[()',]/ - } - }, { - // IF command - pattern: /((?:^|[&(])[ \t]*)if(?: ?\/[a-z?](?:[ :](?:"[^"]*"|\S+))?)* (?:not )?(?:cmdextversion \d+|defined \w+|errorlevel \d+|exist \S+|(?:"[^"]*"|\S+)?(?:==| (?:equ|neq|lss|leq|gtr|geq) )(?:"[^"]*"|\S+))/im, - lookbehind: true, - inside: { - keyword: /^if\b|\b(?:not|cmdextversion|defined|errorlevel|exist)\b/i, - string: string, - parameter: parameter, - variable: variable, - number: number, - operator: /\^|==|\b(?:equ|neq|lss|leq|gtr|geq)\b/i - } - }, { - // ELSE command - pattern: /((?:^|[&()])[ \t]*)else\b/im, - lookbehind: true, - inside: { - keyword: /^else\b/i - } - }, { - // SET command - pattern: /((?:^|[&(])[ \t]*)set(?: ?\/[a-z](?:[ :](?:"[^"]*"|\S+))?)* (?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im, - lookbehind: true, - inside: { - keyword: /^set\b/i, - string: string, - parameter: parameter, - variable: [variable, /\w+(?=(?:[*\/%+\-&^|]|<<|>>)?=)/], - number: number, - operator: /[*\/%+\-&^|]=?|<<=?|>>=?|[!~_=]/, - punctuation: /[()',]/ - } - }, { - // Other commands - pattern: /((?:^|[&(])[ \t]*@?)\w+\b(?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im, - lookbehind: true, - inside: { - keyword: /^\w+\b/i, - string: string, - parameter: parameter, - label: { - pattern: /(^\s*):\S+/m, - lookbehind: true, - alias: 'property' - }, - variable: variable, - number: number, - operator: /\^/ - } - }], - operator: /[&@]/, - punctuation: /[()']/ - }; - })(Prism); +const { SymbolDispose } = __nccwpck_require__(89629) +const { AbortError, codes } = __nccwpck_require__(80529) +const { isNodeStream, isWebStream, kControllerErrorFunction } = __nccwpck_require__(27981) +const eos = __nccwpck_require__(76080) +const { ERR_INVALID_ARG_TYPE } = codes +let addAbortListener + +// This method is inlined here for readable-stream +// It also does not allow for signal to not exist on the stream +// https://github.com/nodejs/node/pull/36061#discussion_r533718029 +const validateAbortSignal = (signal, name) => { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } -}; +} +module.exports.addAbortSignal = function addAbortSignal(signal, stream) { + validateAbortSignal(signal, 'signal') + if (!isNodeStream(stream) && !isWebStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + return module.exports.addAbortSignalNoValidate(signal, stream) +} +module.exports.addAbortSignalNoValidate = function (signal, stream) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + return stream + } + const onAbort = isNodeStream(stream) + ? () => { + stream.destroy( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + : () => { + stream[kControllerErrorFunction]( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + if (signal.aborted) { + onAbort() + } else { + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(signal, onAbort) + eos(stream, disposable[SymbolDispose]) + } + return stream +} + /***/ }), -/***/ 64636: -/***/ ((__unused_webpack_module, exports) => { +/***/ 52746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'brainfuck', - init: function init(Prism) { - Prism.languages.brainfuck = { - pointer: { - pattern: /<|>/, - alias: 'keyword' - }, - increment: { - pattern: /\+/, - alias: 'inserted' - }, - decrement: { - pattern: /-/, - alias: 'deleted' - }, - branching: { - pattern: /\[|\]/, - alias: 'important' - }, - operator: /[.,]/, - comment: /\S+/ - }; +const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = __nccwpck_require__(89629) +const { Buffer } = __nccwpck_require__(14300) +const { inspect } = __nccwpck_require__(46959) +module.exports = class BufferList { + constructor() { + this.head = null + this.tail = null + this.length = 0 + } + push(v) { + const entry = { + data: v, + next: null + } + if (this.length > 0) this.tail.next = entry + else this.head = entry + this.tail = entry + ++this.length + } + unshift(v) { + const entry = { + data: v, + next: this.head + } + if (this.length === 0) this.tail = entry + this.head = entry + ++this.length + } + shift() { + if (this.length === 0) return + const ret = this.head.data + if (this.length === 1) this.head = this.tail = null + else this.head = this.head.next + --this.length + return ret + } + clear() { + this.head = this.tail = null + this.length = 0 + } + join(s) { + if (this.length === 0) return '' + let p = this.head + let ret = '' + p.data + while ((p = p.next) !== null) ret += s + p.data + return ret + } + concat(n) { + if (this.length === 0) return Buffer.alloc(0) + const ret = Buffer.allocUnsafe(n >>> 0) + let p = this.head + let i = 0 + while (p) { + TypedArrayPrototypeSet(ret, p.data, i) + i += p.data.length + p = p.next + } + return ret } -}; - -/***/ }), - -/***/ 57206: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data = this.head.data + if (n < data.length) { + // `slice` is the same for buffers and strings. + const slice = data.slice(0, n) + this.head.data = data.slice(n) + return slice + } + if (n === data.length) { + // First chunk is a perfect match. + return this.shift() + } + // Result spans more than one buffer. + return hasStrings ? this._getString(n) : this._getBuffer(n) + } + first() { + return this.head.data + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'bro', - init: function init(Prism) { - Prism.languages.bro = { - comment: { - pattern: /(^|[^\\$])#.*/, - lookbehind: true, - inside: { - italic: /\b(?:TODO|FIXME|XXX)\b/ + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = '' + let p = this.head + let c = 0 + do { + const str = p.data + if (n > str.length) { + ret += str + n -= str.length + } else { + if (n === str.length) { + ret += str + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + ret += StringPrototypeSlice(str, 0, n) + this.head = p + p.data = StringPrototypeSlice(str, n) } - }, - - string: { - pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - - boolean: /\b[TF]\b/, + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret + } - function: { - pattern: /(?:function|hook|event) \w+(?:::\w+)?/, - inside: { - keyword: /^(?:function|hook|event)/ + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer.allocUnsafe(n) + const retLen = n + let p = this.head + let c = 0 + do { + const buf = p.data + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + n -= buf.length + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) + this.head = p + p.data = buf.slice(n) } - }, + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret + } - variable: { - pattern: /(?:global|local) \w+/i, - inside: { - keyword: /(?:global|local)/ - } - }, + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for('nodejs.util.inspect.custom')](_, options) { + return inspect(this, { + ...options, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }) + } +} - builtin: /(?:@(?:load(?:-(?:sigs|plugin))?|unload|prefixes|ifn?def|else|(?:end)?if|DIR|FILENAME))|(?:&?(?:redef|priority|log|optional|default|add_func|delete_func|expire_func|read_expire|write_expire|create_expire|synchronized|persistent|rotate_interval|rotate_size|encrypt|raw_output|mergeable|group|error_handler|type_column))/, - constant: { - pattern: /const \w+/i, - inside: { - keyword: /const/ - } - }, +/***/ }), - keyword: /\b(?:break|next|continue|alarm|using|of|add|delete|export|print|return|schedule|when|timeout|addr|any|bool|count|double|enum|file|int|interval|pattern|opaque|port|record|set|string|subnet|table|time|vector|for|if|else|in|module|function)\b/, +/***/ 63129: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&|\|\|?|\?|\*|\/|~|\^|%/, +"use strict"; - number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, - punctuation: /[{}[\];(),.:]/ - }; +const { pipeline } = __nccwpck_require__(76989) +const Duplex = __nccwpck_require__(72613) +const { destroyer } = __nccwpck_require__(97049) +const { + isNodeStream, + isReadable, + isWritable, + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream +} = __nccwpck_require__(27981) +const { + AbortError, + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } +} = __nccwpck_require__(80529) +const eos = __nccwpck_require__(76080) +module.exports = function compose(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS('streams') } -}; + if (streams.length === 1) { + return Duplex.from(streams[0]) + } + const orgStreams = [...streams] + if (typeof streams[0] === 'function') { + streams[0] = Duplex.from(streams[0]) + } + if (typeof streams[streams.length - 1] === 'function') { + const idx = streams.length - 1 + streams[idx] = Duplex.from(streams[idx]) + } + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + // TODO(ronag): Add checks for non streams. + continue + } + if ( + n < streams.length - 1 && + !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) + ) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') + } + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') + } + } + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } else if (!readable && !writable) { + d.destroy() + } + } + const head = streams[0] + const tail = pipeline(streams, onfinished) + const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) + const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplex({ + // TODO (ronag): highWaterMark? + writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), + writable, + readable + }) + if (writable) { + if (isNodeStream(head)) { + d._write = function (chunk, encoding, callback) { + if (head.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + head.end() + onfinish = callback + } + head.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + } else if (isWebStream(head)) { + const writable = isTransformStream(head) ? head.writable : head + const writer = writable.getWriter() + d._write = async function (chunk, encoding, callback) { + try { + await writer.ready + writer.write(chunk).catch(() => {}) + callback() + } catch (err) { + callback(err) + } + } + d._final = async function (callback) { + try { + await writer.ready + writer.close().catch(() => {}) + onfinish = callback + } catch (err) { + callback(err) + } + } + } + const toRead = isTransformStream(tail) ? tail.readable : tail + eos(toRead, () => { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) + } + if (readable) { + if (isNodeStream(tail)) { + tail.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + tail.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = tail.read() + if (buf === null) { + onreadable = d._read + return + } + if (!d.push(buf)) { + return + } + } + } + } else if (isWebStream(tail)) { + const readable = isTransformStream(tail) ? tail.readable : tail + const reader = readable.getReader() + d._read = async function () { + while (true) { + try { + const { value, done } = await reader.read() + if (!d.push(value)) { + return + } + if (done) { + d.push(null) + return + } + } catch { + return + } + } + } + } + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + if (isNodeStream(tail)) { + destroyer(tail, err) + } + } + } + return d +} + /***/ }), -/***/ 98220: -/***/ ((__unused_webpack_module, exports) => { +/***/ 97049: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'c', - init: function init(Prism) { - Prism.languages.c = Prism.languages.extend('clike', { - keyword: /\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/, - operator: /-[>-]?|\+\+?|!=?|<>?=?|==?|&&?|\|\|?|[~^%?*\/]/, - number: /(?:\b0x[\da-f]+|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?)[ful]*/i - }); - - Prism.languages.insertBefore('c', 'string', { - macro: { - // allow for multiline macro definitions - // spaces after the # character compile fine with gcc - pattern: /(^\s*)#\s*[a-z]+(?:[^\r\n\\]|\\(?:\r\n|[\s\S]))*/im, - lookbehind: true, - alias: 'property', - inside: { - // highlight the path of the include statement as a string - string: { - pattern: /(#\s*include\s*)(?:<.+?>|("|')(?:\\?.)+?\2)/, - lookbehind: true - }, - // highlight macro directives as keywords - directive: { - pattern: /(#\s*)\b(?:define|defined|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/, - lookbehind: true, - alias: 'keyword' - } - } - }, - // highlight predefined macros as constants - constant: /\b(?:__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|stdin|stdout|stderr)\b/ - }); +/* replacement start */ - delete Prism.languages.c['class-name']; - delete Prism.languages.c.boolean; - } -}; +const process = __nccwpck_require__(45676) -/***/ }), +/* replacement end */ -/***/ 17403: -/***/ ((__unused_webpack_module, exports) => { +const { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError +} = __nccwpck_require__(80529) +const { Symbol } = __nccwpck_require__(89629) +const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = __nccwpck_require__(27981) +const kDestroy = Symbol('kDestroy') +const kConstruct = Symbol('kConstruct') +function checkError(err, w, r) { + if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions -"use strict"; + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err + } + } +} +// Backwards compat. cb() is undocumented and unused in core but +// unfortunately might be used by modules. +function destroy(err, cb) { + const r = this._readableState + const w = this._writableState + // With duplex streams we use the writable side for state. + const s = w || r + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + if (typeof cb === 'function') { + cb() + } + return this + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'clike', - init: function init(Prism) { - Prism.languages.clike = { - comment: [{ - pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, - lookbehind: true - }, { - pattern: /(^|[^\\:])\/\/.*/, - lookbehind: true, - greedy: true - }], - string: { - pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - 'class-name': { - pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, - lookbehind: true, - inside: { - punctuation: /[.\\]/ - } - }, - keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, - boolean: /\b(?:true|false)\b/, - function: /[a-z0-9_]+(?=\()/i, - number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, - operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, - punctuation: /[{}[\];(),.:]/ - }; + // We set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + checkError(err, w, r) + if (w) { + w.destroyed = true + } + if (r) { + r.destroyed = true } -}; -/***/ }), + // If still constructing then defer calling _destroy. + if (!s.constructed) { + this.once(kDestroy, function (er) { + _destroy(this, aggregateTwoErrors(er, err), cb) + }) + } else { + _destroy(this, err, cb) + } + return this +} +function _destroy(self, err, cb) { + let called = false + function onDestroy(err) { + if (called) { + return + } + called = true + const r = self._readableState + const w = self._writableState + checkError(err, w, r) + if (w) { + w.closed = true + } + if (r) { + r.closed = true + } + if (typeof cb === 'function') { + cb(err) + } + if (err) { + process.nextTick(emitErrorCloseNT, self, err) + } else { + process.nextTick(emitCloseNT, self) + } + } + try { + self._destroy(err || null, onDestroy) + } catch (err) { + onDestroy(err) + } +} +function emitErrorCloseNT(self, err) { + emitErrorNT(self, err) + emitCloseNT(self) +} +function emitCloseNT(self) { + const r = self._readableState + const w = self._writableState + if (w) { + w.closeEmitted = true + } + if (r) { + r.closeEmitted = true + } + if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { + self.emit('close') + } +} +function emitErrorNT(self, err) { + const r = self._readableState + const w = self._writableState + if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { + return + } + if (w) { + w.errorEmitted = true + } + if (r) { + r.errorEmitted = true + } + self.emit('error', err) +} +function undestroy() { + const r = this._readableState + const w = this._writableState + if (r) { + r.constructed = true + r.closed = false + r.closeEmitted = false + r.destroyed = false + r.errored = null + r.errorEmitted = false + r.reading = false + r.ended = r.readable === false + r.endEmitted = r.readable === false + } + if (w) { + w.constructed = true + w.destroyed = false + w.closed = false + w.closeEmitted = false + w.errored = null + w.errorEmitted = false + w.finalCalled = false + w.prefinished = false + w.ended = w.writable === false + w.ending = w.writable === false + w.finished = w.writable === false + } +} +function errorOrDestroy(stream, err, sync) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. -/***/ 45685: -/***/ ((__unused_webpack_module, exports) => { + const r = stream._readableState + const w = stream._writableState + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + return this + } + if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) + stream.destroy(err) + else if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions -"use strict"; + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err + } + if (sync) { + process.nextTick(emitErrorNT, stream, err) + } else { + emitErrorNT(stream, err) + } + } +} +function construct(stream, cb) { + if (typeof stream._construct !== 'function') { + return + } + const r = stream._readableState + const w = stream._writableState + if (r) { + r.constructed = false + } + if (w) { + w.constructed = false + } + stream.once(kConstruct, cb) + if (stream.listenerCount(kConstruct) > 1) { + // Duplex + return + } + process.nextTick(constructNT, stream) +} +function constructNT(stream) { + let called = false + function onConstruct(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) + return + } + called = true + const r = stream._readableState + const w = stream._writableState + const s = w || r + if (r) { + r.constructed = true + } + if (w) { + w.constructed = true + } + if (s.destroyed) { + stream.emit(kDestroy, err) + } else if (err) { + errorOrDestroy(stream, err, true) + } else { + process.nextTick(emitConstructNT, stream) + } + } + try { + stream._construct((err) => { + process.nextTick(onConstruct, err) + }) + } catch (err) { + process.nextTick(onConstruct, err) + } +} +function emitConstructNT(stream) { + stream.emit(kConstruct) +} +function isRequest(stream) { + return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' +} +function emitCloseLegacy(stream) { + stream.emit('close') +} +function emitErrorCloseLegacy(stream, err) { + stream.emit('error', err) + process.nextTick(emitCloseLegacy, stream) +} +// Normalize destroy for legacy. +function destroyer(stream, err) { + if (!stream || isDestroyed(stream)) { + return + } + if (!err && !isFinished(stream)) { + err = new AbortError() + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'clojure', - init: function init(Prism) { - // Copied from https://github.com/jeluard/prism-clojure - Prism.languages.clojure = { - comment: /;+.*/, - string: /"(?:\\.|[^\\"\r\n])*"/, - operator: /(?:::|[:|'])\b[a-z][\w*+!?-]*\b/i, // used for symbols and keywords - keyword: { - pattern: /([^\w+*'?-])(?:def|if|do|let|\.\.|quote|var|->>|->|fn|loop|recur|throw|try|monitor-enter|\.|new|set!|def\-|defn|defn\-|defmacro|defmulti|defmethod|defstruct|defonce|declare|definline|definterface|defprotocol|==|defrecord|>=|deftype|<=|defproject|ns|\*|\+|\-|\/|<|=|>|accessor|agent|agent-errors|aget|alength|all-ns|alter|and|append-child|apply|array-map|aset|aset-boolean|aset-byte|aset-char|aset-double|aset-float|aset-int|aset-long|aset-short|assert|assoc|await|await-for|bean|binding|bit-and|bit-not|bit-or|bit-shift-left|bit-shift-right|bit-xor|boolean|branch\?|butlast|byte|cast|char|children|class|clear-agent-errors|comment|commute|comp|comparator|complement|concat|conj|cons|constantly|cond|if-not|construct-proxy|contains\?|count|create-ns|create-struct|cycle|dec|deref|difference|disj|dissoc|distinct|doall|doc|dorun|doseq|dosync|dotimes|doto|double|down|drop|drop-while|edit|end\?|ensure|eval|every\?|false\?|ffirst|file-seq|filter|find|find-doc|find-ns|find-var|first|float|flush|for|fnseq|frest|gensym|get-proxy-class|get|hash-map|hash-set|identical\?|identity|if-let|import|in-ns|inc|index|insert-child|insert-left|insert-right|inspect-table|inspect-tree|instance\?|int|interleave|intersection|into|into-array|iterate|join|key|keys|keyword|keyword\?|last|lazy-cat|lazy-cons|left|lefts|line-seq|list\*|list|load|load-file|locking|long|loop|macroexpand|macroexpand-1|make-array|make-node|map|map-invert|map\?|mapcat|max|max-key|memfn|merge|merge-with|meta|min|min-key|name|namespace|neg\?|new|newline|next|nil\?|node|not|not-any\?|not-every\?|not=|ns-imports|ns-interns|ns-map|ns-name|ns-publics|ns-refers|ns-resolve|ns-unmap|nth|nthrest|or|parse|partial|path|peek|pop|pos\?|pr|pr-str|print|print-str|println|println-str|prn|prn-str|project|proxy|proxy-mappings|quot|rand|rand-int|range|re-find|re-groups|re-matcher|re-matches|re-pattern|re-seq|read|read-line|reduce|ref|ref-set|refer|rem|remove|remove-method|remove-ns|rename|rename-keys|repeat|replace|replicate|resolve|rest|resultset-seq|reverse|rfirst|right|rights|root|rrest|rseq|second|select|select-keys|send|send-off|seq|seq-zip|seq\?|set|short|slurp|some|sort|sort-by|sorted-map|sorted-map-by|sorted-set|special-symbol\?|split-at|split-with|str|string\?|struct|struct-map|subs|subvec|symbol|symbol\?|sync|take|take-nth|take-while|test|time|to-array|to-array-2d|tree-seq|true\?|union|up|update-proxy|val|vals|var-get|var-set|var\?|vector|vector-zip|vector\?|when|when-first|when-let|when-not|with-local-vars|with-meta|with-open|with-out-str|xml-seq|xml-zip|zero\?|zipmap|zipper)(?=[^\w+*'?-])/, - lookbehind: true - }, - boolean: /\b(?:true|false|nil)\b/, - number: /\b[0-9A-Fa-f]+\b/, - punctuation: /[{}\[\](),]/ - }; + // TODO: Remove isRequest branches. + if (isServerRequest(stream)) { + stream.socket = null + stream.destroy(err) + } else if (isRequest(stream)) { + stream.abort() + } else if (isRequest(stream.req)) { + stream.req.abort() + } else if (typeof stream.destroy === 'function') { + stream.destroy(err) + } else if (typeof stream.close === 'function') { + // TODO: Don't lose err? + stream.close() + } else if (err) { + process.nextTick(emitErrorCloseLegacy, stream, err) + } else { + process.nextTick(emitCloseLegacy, stream) } -}; + if (!stream.destroyed) { + stream[kIsDestroyed] = true + } +} +module.exports = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy +} + /***/ }), -/***/ 20525: -/***/ ((__unused_webpack_module, exports) => { +/***/ 72613: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototype inheritance, this class +// prototypically inherits from Readable, and then parasitically from +// Writable. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'coffeescript', - init: function init(Prism) { - (function (Prism) { - // Ignore comments starting with { to privilege string interpolation highlighting - var comment = /#(?!\{).+/, - interpolation = { - pattern: /#\{[^}]+\}/, - alias: 'variable' - }; - - Prism.languages.coffeescript = Prism.languages.extend('javascript', { - comment: comment, - string: [ - // Strings are multiline - { - pattern: /'(?:\\[\s\S]|[^\\'])*'/, - greedy: true - }, { - // Strings are multiline - pattern: /"(?:\\[\s\S]|[^\\"])*"/, - greedy: true, - inside: { - interpolation: interpolation - } - }], - keyword: /\b(?:and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/, - 'class-member': { - pattern: /@(?!\d)\w+/, - alias: 'variable' - } - }); - - Prism.languages.insertBefore('coffeescript', 'comment', { - 'multiline-comment': { - pattern: /###[\s\S]+?###/, - alias: 'comment' - }, - - // Block regexp can contain comments and interpolation - 'block-regex': { - pattern: /\/{3}[\s\S]*?\/{3}/, - alias: 'regex', - inside: { - comment: comment, - interpolation: interpolation - } - } - }); - - Prism.languages.insertBefore('coffeescript', 'string', { - 'inline-javascript': { - pattern: /`(?:\\[\s\S]|[^\\`])*`/, - inside: { - delimiter: { - pattern: /^`|`$/, - alias: 'punctuation' - }, - rest: Prism.languages.javascript - } - }, - // Block strings - 'multiline-string': [{ - pattern: /'''[\s\S]*?'''/, - greedy: true, - alias: 'string' - }, { - pattern: /"""[\s\S]*?"""/, - greedy: true, - alias: 'string', - inside: { - interpolation: interpolation - } - }] - }); - Prism.languages.insertBefore('coffeescript', 'keyword', { - // Object property - property: /(?!\d)\w+(?=\s*:(?!:))/ - }); +const { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf +} = __nccwpck_require__(89629) +module.exports = Duplex +const Readable = __nccwpck_require__(57920) +const Writable = __nccwpck_require__(48488) +ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) +ObjectSetPrototypeOf(Duplex, Readable) +{ + const keys = ObjectKeys(Writable.prototype) + // Allow the keys array to be GC'ed. + for (let i = 0; i < keys.length; i++) { + const method = keys[i] + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options) + Readable.call(this, options) + Writable.call(this, options) + if (options) { + this.allowHalfOpen = options.allowHalfOpen !== false + if (options.readable === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if (options.writable === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } + } else { + this.allowHalfOpen = true + } +} +ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') + }, + writableHighWaterMark: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') + }, + writableObjectMode: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') + }, + writableBuffer: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') + }, + writableLength: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') + }, + writableFinished: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') + }, + writableCorked: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') + }, + writableEnded: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') + }, + writableNeedDrain: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') + }, + destroyed: { + __proto__: null, + get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false + } + return this._readableState.destroyed && this._writableState.destroyed + }, + set(value) { + // Backward compatibility, the user is explicitly + // managing destroyed. + if (this._readableState && this._writableState) { + this._readableState.destroyed = value + this._writableState.destroyed = value + } + } + } +}) +let webStreamsAdapters - delete Prism.languages.coffeescript['template-string']; - })(Prism); +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Duplex.fromWeb = function (pair, options) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) +} +Duplex.toWeb = function (duplex) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) +} +let duplexify +Duplex.from = function (body) { + if (!duplexify) { + duplexify = __nccwpck_require__(86350) } -}; + return duplexify(body, 'body') +} + /***/ }), -/***/ 26433: -/***/ ((__unused_webpack_module, exports) => { +/***/ 86350: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/* replacement start */ +const process = __nccwpck_require__(45676) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'cpp', - init: function init(Prism) { - Prism.languages.cpp = Prism.languages.extend('c', { - keyword: /\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/, - boolean: /\b(?:true|false)\b/, - operator: /--?|\+\+?|!=?|<{1,2}=?|>{1,2}=?|->|:{1,2}|={1,2}|\^|~|%|&{1,2}|\|\|?|\?|\*|\/|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/ - }); +/* replacement end */ - Prism.languages.insertBefore('cpp', 'keyword', { - 'class-name': { - pattern: /(class\s+)\w+/i, - lookbehind: true +;('use strict') +const bufferModule = __nccwpck_require__(14300) +const { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream +} = __nccwpck_require__(27981) +const eos = __nccwpck_require__(76080) +const { + AbortError, + codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } +} = __nccwpck_require__(80529) +const { destroyer } = __nccwpck_require__(97049) +const Duplex = __nccwpck_require__(72613) +const Readable = __nccwpck_require__(57920) +const Writable = __nccwpck_require__(48488) +const { createDeferredPromise } = __nccwpck_require__(46959) +const from = __nccwpck_require__(39082) +const Blob = globalThis.Blob || bufferModule.Blob +const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + return b instanceof Blob } - }); - - Prism.languages.insertBefore('cpp', 'string', { - 'raw-string': { - pattern: /R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/, - alias: 'string', - greedy: true + : function isBlob(b) { + return false } - }); - } -}; - -/***/ }), - -/***/ 3204: -/***/ ((__unused_webpack_module, exports) => { +const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) +const { FunctionPrototypeCall } = __nccwpck_require__(89629) -"use strict"; +// This is needed for pre node 17. +class Duplexify extends Duplex { + constructor(options) { + super(options) + // https://github.com/nodejs/node/pull/34385 -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'csharp', - init: function init(Prism) { - Prism.languages.csharp = Prism.languages.extend('clike', { - keyword: /\b(?:abstract|add|alias|as|ascending|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|descending|do|double|dynamic|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|from|get|global|goto|group|if|implicit|in|int|interface|internal|into|is|join|let|lock|long|namespace|new|null|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|remove|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield)\b/, - string: [{ - pattern: /@("|')(?:\1\1|\\[\s\S]|(?!\1)[^\\])*\1/, - greedy: true - }, { - pattern: /("|')(?:\\.|(?!\1)[^\\\r\n])*?\1/, - greedy: true - }], - 'class-name': [{ - // (Foo bar, Bar baz) - pattern: /\b[A-Z]\w*(?:\.\w+)*\b(?=\s+\w+)/, - inside: { - punctuation: /\./ - } - }, { - // [Foo] - pattern: /(\[)[A-Z]\w*(?:\.\w+)*\b/, - lookbehind: true, - inside: { - punctuation: /\./ - } - }, { - // class Foo : Bar - pattern: /(\b(?:class|interface)\s+[A-Z]\w*(?:\.\w+)*\s*:\s*)[A-Z]\w*(?:\.\w+)*\b/, - lookbehind: true, - inside: { - punctuation: /\./ - } - }, { - // class Foo - pattern: /((?:\b(?:class|interface|new)\s+)|(?:catch\s+\())[A-Z]\w*(?:\.\w+)*\b/, - lookbehind: true, - inside: { - punctuation: /\./ + if ((options === null || options === undefined ? undefined : options.readable) === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if ((options === null || options === undefined ? undefined : options.writable) === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } + } +} +module.exports = function duplexify(body, name) { + if (isDuplexNodeStream(body)) { + return body + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }) + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }) + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }) + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }) + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }) + } + if (typeof body === 'function') { + const { value, write, final, destroy } = fromAsyncGen(body) + if (isIterable(value)) { + return from(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write, + final, + destroy + }) + } + const then = value === null || value === undefined ? undefined : value.then + if (typeof then === 'function') { + let d + const promise = FunctionPrototypeCall( + then, + value, + (val) => { + if (val != null) { + throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) + } + }, + (err) => { + destroyer(d, err) } - }], - number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)f?/i - }); - - Prism.languages.insertBefore('csharp', 'class-name', { - 'generic-method': { - pattern: /\w+\s*<[^>\r\n]+?>\s*(?=\()/, - inside: { - function: /^\w+/, - 'class-name': { - pattern: /\b[A-Z]\w*(?:\.\w+)*\b/, - inside: { - punctuation: /\./ + ) + return (d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write, + final(cb) { + final(async () => { + try { + await promise + process.nextTick(cb, null) + } catch (err) { + process.nextTick(cb, err) } - }, - keyword: Prism.languages.csharp.keyword, - punctuation: /[<>(),.:]/ + }) + }, + destroy + })) + } + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) + } + if (isBlob(body)) { + return duplexify(body.arrayBuffer()) + } + if (isIterable(body)) { + return from(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }) + } + if ( + isReadableStream(body === null || body === undefined ? undefined : body.readable) && + isWritableStream(body === null || body === undefined ? undefined : body.writable) + ) { + return Duplexify.fromWeb(body) + } + if ( + typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || + typeof (body === null || body === undefined ? undefined : body.readable) === 'object' + ) { + const readable = + body !== null && body !== undefined && body.readable + ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) + ? body === null || body === undefined + ? undefined + : body.readable + : duplexify(body.readable) + : undefined + const writable = + body !== null && body !== undefined && body.writable + ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) + ? body === null || body === undefined + ? undefined + : body.writable + : duplexify(body.writable) + : undefined + return _duplexify({ + readable, + writable + }) + } + const then = body === null || body === undefined ? undefined : body.then + if (typeof then === 'function') { + let d + FunctionPrototypeCall( + then, + body, + (val) => { + if (val != null) { + d.push(val) } + d.push(null) }, - preprocessor: { - pattern: /(^\s*)#.*/m, - lookbehind: true, - alias: 'property', - inside: { - // highlight preprocessor directives as keywords - directive: { - pattern: /(\s*#)\b(?:define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/, - lookbehind: true, - alias: 'keyword' - } - } + (err) => { + destroyer(d, err) } - }); - - Prism.languages.dotnet = Prism.languages.csharp; + ) + return (d = new Duplexify({ + objectMode: true, + writable: false, + read() {} + })) } -}; - -/***/ }), - -/***/ 12115: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'csp', - init: function init(Prism) { - /** - * Original by Scott Helme. - * - * Reference: https://scotthelme.co.uk/csp-cheat-sheet/ - * - * Supports the following: - * - CSP Level 1 - * - CSP Level 2 - * - CSP Level 3 - */ - - Prism.languages.csp = { - directive: { - pattern: /\b(?:(?:base-uri|form-action|frame-ancestors|plugin-types|referrer|reflected-xss|report-to|report-uri|require-sri-for|sandbox) |(?:block-all-mixed-content|disown-opener|upgrade-insecure-requests)(?: |;)|(?:child|connect|default|font|frame|img|manifest|media|object|script|style|worker)-src )/i, - alias: 'keyword' - }, - safe: { - pattern: /'(?:self|none|strict-dynamic|(?:nonce-|sha(?:256|384|512)-)[a-zA-Z\d+=/]+)'/, - alias: 'selector' - }, - unsafe: { - pattern: /(?:'unsafe-inline'|'unsafe-eval'|'unsafe-hashed-attributes'|\*)/, - alias: 'function' + throw new ERR_INVALID_ARG_TYPE( + name, + [ + 'Blob', + 'ReadableStream', + 'WritableStream', + 'Stream', + 'Iterable', + 'AsyncIterable', + 'Function', + '{ readable, writable } pair', + 'Promise' + ], + body + ) +} +function fromAsyncGen(fn) { + let { promise, resolve } = createDeferredPromise() + const ac = new AbortController() + const signal = ac.signal + const value = fn( + (async function* () { + while (true) { + const _promise = promise + promise = null + const { chunk, done, cb } = await _promise + process.nextTick(cb) + if (done) return + if (signal.aborted) + throw new AbortError(undefined, { + cause: signal.reason + }) + ;({ promise, resolve } = createDeferredPromise()) + yield chunk } - }; + })(), + { + signal + } + ) + return { + value, + write(chunk, encoding, cb) { + const _resolve = resolve + resolve = null + _resolve({ + chunk, + done: false, + cb + }) + }, + final(cb) { + const _resolve = resolve + resolve = null + _resolve({ + done: true, + cb + }) + }, + destroy(err, cb) { + ac.abort() + cb(err) + } + } +} +function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable + const w = pair.writable + let readable = !!isReadable(r) + let writable = !!isWritable(w) + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } } -}; - -/***/ }), - -/***/ 16590: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'css-extras', - init: function init(Prism) { - Prism.languages.css.selector = { - pattern: /[^{}\s][^{}]*(?=\s*\{)/, - inside: { - 'pseudo-element': /:(?:after|before|first-letter|first-line|selection)|::[-\w]+/, - 'pseudo-class': /:[-\w]+(?:\(.*\))?/, - class: /\.[-:.\w]+/, - id: /#[-:.\w]+/, - attribute: /\[[^\]]+\]/ + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), + readable, + writable + }) + if (writable) { + eos(w, (err) => { + writable = false + if (err) { + destroyer(r, err) } - }; - - Prism.languages.insertBefore('css', 'function', { - hexcode: /#[\da-f]{3,8}/i, - entity: /\\[\da-f]{1,8}/i, - number: /[\d%.]+/ - }); + onfinished(err) + }) + d._write = function (chunk, encoding, callback) { + if (w.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + w.end() + onfinish = callback + } + w.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + w.on('finish', function () { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) } -}; - -/***/ }), - -/***/ 58302: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'css', - init: function init(Prism) { - Prism.languages.css = { - comment: /\/\*[\s\S]*?\*\//, - atrule: { - pattern: /@[\w-]+?.*?(?:;|(?=\s*\{))/i, - inside: { - rule: /@[\w-]+/ - // See rest below - } - }, - url: /url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, - selector: /[^{}\s][^{};]*?(?=\s*\{)/, - string: { - pattern: /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - property: /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i, - important: /\B!important\b/i, - function: /[-a-z0-9]+(?=\()/i, - punctuation: /[(){};:]/ - }; - - Prism.languages.css.atrule.inside.rest = Prism.languages.css; - - if (Prism.languages.markup) { - Prism.languages.insertBefore('markup', 'tag', { - style: { - pattern: /()[\s\S]*?(?=<\/style>)/i, - lookbehind: true, - inside: Prism.languages.css, - alias: 'language-css', - greedy: true + if (readable) { + eos(r, (err) => { + readable = false + if (err) { + destroyer(r, err) + } + onfinished(err) + }) + r.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + r.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = r.read() + if (buf === null) { + onreadable = d._read + return } - }); - - Prism.languages.insertBefore('inside', 'attr-value', { - 'style-attr': { - pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i, - inside: { - 'attr-name': { - pattern: /^\s*style/i, - inside: Prism.languages.markup.tag.inside - }, - punctuation: /^\s*=\s*['"]|['"]\s*$/, - 'attr-value': { - pattern: /.+/i, - inside: Prism.languages.css - } - }, - alias: 'language-css' + if (!d.push(buf)) { + return } - }, Prism.languages.markup.tag); + } } } -}; + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + destroyer(w, err) + destroyer(r, err) + } + } + return d +} + /***/ }), -/***/ 60310: -/***/ ((__unused_webpack_module, exports) => { +/***/ 76080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'd', - init: function init(Prism) { - Prism.languages.d = Prism.languages.extend('clike', { - string: [ - // r"", x"" - /\b[rx]"(?:\\[\s\S]|[^\\"])*"[cwd]?/, - // q"[]", q"()", q"<>", q"{}" - /\bq"(?:\[[\s\S]*?\]|\([\s\S]*?\)|<[\s\S]*?>|\{[\s\S]*?\})"/, - // q"IDENT - // ... - // IDENT" - /\bq"([_a-zA-Z][_a-zA-Z\d]*)(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\1"/, - // q"//", q"||", etc. - /\bq"(.)[\s\S]*?\1"/, - // Characters - /'(?:\\'|\\?[^']+)'/, /(["`])(?:\\[\s\S]|(?!\1)[^\\])*\1[cwd]?/], - - number: [ - // The lookbehind and the negative look-ahead try to prevent bad highlighting of the .. operator - // Hexadecimal numbers must be handled separately to avoid problems with exponent "e" - /\b0x\.?[a-f\d_]+(?:(?!\.\.)\.[a-f\d_]*)?(?:p[+-]?[a-f\d_]+)?[ulfi]*/i, { - pattern: /((?:\.\.)?)(?:\b0b\.?|\b|\.)\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:e[+-]?\d[\d_]*)?[ulfi]*/i, - lookbehind: true - }], - // In order: $, keywords and special tokens, globally defined symbols - keyword: /\$|\b(?:abstract|alias|align|asm|assert|auto|body|bool|break|byte|case|cast|catch|cdouble|cent|cfloat|char|class|const|continue|creal|dchar|debug|default|delegate|delete|deprecated|do|double|else|enum|export|extern|false|final|finally|float|for|foreach|foreach_reverse|function|goto|idouble|if|ifloat|immutable|import|inout|int|interface|invariant|ireal|lazy|long|macro|mixin|module|new|nothrow|null|out|override|package|pragma|private|protected|public|pure|real|ref|return|scope|shared|short|static|struct|super|switch|synchronized|template|this|throw|true|try|typedef|typeid|typeof|ubyte|ucent|uint|ulong|union|unittest|ushort|version|void|volatile|wchar|while|with|__(?:(?:FILE|MODULE|LINE|FUNCTION|PRETTY_FUNCTION|DATE|EOF|TIME|TIMESTAMP|VENDOR|VERSION)__|gshared|traits|vector|parameters)|string|wstring|dstring|size_t|ptrdiff_t)\b/, - operator: /\|[|=]?|&[&=]?|\+[+=]?|-[-=]?|\.?\.\.|=[>=]?|!(?:i[ns]\b|<>?=?|>=?|=)?|\bi[ns]\b|(?:<[<>]?|>>?>?|\^\^|[*\/%^~])=?/ - }); +/* replacement start */ - Prism.languages.d.comment = [ - // Shebang - /^\s*#!.+/, - // /+ +/ - { - // Allow one level of nesting - pattern: /(^|[^\\])\/\+(?:\/\+[\s\S]*?\+\/|[\s\S])*?\+\//, - lookbehind: true - }].concat(Prism.languages.d.comment); +const process = __nccwpck_require__(45676) + +/* replacement end */ + +const { AbortError, codes } = __nccwpck_require__(80529) +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes +const { kEmptyObject, once } = __nccwpck_require__(46959) +const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = __nccwpck_require__(669) +const { Promise, PromisePrototypeThen, SymbolDispose } = __nccwpck_require__(89629) +const { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise +} = __nccwpck_require__(27981) +let addAbortListener +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function' +} +const nop = () => {} +function eos(stream, options, callback) { + var _options$readable, _options$writable + if (arguments.length === 2) { + callback = options + options = kEmptyObject + } else if (options == null) { + options = kEmptyObject + } else { + validateObject(options, 'options') + } + validateFunction(callback, 'callback') + validateAbortSignal(options.signal, 'options.signal') + callback = once(callback) + if (isReadableStream(stream) || isWritableStream(stream)) { + return eosWeb(stream, options, callback) + } + if (!isNodeStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + const readable = + (_options$readable = options.readable) !== null && _options$readable !== undefined + ? _options$readable + : isReadableNodeStream(stream) + const writable = + (_options$writable = options.writable) !== null && _options$writable !== undefined + ? _options$writable + : isWritableNodeStream(stream) + const wState = stream._writableState + const rState = stream._readableState + const onlegacyfinish = () => { + if (!stream.writable) { + onfinish() + } + } + + // TODO (ronag): Improve soft detection to include core modules and + // common ecosystem modules that do properly emit 'close' but fail + // this generic check. + let willEmitClose = + _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable + let writableFinished = isWritableFinished(stream, false) + const onfinish = () => { + writableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.readable || readable)) { + return + } + if (!readable || readableFinished) { + callback.call(stream) + } + } + let readableFinished = isReadableFinished(stream, false) + const onend = () => { + readableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.writable || writable)) { + return + } + if (!writable || writableFinished) { + callback.call(stream) + } + } + const onerror = (err) => { + callback.call(stream, err) + } + let closed = isClosed(stream) + const onclose = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + if (readable && !readableFinished && isReadableNodeStream(stream, true)) { + if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + if (writable && !writableFinished) { + if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + callback.call(stream) + } + const onclosed = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + callback.call(stream) + } + const onrequest = () => { + stream.req.on('finish', onfinish) + } + if (isRequest(stream)) { + stream.on('complete', onfinish) + if (!willEmitClose) { + stream.on('abort', onclose) + } + if (stream.req) { + onrequest() + } else { + stream.on('request', onrequest) + } + } else if (writable && !wState) { + // legacy streams + stream.on('end', onlegacyfinish) + stream.on('close', onlegacyfinish) + } - Prism.languages.insertBefore('d', 'comment', { - 'token-string': { - // Allow one level of nesting - pattern: /\bq\{(?:\{[^}]*\}|[^}])*\}/, - alias: 'string' + // Not all streams will emit 'close' after 'aborted'. + if (!willEmitClose && typeof stream.aborted === 'boolean') { + stream.on('aborted', onclose) + } + stream.on('end', onend) + stream.on('finish', onfinish) + if (options.error !== false) { + stream.on('error', onerror) + } + stream.on('close', onclose) + if (closed) { + process.nextTick(onclose) + } else if ( + (wState !== null && wState !== undefined && wState.errorEmitted) || + (rState !== null && rState !== undefined && rState.errorEmitted) + ) { + if (!willEmitClose) { + process.nextTick(onclosed) + } + } else if ( + !readable && + (!willEmitClose || isReadable(stream)) && + (writableFinished || isWritable(stream) === false) + ) { + process.nextTick(onclosed) + } else if ( + !writable && + (!willEmitClose || isWritable(stream)) && + (readableFinished || isReadable(stream) === false) + ) { + process.nextTick(onclosed) + } else if (rState && stream.req && stream.aborted) { + process.nextTick(onclosed) + } + const cleanup = () => { + callback = nop + stream.removeListener('aborted', onclose) + stream.removeListener('complete', onfinish) + stream.removeListener('abort', onclose) + stream.removeListener('request', onrequest) + if (stream.req) stream.req.removeListener('finish', onfinish) + stream.removeListener('end', onlegacyfinish) + stream.removeListener('close', onlegacyfinish) + stream.removeListener('finish', onfinish) + stream.removeListener('end', onend) + stream.removeListener('error', onerror) + stream.removeListener('close', onclose) + } + if (options.signal && !closed) { + const abort = () => { + // Keep it because cleanup removes it. + const endCallback = callback + cleanup() + endCallback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + return cleanup +} +function eosWeb(stream, options, callback) { + let isAborted = false + let abort = nop + if (options.signal) { + abort = () => { + isAborted = true + callback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + const resolverFn = (...args) => { + if (!isAborted) { + process.nextTick(() => callback.apply(stream, args)) + } + } + PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) + return nop +} +function finished(stream, opts) { + var _opts + let autoCleanup = false + if (opts === null) { + opts = kEmptyObject + } + if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { + validateBoolean(opts.cleanup, 'cleanup') + autoCleanup = opts.cleanup + } + return new Promise((resolve, reject) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup() } - }); - - Prism.languages.insertBefore('d', 'keyword', { - property: /\B@\w*/ - }); - - Prism.languages.insertBefore('d', 'function', { - register: { - // Iasm registers - pattern: /\b(?:[ABCD][LHX]|E[ABCD]X|E?(?:BP|SP|DI|SI)|[ECSDGF]S|CR[0234]|DR[012367]|TR[3-7]|X?MM[0-7]|R[ABCD]X|[BS]PL|R[BS]P|[DS]IL|R[DS]I|R(?:[89]|1[0-5])[BWD]?|XMM(?:[89]|1[0-5])|YMM(?:1[0-5]|\d))\b|\bST(?:\([0-7]\)|\b)/, - alias: 'variable' + if (err) { + reject(err) + } else { + resolve() } - }); - } -}; - -/***/ }), - -/***/ 14572: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'dart', - init: function init(Prism) { - Prism.languages.dart = Prism.languages.extend('clike', { - string: [{ - pattern: /r?("""|''')[\s\S]*?\1/, - greedy: true - }, { - pattern: /r?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/, - greedy: true - }], - keyword: [/\b(?:async|sync|yield)\*/, /\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|default|deferred|do|dynamic|else|enum|export|external|extends|factory|final|finally|for|get|if|implements|import|in|library|new|null|operator|part|rethrow|return|set|static|super|switch|this|throw|try|typedef|var|void|while|with|yield)\b/], - operator: /\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/ - }); + }) + }) +} +module.exports = eos +module.exports.finished = finished - Prism.languages.insertBefore('dart', 'function', { - metadata: { - pattern: /@\w+/, - alias: 'symbol' - } - }); - } -}; /***/ }), -/***/ 35844: -/***/ ((__unused_webpack_module, exports) => { +/***/ 39082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'diff', - init: function init(Prism) { - Prism.languages.diff = { - coord: [ - // Match all kinds of coord lines (prefixed by "+++", "---" or "***"). - /^(?:\*{3}|-{3}|\+{3}).*$/m, - // Match "@@ ... @@" coord lines in unified diff. - /^@@.*@@$/m, - // Match coord lines in normal diff (starts with a number). - /^\d+.*$/m], - - // Match inserted and deleted lines. Support both +/- and >/< styles. - deleted: /^[-<].*$/m, - inserted: /^[+>].*$/m, - - // Match "different" lines (prefixed with "!") in context diff. - diff: { - pattern: /^!(?!!).+$/m, - alias: 'important' - } - }; - } -}; - -/***/ }), - -/***/ 97535: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/* replacement start */ +const process = __nccwpck_require__(45676) -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = { - language: 'django', - init: function init(Prism) { - // Django/Jinja2 syntax definition for Prism.js syntax highlighter. - // Mostly it works OK but can paint code incorrectly on complex html/template tag combinations. +/* replacement end */ - var _django_template = { - property: { - pattern: /(?:{{|{%)[\s\S]*?(?:%}|}})/g, - greedy: true, - inside: { - string: { - pattern: /("|')(?:\\.|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - keyword: /\b(?:\||load|verbatim|widthratio|ssi|firstof|for|url|ifchanged|csrf_token|lorem|ifnotequal|autoescape|now|templatetag|debug|cycle|ifequal|regroup|comment|filter|endfilter|if|spaceless|with|extends|block|include|else|empty|endif|endfor|as|endblock|endautoescape|endverbatim|trans|endtrans|[Tt]rue|[Ff]alse|[Nn]one|in|is|static|macro|endmacro|call|endcall|set|endset|raw|endraw)\b/, - operator: /[-+=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/, - function: /\b(?:_|abs|add|addslashes|attr|batch|callable|capfirst|capitalize|center|count|cut|d|date|default|default_if_none|defined|dictsort|dictsortreversed|divisibleby|e|equalto|escape|escaped|escapejs|even|filesizeformat|first|float|floatformat|force_escape|forceescape|format|get_digit|groupby|indent|int|iriencode|iterable|join|last|length|length_is|linebreaks|linebreaksbr|linenumbers|list|ljust|lower|make_list|map|mapping|number|odd|phone2numeric|pluralize|pprint|random|reject|rejectattr|removetags|replace|reverse|rjust|round|safe|safeseq|sameas|select|selectattr|sequence|slice|slugify|sort|string|stringformat|striptags|sum|time|timesince|timeuntil|title|trim|truncate|truncatechars|truncatechars_html|truncatewords|truncatewords_html|undefined|unordered_list|upper|urlencode|urlize|urlizetrunc|wordcount|wordwrap|xmlattr|yesno)\b/, - important: /\b-?\d+(?:\.\d+)?\b/, - variable: /\b\w+?\b/, - punctuation: /[[\];(),.:]/ - } +const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = __nccwpck_require__(89629) +const { Buffer } = __nccwpck_require__(14300) +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = (__nccwpck_require__(80529).codes) +function from(Readable, iterable, opts) { + let iterator + if (typeof iterable === 'string' || iterable instanceof Buffer) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable) + this.push(null) } - }; - - Prism.languages.django = Prism.languages.extend('markup', { - comment: /(?:)/ - }); - // Updated html tag pattern to allow template tags inside html tags - Prism.languages.django.tag.pattern = /<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^>=]+))?)*\s*\/?>/i; - Prism.languages.insertBefore('django', 'entity', _django_template); - Prism.languages.insertBefore('inside', 'tag', _django_template, Prism.languages.django.tag); + }) + } + let isAsync + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true + iterator = iterable[SymbolAsyncIterator]() + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false + iterator = iterable[SymbolIterator]() + } else { + throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) + } + const readable = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }) - if (Prism.languages.javascript) { - // Combine js code and template tags painting inside