From 92a680299f49824119c2f8aa9257cf474acb8230 Mon Sep 17 00:00:00 2001 From: Petu Eusebiu Date: Thu, 29 Sep 2022 13:11:41 +0300 Subject: [PATCH] Added option to recursive build multiple stacker files Added option to specify stacker cache dir Added option to specify stacker version feat(dockerfile): added option to build images from dockerfiles Signed-off-by: Petu Eusebiu --- .github/workflows/ci.yaml | 26 +- README.md | 44 +- action.yml | 26 +- dist/index.js | 11780 +----------------------------- dist/licenses.txt | 618 ++ src/index.ts | 45 +- src/stacker.ts | 93 +- test/Dockerfile | 25 + test/builds/first/importfile1 | 1 + test/builds/first/stacker.yaml | 14 + test/builds/second/importfile2 | 1 + test/builds/second/stacker.yaml | 12 + test/builds/third/stacker.yaml | 16 + 13 files changed, 1193 insertions(+), 11508 deletions(-) create mode 100644 test/Dockerfile create mode 100644 test/builds/first/importfile1 create mode 100644 test/builds/first/stacker.yaml create mode 100644 test/builds/second/importfile2 create mode 100644 test/builds/second/stacker.yaml create mode 100644 test/builds/third/stacker.yaml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 035508a..18e74b1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -11,13 +11,22 @@ jobs: runs-on: ubuntu-latest services: registry: - image: registry:2 + image: ghcr.io/project-zot/zot-linux-amd64:latest ports: - 5000:5000 name: Test stacker-build-push-action steps: - uses: actions/checkout@v2 + - name: Run stacker-build with a Dockerfile + uses: ./ + with: + dockerfile: 'test/Dockerfile' + tags: v1 latest + url: docker://localhost:5000/four/app + layer-type: 'tar squashfs' + skip-tls: true + - name: Run stacker-build with all build inputs uses: ./ with: @@ -53,7 +62,7 @@ jobs: with: file: 'test/stacker_wo_subs.yaml' tags: v1 latest - url: docker://localhost:5000/name/app + url: docker://localhost:5000/one/app skip-tls: true - name: Run stacker-build with push, tags and build-args @@ -65,7 +74,7 @@ jobs: SUB2=VAR2 SUB3=VAR3 tags: v1 latest - url: docker://localhost:5000/name/app + url: docker://localhost:5000/two/app skip-tls: true - name: Run stacker-build with push, tags, build-args and layer-type @@ -77,6 +86,15 @@ jobs: SUB2=VAR2 SUB3=VAR3 tags: v1 latest - url: docker://localhost:5000/name/app + url: docker://localhost:5000/three/app + layer-type: 'tar squashfs' + skip-tls: true + + - name: Run stacker recursive-build + uses: ./ + with: + dir: 'test/builds' + tags: v2 + url: docker://localhost:5000/five/app layer-type: 'tar squashfs' skip-tls: true diff --git a/README.md b/README.md index 6d6f7f3..62d774c 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,26 @@ For more information about stacker tool see: https://github.com/project-stacker/ ## Action Inputs - + | Input Name | Type | Description | Default | | ---------- | ---- |----------- | ------- | -| file | string |the yaml file to be built as an OCI image, example: [stacker.yaml](./test/stacker.yaml) | stacker.yaml -| layer-type | list | output layer type (supported values: tar, squashfs), can be both separated by whitespace | tar -| build-args | list | the list of build-time arguments (subtitutes) separated by newline, see [stacker.yaml doc](https://github.com/project-stacker/stacker/blob/master/doc/stacker_yaml.md) | None +| file | string | path to yaml file to be built as an OCI image, example: [stacker.yaml](./test/stacker.yaml) | stacker.yaml +| dockerfile| string | path to dockerfile to be build as an OCI image(instead of stacker.yaml) | None +| cache-dir | string | stacker's cache directory | ./.stacker +| dir | string | directory under which to recursive search for stackerfiles to build, use either file or dir | None +| file-pattern| string | regex pattern to use when searching for stackerfile paths, used only with dir arg | \\/stacker.yaml$ +| layer-type | list | output layer type (supported values: tar, squashfs), ca be both separated by whitespace | tar +| build-args | list | the list of build-time arguments (subtitutes) separated by newline FOO=bar format, see [stacker.yaml doc](https://github.com/project-stacker/stacker/blob/master/doc/stacker_yaml.md) | None +| build-args-file | string | path to yaml file where build-args are set 'FOO: bar' yaml format | None | url | string | remote OCI registry + repo name eg: docker://ghcr.io/project-stacker/ | None | tags | list | one or more tags to give the new image, separated by whitespace | None | username | string | used to login to registry | None | password | string | used to login to registry | None | skip-tls | bool | used with unsecure (http) registries | false -| token | string |github token used to authenticate against a repository for Git context | ${{ github.token }} +| token | string | github token used to authenticate against a repository for Git context | ${{ github.token }} +| version | string | stacker version, see [stacker releases](https://github.com/project-stacker/stacker/releases) | v1.0.0-rc8 + Build only example: @@ -89,3 +96,30 @@ Build and push example to localhost: The above action will build test/stacker.yaml and push it to 1. docker://localhost:5000/test:test + +Build and push a Dockerfile: + +``` +- name: Run stacker-build with a Dockerfile + uses: ./ + with: + dockerfile: 'test/Dockerfile.yaml' + tags: v1 latest + url: docker://localhost:5000/four/app + layer-type: 'tar squashfs' + skip-tls: true +``` + + +Build recursively all stacker files under dir/ and push all: + +``` +- name: Run stacker recursive-build + uses: ./ + with: + dir: 'test/builds' + tags: v2 + url: docker://localhost:5000/five/app + layer-type: 'tar squashfs' + skip-tls: true +``` diff --git a/action.yml b/action.yml index 926c5f0..82ccc64 100644 --- a/action.yml +++ b/action.yml @@ -5,13 +5,27 @@ branding: color: 'blue' inputs: version: - description: 'Which stacker version to use' + description: 'Which stacker version to use, eg v0.40.3 see: https://github.com/project-stacker/stacker/releases' required: false - default: 'latest' + default: 'v1.0.0-rc8' file: description: 'Which stacker file to build' - required: true + required: false default: 'stacker.yaml' + dockerfile: + description: 'Which dockerfile to build(will be converted to stacker.yaml)' + required: false + cache-dir: + description: "stacker's cache directory" + required: false + default: '.stacker' + dir: + description: 'directory under which to recursively search for stackerfiles to build' + required: false + file-pattern: + description: 'regex pattern to use when searching for stackerfile paths, used with dir arg' + required: false + default: '\\/stacker.yaml$' layer-type: description: 'Set the output layer type (supported values: tar, squashfs) separated by whitespace' required: false @@ -30,13 +44,13 @@ inputs: description: 'Remote registry URL, eg: docker://ghcr.io/myRepo' required: false username: - description: "Username for the remote registry" + description: 'Username for the remote registry' required: false password: - description: "Password for the remote registry" + description: 'Password for the remote registry' required: false skip-tls: - description: "Skip tls verify on unsecure http registry" + description: 'Skip tls verify on unsecure http registry' required: false runs: using: 'node16' diff --git a/dist/index.js b/dist/index.js index bb55d18..5d2fd17 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1334,6 +1334,221 @@ class ExecState extends events.EventEmitter { /***/ }), +/***/ 5009: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(2037); +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 + +/***/ }), + +/***/ 1528: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(5009)); +const utils_1 = __nccwpck_require__(2815); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options) { + return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); +} +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 6064: +/***/ (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__(7307)); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 2815: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(5009)); +const Utils = __importStar(__nccwpck_require__(6064)); +// octokit + plugins +const core_1 = __nccwpck_require__(8299); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(6943); +const plugin_paginate_rest_1 = __nccwpck_require__(6045); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +const defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + /***/ 7826: /***/ ((__unused_webpack_module, exports) => { @@ -3437,1884 +3652,6 @@ function _unique(values) { } //# sourceMappingURL=tool-cache.js.map -/***/ }), - -/***/ 5150: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var core = __nccwpck_require__(8299); -var authApp = __nccwpck_require__(5176); -var oauthApp = __nccwpck_require__(2804); -var authUnauthenticated = __nccwpck_require__(1851); -var webhooks$1 = __nccwpck_require__(5080); -var pluginPaginateRest = __nccwpck_require__(6045); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator]; - if (method == null && Symbol.iterator) method = iterable[Symbol.iterator]; - } - - if (method == null) method = iterable["@@asyncIterator"]; - if (method == null) method = iterable["@@iterator"]; - if (method == null) throw new TypeError("Object is not async iterable"); - return method.call(iterable); -} - -function _AwaitValue(value) { - this.wrapped = value; -} - -function _AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - var wrappedAwait = value instanceof _AwaitValue; - Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { - if (wrappedAwait) { - resume(key === "return" ? "return" : "next", arg); - return; - } - - settle(result.done ? "return" : "normal", arg); - }, function (err) { - resume("throw", err); - }); - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } -} - -_AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { - return this; -}; - -_AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); -}; - -_AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); -}; - -_AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); -}; - -function _wrapAsyncGenerator(fn) { - return function () { - return new _AsyncGenerator(fn.apply(this, arguments)); - }; -} - -function _awaitAsyncGenerator(value) { - return new _AwaitValue(value); -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const VERSION = "12.0.5"; - -function webhooks(appOctokit, options // Explict return type for better debugability and performance, -// see https://github.com/octokit/app.js/pull/201 -) { - return new webhooks$1.Webhooks({ - secret: options.secret, - transform: async event => { - if (!("installation" in event.payload) || typeof event.payload.installation !== "object") { - const octokit = new appOctokit.constructor({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `"installation" key missing in webhook event payload` - } - }); - return _objectSpread2(_objectSpread2({}, event), {}, { - octokit: octokit - }); - } - - const installationId = event.payload.installation.id; - const octokit = await appOctokit.auth({ - type: "installation", - installationId, - - factory(auth) { - return new auth.octokit.constructor(_objectSpread2(_objectSpread2({}, auth.octokitOptions), {}, { - authStrategy: authApp.createAppAuth - }, { - auth: _objectSpread2(_objectSpread2({}, auth), {}, { - installationId - }) - })); - } - - }); - return _objectSpread2(_objectSpread2({}, event), {}, { - octokit: octokit - }); - } - }); -} - -async function getInstallationOctokit(app, installationId) { - return app.octokit.auth({ - type: "installation", - installationId: installationId, - - factory(auth) { - const options = _objectSpread2(_objectSpread2({}, auth.octokitOptions), {}, { - authStrategy: authApp.createAppAuth - }, { - auth: _objectSpread2(_objectSpread2({}, auth), {}, { - installationId: installationId - }) - }); - - return new auth.octokit.constructor(options); - } - - }); -} - -function eachInstallationFactory(app) { - return Object.assign(eachInstallation.bind(null, app), { - iterator: eachInstallationIterator.bind(null, app) - }); -} -async function eachInstallation(app, callback) { - const i = eachInstallationIterator(app)[Symbol.asyncIterator](); - let result = await i.next(); - - while (!result.done) { - await callback(result.value); - result = await i.next(); - } -} -function eachInstallationIterator(app) { - return { - [Symbol.asyncIterator]() { - return _wrapAsyncGenerator(function* () { - const iterator = pluginPaginateRest.composePaginateRest.iterator(app.octokit, "GET /app/installations"); - var _iteratorAbruptCompletion = false; - var _didIteratorError = false; - - var _iteratorError; - - try { - for (var _iterator = _asyncIterator(iterator), _step; _iteratorAbruptCompletion = !(_step = yield _awaitAsyncGenerator(_iterator.next())).done; _iteratorAbruptCompletion = false) { - const { - data: installations - } = _step.value; - - for (const installation of installations) { - const installationOctokit = yield _awaitAsyncGenerator(getInstallationOctokit(app, installation.id)); - yield { - octokit: installationOctokit, - installation - }; - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (_iteratorAbruptCompletion && _iterator.return != null) { - yield _awaitAsyncGenerator(_iterator.return()); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - })(); - } - - }; -} - -function eachRepositoryFactory(app) { - return Object.assign(eachRepository.bind(null, app), { - iterator: eachRepositoryIterator.bind(null, app) - }); -} -async function eachRepository(app, queryOrCallback, callback) { - const i = eachRepositoryIterator(app, callback ? queryOrCallback : undefined)[Symbol.asyncIterator](); - let result = await i.next(); - - while (!result.done) { - if (callback) { - await callback(result.value); - } else { - await queryOrCallback(result.value); - } - - result = await i.next(); - } -} - -function singleInstallationIterator(app, installationId) { - return { - [Symbol.asyncIterator]() { - return _wrapAsyncGenerator(function* () { - yield { - octokit: yield _awaitAsyncGenerator(app.getInstallationOctokit(installationId)) - }; - })(); - } - - }; -} - -function eachRepositoryIterator(app, query) { - return { - [Symbol.asyncIterator]() { - return _wrapAsyncGenerator(function* () { - const iterator = query ? singleInstallationIterator(app, query.installationId) : app.eachInstallation.iterator(); - var _iteratorAbruptCompletion = false; - var _didIteratorError = false; - - var _iteratorError; - - try { - for (var _iterator = _asyncIterator(iterator), _step; _iteratorAbruptCompletion = !(_step = yield _awaitAsyncGenerator(_iterator.next())).done; _iteratorAbruptCompletion = false) { - const { - octokit - } = _step.value; - const repositoriesIterator = pluginPaginateRest.composePaginateRest.iterator(octokit, "GET /installation/repositories"); - var _iteratorAbruptCompletion2 = false; - var _didIteratorError2 = false; - - var _iteratorError2; - - try { - for (var _iterator2 = _asyncIterator(repositoriesIterator), _step2; _iteratorAbruptCompletion2 = !(_step2 = yield _awaitAsyncGenerator(_iterator2.next())).done; _iteratorAbruptCompletion2 = false) { - const { - data: repositories - } = _step2.value; - - for (const repository of repositories) { - yield { - octokit: octokit, - repository - }; - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (_iteratorAbruptCompletion2 && _iterator2.return != null) { - yield _awaitAsyncGenerator(_iterator2.return()); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (_iteratorAbruptCompletion && _iterator.return != null) { - yield _awaitAsyncGenerator(_iterator.return()); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - })(); - } - - }; -} - -function onUnhandledRequestDefault(request, response) { - response.writeHead(404, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Unknown route: ${request.method} ${request.url}` - })); -} - -function noop() {} - -function createNodeMiddleware(app, options = {}) { - const log = Object.assign({ - debug: noop, - info: noop, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - - const optionsWithDefaults = _objectSpread2(_objectSpread2({ - onUnhandledRequest: onUnhandledRequestDefault, - pathPrefix: "/api/github" - }, options), {}, { - log - }); - - const webhooksMiddleware = webhooks$1.createNodeMiddleware(app.webhooks, { - path: optionsWithDefaults.pathPrefix + "/webhooks", - log, - onUnhandledRequest: optionsWithDefaults.onUnhandledRequest - }); - const oauthMiddleware = oauthApp.createNodeMiddleware(app.oauth, { - pathPrefix: optionsWithDefaults.pathPrefix + "/oauth", - onUnhandledRequest: optionsWithDefaults.onUnhandledRequest - }); - return middleware.bind(null, optionsWithDefaults, { - webhooksMiddleware, - oauthMiddleware - }); -} -async function middleware(options, { - webhooksMiddleware, - oauthMiddleware -}, request, response, next) { - const { - pathname - } = new URL(request.url, "http://localhost"); - - if (pathname === `${options.pathPrefix}/webhooks`) { - return webhooksMiddleware(request, response, next); - } - - if (pathname.startsWith(`${options.pathPrefix}/oauth/`)) { - return oauthMiddleware(request, response, next); - } - - const isExpressMiddleware = typeof next === "function"; - - if (isExpressMiddleware) { - // @ts-ignore `next` must be a function as we check two lines above - return next(); - } - - return options.onUnhandledRequest(request, response); -} - -class App { - constructor(options) { - const Octokit = options.Octokit || core.Octokit; - const authOptions = Object.assign({ - appId: options.appId, - privateKey: options.privateKey - }, options.oauth ? { - clientId: options.oauth.clientId, - clientSecret: options.oauth.clientSecret - } : {}); - this.octokit = new Octokit({ - authStrategy: authApp.createAppAuth, - auth: authOptions, - log: options.log - }); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); // set app.webhooks depending on whether "webhooks" option has been passed - - if (options.webhooks) { - // @ts-expect-error TODO: figure this out - this.webhooks = webhooks(this.octokit, options.webhooks); - } else { - Object.defineProperty(this, "webhooks", { - get() { - throw new Error("[@octokit/app] webhooks option not set"); - } - - }); - } // set app.oauth depending on whether "oauth" option has been passed - - - if (options.oauth) { - this.oauth = new oauthApp.OAuthApp(_objectSpread2(_objectSpread2({}, options.oauth), {}, { - clientType: "github-app", - Octokit - })); - } else { - Object.defineProperty(this, "oauth", { - get() { - throw new Error("[@octokit/app] oauth.clientId / oauth.clientSecret options are not set"); - } - - }); - } - - this.getInstallationOctokit = getInstallationOctokit.bind(null, this); - this.eachInstallation = eachInstallationFactory(this); - this.eachRepository = eachRepositoryFactory(this); - } - - static defaults(defaults) { - const AppWithDefaults = class extends this { - constructor(...args) { - super(_objectSpread2(_objectSpread2({}, defaults), args[0])); - } - - }; - return AppWithDefaults; - } - -} -App.VERSION = VERSION; - -exports.App = App; -exports.createNodeMiddleware = createNodeMiddleware; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 5176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(958); -var request = __nccwpck_require__(9436); -var authOauthApp = __nccwpck_require__(7207); -var deprecation = __nccwpck_require__(9325); -var universalGithubAppJwt = __nccwpck_require__(6988); -var LRU = _interopDefault(__nccwpck_require__(1493)); -var authOauthUser = __nccwpck_require__(2313); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -async function getAppAuthentication({ - appId, - privateKey, - timeDifference -}) { - try { - const appAuthentication = await universalGithubAppJwt.githubAppJwt({ - id: +appId, - privateKey, - now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference - }); - return { - type: "app", - token: appAuthentication.token, - appId: appAuthentication.appId, - expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() - }; - } catch (error) { - if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { - throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"); - } else { - throw error; - } - } -} - -// https://github.com/isaacs/node-lru-cache#readme -function getCache() { - return new LRU({ - // cache max. 15000 tokens, that will use less than 10mb memory - max: 15000, - // Cache for 1 minute less than GitHub expiry - maxAge: 1000 * 60 * 59 - }); -} -async function get(cache, options) { - const cacheKey = optionsToCacheKey(options); - const result = await cache.get(cacheKey); - - if (!result) { - return; - } - - const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); - const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { - if (/!$/.test(string)) { - permissions[string.slice(0, -1)] = "write"; - } else { - permissions[string] = "read"; - } - - return permissions; - }, {}); - return { - token, - createdAt, - expiresAt, - permissions, - repositoryIds: options.repositoryIds, - repositoryNames: options.repositoryNames, - singleFileName, - repositorySelection: repositorySelection - }; -} -async function set(cache, options, data) { - const key = optionsToCacheKey(options); - const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); - const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); - await cache.set(key, value); -} - -function optionsToCacheKey({ - installationId, - permissions = {}, - repositoryIds = [], - repositoryNames = [] -}) { - const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); - const repositoryIdsString = repositoryIds.sort().join(","); - const repositoryNamesString = repositoryNames.join(","); - return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|"); -} - -function toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName -}) { - return Object.assign({ - type: "token", - tokenType: "installation", - token, - installationId, - permissions, - createdAt, - expiresAt, - repositorySelection - }, repositoryIds ? { - repositoryIds - } : null, repositoryNames ? { - repositoryNames - } : null, singleFileName ? { - singleFileName - } : null); -} - -const _excluded = ["type", "factory", "oauthApp"]; -async function getInstallationAuthentication(state, options, customRequest) { - const installationId = Number(options.installationId || state.installationId); - - if (!installationId) { - throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); - } - - if (options.factory) { - const _state$options = _objectSpread2(_objectSpread2({}, state), options), - { - type, - factory, - oauthApp - } = _state$options, - factoryAuthOptions = _objectWithoutProperties(_state$options, _excluded); // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>` - - - return factory(factoryAuthOptions); - } - - const optionsWithInstallationTokenFromState = Object.assign({ - installationId - }, options); - - if (!options.refresh) { - const result = await get(state.cache, optionsWithInstallationTokenFromState); - - if (result) { - const { - token, - createdAt, - expiresAt, - permissions, - repositoryIds, - repositoryNames, - singleFileName, - repositorySelection - } = result; - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - permissions, - repositorySelection, - repositoryIds, - repositoryNames, - singleFileName - }); - } - } - - const appAuthentication = await getAppAuthentication(state); - const request = customRequest || state.request; - const { - data: { - token, - expires_at: expiresAt, - repositories, - permissions: permissionsOptional, - repository_selection: repositorySelectionOptional, - single_file: singleFileName - } - } = await request("POST /app/installations/{installation_id}/access_tokens", { - installation_id: installationId, - repository_ids: options.repositoryIds, - repositories: options.repositoryNames, - permissions: options.permissions, - mediaType: { - previews: ["machine-man"] - }, - headers: { - authorization: `bearer ${appAuthentication.token}` - } - }); - /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */ - - const permissions = permissionsOptional || {}; - /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */ - - const repositorySelection = repositorySelectionOptional || "all"; - const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; - const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0; - const createdAt = new Date().toISOString(); - await set(state.cache, optionsWithInstallationTokenFromState, { - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName - }); - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - repositoryNames, - singleFileName - }); -} - -async function auth(state, authOptions) { - switch (authOptions.type) { - case "app": - return getAppAuthentication(state); - // @ts-expect-error "oauth" is not supperted in types - - case "oauth": - state.log.warn( // @ts-expect-error `log.warn()` expects string - new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`)); - - case "oauth-app": - return state.oauthApp({ - type: "oauth-app" - }); - - case "installation": - return getInstallationAuthentication(state, _objectSpread2(_objectSpread2({}, authOptions), {}, { - type: "installation" - })); - - case "oauth-user": - // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions" - return state.oauthApp(authOptions); - - default: - // @ts-expect-error type is "never" at this point - throw new Error(`Invalid auth type: ${authOptions.type}`); - } -} - -const PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) -// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js - -function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/{org}/invitations", - "/repos/{owner}/{repo}/collaborators/{username}" - ] */ - const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - - return new RegExp(regex, "i"); -} - -const REGEX = routeMatcher(PATHS); -function requiresAppAuth(url) { - return !!url && REGEX.test(url); -} - -const FIVE_SECONDS_IN_MS = 5 * 1000; - -function isNotTimeSkewError(error) { - return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); -} - -async function hook(state, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - const url = endpoint.url; // Do not intercept request to retrieve a new token - - if (/\/login\/oauth\/access_token$/.test(url)) { - return request(endpoint); - } - - if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { - const { - token - } = await getAppAuthentication(state); - endpoint.headers.authorization = `bearer ${token}`; - let response; - - try { - response = await request(endpoint); - } catch (error) { - // If there's an issue with the expiration, regenerate the token and try again. - // Otherwise rethrow the error for upstream handling. - if (isNotTimeSkewError(error)) { - throw error; - } // If the date header is missing, we can't correct the system time skew. - // Throw the error to be handled upstream. - - - if (typeof error.response.headers.date === "undefined") { - throw error; - } - - const diff = Math.floor((Date.parse(error.response.headers.date) - Date.parse(new Date().toString())) / 1000); - state.log.warn(error.message); - state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); - const { - token - } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { - timeDifference: diff - })); - endpoint.headers.authorization = `bearer ${token}`; - return request(endpoint); - } - - return response; - } - - if (authOauthUser.requiresBasicAuth(url)) { - const authentication = await state.oauthApp({ - type: "oauth-app" - }); - endpoint.headers.authorization = authentication.headers.authorization; - return request(endpoint); - } - - const { - token, - createdAt - } = await getInstallationAuthentication(state, // @ts-expect-error TBD - {}, request); - endpoint.headers.authorization = `token ${token}`; - return sendRequestWithRetries(state, request, endpoint, createdAt); -} -/** - * Newly created tokens might not be accessible immediately after creation. - * In case of a 401 response, we retry with an exponential delay until more - * than five seconds pass since the creation of the token. - * - * @see https://github.com/octokit/auth-app.js/issues/65 - */ - -async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { - const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); - - try { - return await request(options); - } catch (error) { - if (error.status !== 401) { - throw error; - } - - if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { - if (retries > 0) { - error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; - } - - throw error; - } - - ++retries; - const awaitTime = retries * 1000; - state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); - await new Promise(resolve => setTimeout(resolve, awaitTime)); - return sendRequestWithRetries(state, request, options, createdAt, retries); - } -} - -const VERSION = "3.6.1"; - -function createAppAuth(options) { - if (!options.appId) { - throw new Error("[@octokit/auth-app] appId option is required"); - } - - if (!options.privateKey) { - throw new Error("[@octokit/auth-app] privateKey option is required"); - } - - if ("installationId" in options && !options.installationId) { - throw new Error("[@octokit/auth-app] installationId is set to a falsy value"); - } - - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); - const request$1 = options.request || request.request.defaults({ - headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }); - const state = Object.assign({ - request: request$1, - cache: getCache() - }, options, options.installationId ? { - installationId: Number(options.installationId) - } : {}, { - log, - oauthApp: authOauthApp.createOAuthAppAuth({ - clientType: "github-app", - clientId: options.clientId || "", - clientSecret: options.clientSecret || "", - request: request$1 - }) - }); // @ts-expect-error not worth the extra code to appease TS - - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -} - -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; - } -})); -exports.createAppAuth = createAppAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 7207: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(958); -var request = __nccwpck_require__(9436); -var btoa = _interopDefault(__nccwpck_require__(1119)); -var authOauthUser = __nccwpck_require__(2313); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const _excluded = ["type"]; -async function auth(state, authOptions) { - if (authOptions.type === "oauth-app") { - return { - type: "oauth-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType, - headers: { - authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` - } - }; - } - - if ("factory" in authOptions) { - const _authOptions$state = _objectSpread2(_objectSpread2({}, authOptions), state), - options = _objectWithoutProperties(_authOptions$state, _excluded); // @ts-expect-error TODO: `option` cannot be never, is this a bug? - - - return authOptions.factory(options); - } - - const common = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.request - }, authOptions); // TS: Look what you made me do - - - const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })) : await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })); - return userAuth(); -} - -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - - if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); - } - - if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) { - throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`); - } - - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); - endpoint.headers.authorization = `basic ${credentials}`; - - try { - return await request(endpoint); - } catch (error) { - /* istanbul ignore if */ - if (error.status !== 401) throw error; - error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`; - throw error; - } -} - -const VERSION = "4.3.0"; - -function createOAuthAppAuth(options) { - const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), - clientType: "oauth-app" - }, options); // @ts-expect-error not worth the extra code to appease TS - - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -} - -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; - } -})); -exports.createOAuthAppAuth = createOAuthAppAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 1296: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var universalUserAgent = __nccwpck_require__(958); -var request = __nccwpck_require__(9436); -var oauthMethods = __nccwpck_require__(9261); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -async function getOAuthAccessToken(state, options) { - const cachedAuthentication = getCachedAuthentication(state, options.auth); - if (cachedAuthentication) return cachedAuthentication; // Step 1: Request device and user codes - // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github - - const { - data: verification - } = await oauthMethods.createDeviceCode({ - clientType: state.clientType, - clientId: state.clientId, - request: options.request || state.request, - // @ts-expect-error the extra code to make TS happy is not worth it - scopes: options.auth.scopes || state.scopes - }); // Step 2: User must enter the user code on https://github.com/login/device - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser - - await state.onVerification(verification); // Step 3: Exchange device code for access token - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device - - const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification); - state.authentication = authentication; - return authentication; -} - -function getCachedAuthentication(state, auth) { - if (auth.refresh === true) return false; - if (!state.authentication) return false; - - if (state.clientType === "github-app") { - return state.authentication; - } - - const authentication = state.authentication; - const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" "); - const currentScope = authentication.scopes.join(" "); - return newScope === currentScope ? authentication : false; -} - -async function wait(seconds) { - await new Promise(resolve => setTimeout(resolve, seconds * 1000)); -} - -async function waitForAccessToken(request, clientId, clientType, verification) { - try { - const options = { - clientId, - request, - code: verification.device_code - }; // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME - - const { - authentication - } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { - clientType: "oauth-app" - })) : await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { - clientType: "github-app" - })); - return _objectSpread2({ - type: "token", - tokenType: "oauth" - }, authentication); - } catch (error) { - // istanbul ignore if - if (!error.response) throw error; - const errorType = error.response.data.error; - - if (errorType === "authorization_pending") { - await wait(verification.interval); - return waitForAccessToken(request, clientId, clientType, verification); - } - - if (errorType === "slow_down") { - await wait(verification.interval + 5); - return waitForAccessToken(request, clientId, clientType, verification); - } - - throw error; - } -} - -async function auth(state, authOptions) { - return getOAuthAccessToken(state, { - auth: authOptions - }); -} - -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept request to retrieve codes or token - - if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); - } - - const { - token - } = await getOAuthAccessToken(state, { - request, - auth: { - type: "oauth" - } - }); - endpoint.headers.authorization = `token ${token}`; - return request(endpoint); -} - -const VERSION = "3.1.2"; - -function createOAuthDeviceAuth(options) { - const requestWithDefaults = options.request || request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }); - - const { - request: request$1 = requestWithDefaults - } = options, - otherOptions = _objectWithoutProperties(options, ["request"]); - - const state = options.clientType === "github-app" ? _objectSpread2(_objectSpread2({}, otherOptions), {}, { - clientType: "github-app", - request: request$1 - }) : _objectSpread2(_objectSpread2({}, otherOptions), {}, { - clientType: "oauth-app", - request: request$1, - scopes: options.scopes || [] - }); - - if (!options.clientId) { - throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'); - } - - if (!options.onVerification) { - throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'); - } // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯ - - - return Object.assign(auth.bind(null, state), { - hook: hook.bind(null, state) - }); -} - -exports.createOAuthDeviceAuth = createOAuthDeviceAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 2313: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(958); -var request = __nccwpck_require__(9436); -var authOauthDevice = __nccwpck_require__(1296); -var oauthMethods = __nccwpck_require__(9261); -var btoa = _interopDefault(__nccwpck_require__(1119)); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const VERSION = "1.3.0"; - -async function getAuthentication(state) { - // handle code exchange form OAuth Web Flow - if ("code" in state.strategyOptions) { - const { - authentication - } = await oauthMethods.exchangeWebFlowCode(_objectSpread2(_objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions), {}, { - request: state.request - })); - return _objectSpread2({ - type: "token", - tokenType: "oauth" - }, authentication); - } // handle OAuth device flow - - - if ("onVerification" in state.strategyOptions) { - const deviceAuth = authOauthDevice.createOAuthDeviceAuth(_objectSpread2(_objectSpread2({ - clientType: state.clientType, - clientId: state.clientId - }, state.strategyOptions), {}, { - request: state.request - })); - const authentication = await deviceAuth({ - type: "oauth" - }); - return _objectSpread2({ - clientSecret: state.clientSecret - }, authentication); - } // use existing authentication - - - if ("token" in state.strategyOptions) { - return _objectSpread2({ - type: "token", - tokenType: "oauth", - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions); - } - - throw new Error("[@octokit/auth-oauth-user] Invalid strategy options"); -} - -async function auth(state, options = {}) { - if (!state.authentication) { - // This is what TS makes us do ¯\_(ツ)_/¯ - state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state); - } - - if (state.authentication.invalid) { - throw new Error("[@octokit/auth-oauth-user] Token is invalid"); - } - - const currentAuthentication = state.authentication; // (auto) refresh for user-to-server tokens - - if ("expiresAt" in currentAuthentication) { - if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) { - const { - authentication - } = await oauthMethods.refreshToken({ - clientType: "github-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - refreshToken: currentAuthentication.refreshToken, - request: state.request - }); - state.authentication = _objectSpread2({ - tokenType: "oauth", - type: "token" - }, authentication); - } - } // throw error for invalid refresh call - - - if (options.type === "refresh") { - if (state.clientType === "oauth-app") { - throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"); - } - - if (!currentAuthentication.hasOwnProperty("expiresAt")) { - throw new Error("[@octokit/auth-oauth-user] Refresh token missing"); - } - } // check or reset token - - - if (options.type === "check" || options.type === "reset") { - const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken; - - try { - const { - authentication - } = await method({ - // @ts-expect-error making TS happy would require unnecessary code so no - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: state.authentication.token, - request: state.request - }); - state.authentication = _objectSpread2({ - tokenType: "oauth", - type: "token" - }, authentication); - return state.authentication; - } catch (error) { - // istanbul ignore else - if (error.status === 404) { - error.message = "[@octokit/auth-oauth-user] Token is invalid"; // @ts-expect-error TBD - - state.authentication.invalid = true; - } - - throw error; - } - } // invalidate - - - if (options.type === "delete" || options.type === "deleteAuthorization") { - const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization; - - try { - await method({ - // @ts-expect-error making TS happy would require unnecessary code so no - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: state.authentication.token, - request: state.request - }); - } catch (error) { - // istanbul ignore if - if (error.status !== 404) throw error; - } - - state.authentication.invalid = true; - return state.authentication; - } - - return state.authentication; -} - -/** - * The following endpoints require an OAuth App to authenticate using its client_id and client_secret. - * - * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token - * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token - * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token - * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token - * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization - * - * deprecated: - * - * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization - * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization - * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application - * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application - */ -const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; -function requiresBasicAuth(url) { - return url && ROUTES_REQUIRING_BASIC_AUTH.test(url); -} - -async function hook(state, request, route, parameters = {}) { - const endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - - if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); - } - - if (requiresBasicAuth(endpoint.url)) { - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); - endpoint.headers.authorization = `basic ${credentials}`; - return request(endpoint); - } // TS makes us do this ¯\_(ツ)_/¯ - - - const { - token - } = state.clientType === "oauth-app" ? await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })) : await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })); - endpoint.headers.authorization = "token " + token; - return request(endpoint); -} - -const _excluded = ["clientId", "clientSecret", "clientType", "request"]; -function createOAuthUserAuth(_ref) { - let { - clientId, - clientSecret, - clientType = "oauth-app", - request: request$1 = request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }) - } = _ref, - strategyOptions = _objectWithoutProperties(_ref, _excluded); - - const state = Object.assign({ - clientType, - clientId, - clientSecret, - strategyOptions, - request: request$1 - }); // @ts-expect-error not worth the extra code needed to appease TS - - return Object.assign(auth.bind(null, state), { - // @ts-expect-error not worth the extra code needed to appease TS - hook: hook.bind(null, state) - }); -} -createOAuthUserAuth.VERSION = VERSION; - -exports.createOAuthUserAuth = createOAuthUserAuth; -exports.requiresBasicAuth = requiresBasicAuth; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 8746: @@ -5378,91 +3715,6 @@ exports.createTokenAuth = createTokenAuth; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 1851: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -async function auth(reason) { - return { - type: "unauthenticated", - reason - }; -} - -function isRateLimitError(error) { - if (error.status !== 403) { - return false; - } - /* istanbul ignore if */ - - - if (!error.response) { - return false; - } - - return error.response.headers["x-ratelimit-remaining"] === "0"; -} - -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; -function isAbuseLimitError(error) { - if (error.status !== 403) { - return false; - } - - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); -} - -async function hook(reason, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - return request(endpoint).catch(error => { - if (error.status === 404) { - error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; - throw error; - } - - if (isRateLimitError(error)) { - error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (isAbuseLimitError(error)) { - error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (error.status === 401) { - error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; - throw error; - } - - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); - } - - throw error; - }); -} - -const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { - if (!options || !options.reason) { - throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); - } - - return Object.assign(auth.bind(null, options.reason), { - hook: hook.bind(null, options.reason) - }); -}; - -exports.createUnauthenticatedAuth = createUnauthenticatedAuth; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 8299: @@ -6171,1368 +4423,6 @@ exports.withCustomRequest = withCustomRequest; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 2804: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var OAuthAppAuth = __nccwpck_require__(7207); -var core = __nccwpck_require__(8299); -var universalUserAgent = __nccwpck_require__(958); -var authOauthUser = __nccwpck_require__(2313); -var OAuthMethods = __nccwpck_require__(9261); -var authUnauthenticated = __nccwpck_require__(1851); -var fromEntries = _interopDefault(__nccwpck_require__(8257)); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const VERSION = "3.6.0"; - -function addEventHandler(state, eventName, eventHandler) { - if (Array.isArray(eventName)) { - for (const singleEventName of eventName) { - addEventHandler(state, singleEventName, eventHandler); - } - - return; - } - - if (!state.eventHandlers[eventName]) { - state.eventHandlers[eventName] = []; - } - - state.eventHandlers[eventName].push(eventHandler); -} - -const OAuthAppOctokit = core.Octokit.defaults({ - userAgent: `octokit-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` -}); - -async function emitEvent(state, context) { - const { - name, - action - } = context; - - if (state.eventHandlers[`${name}.${action}`]) { - for (const eventHandler of state.eventHandlers[`${name}.${action}`]) { - await eventHandler(context); - } - } - - if (state.eventHandlers[name]) { - for (const eventHandler of state.eventHandlers[name]) { - await eventHandler(context); - } - } -} - -async function getUserOctokitWithState(state, options) { - return state.octokit.auth(_objectSpread2(_objectSpread2({ - type: "oauth-user" - }, options), {}, { - async factory(options) { - const octokit = new state.Octokit({ - authStrategy: authOauthUser.createOAuthUserAuth, - auth: options - }); - const authentication = await octokit.auth({ - type: "get" - }); - await emitEvent(state, { - name: "token", - action: "created", - token: authentication.token, - scopes: authentication.scopes, - authentication, - octokit - }); - return octokit; - } - - })); -} - -function getWebFlowAuthorizationUrlWithState(state, options) { - const optionsWithDefaults = _objectSpread2(_objectSpread2({ - clientId: state.clientId, - request: state.octokit.request - }, options), {}, { - allowSignup: options.allowSignup || state.allowSignup, - scopes: options.scopes || state.defaultScopes - }); - - return OAuthMethods.getWebFlowAuthorizationUrl(_objectSpread2({ - clientType: state.clientType - }, optionsWithDefaults)); -} - -async function createTokenWithState(state, options) { - const authentication = await state.octokit.auth(_objectSpread2({ - type: "oauth-user" - }, options)); - await emitEvent(state, { - name: "token", - action: "created", - token: authentication.token, - scopes: authentication.scopes, - authentication, - octokit: new state.Octokit({ - authStrategy: OAuthAppAuth.createOAuthUserAuth, - auth: { - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: authentication.token, - scopes: authentication.scopes, - refreshToken: authentication.refreshToken, - expiresAt: authentication.expiresAt, - refreshTokenExpiresAt: authentication.refreshTokenExpiresAt - } - }) - }); - return { - authentication - }; -} - -async function checkTokenWithState(state, options) { - const result = await OAuthMethods.checkToken(_objectSpread2({ - // @ts-expect-error not worth the extra code to appease TS - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request - }, options)); - Object.assign(result.authentication, { - type: "token", - tokenType: "oauth" - }); - return result; -} - -async function resetTokenWithState(state, options) { - const optionsWithDefaults = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request - }, options); - - if (state.clientType === "oauth-app") { - const response = await OAuthMethods.resetToken(_objectSpread2({ - clientType: "oauth-app" - }, optionsWithDefaults)); - const authentication = Object.assign(response.authentication, { - type: "token", - tokenType: "oauth" - }); - await emitEvent(state, { - name: "token", - action: "reset", - token: response.authentication.token, - scopes: response.authentication.scopes || undefined, - authentication: authentication, - octokit: new state.Octokit({ - authStrategy: authOauthUser.createOAuthUserAuth, - auth: { - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: response.authentication.token, - scopes: response.authentication.scopes - } - }) - }); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); - } - - const response = await OAuthMethods.resetToken(_objectSpread2({ - clientType: "github-app" - }, optionsWithDefaults)); - const authentication = Object.assign(response.authentication, { - type: "token", - tokenType: "oauth" - }); - await emitEvent(state, { - name: "token", - action: "reset", - token: response.authentication.token, - authentication: authentication, - octokit: new state.Octokit({ - authStrategy: authOauthUser.createOAuthUserAuth, - auth: { - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: response.authentication.token - } - }) - }); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function refreshTokenWithState(state, options) { - if (state.clientType === "oauth-app") { - throw new Error("[@octokit/oauth-app] app.refreshToken() is not supported for OAuth Apps"); - } - - const response = await OAuthMethods.refreshToken({ - clientType: "github-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request, - refreshToken: options.refreshToken - }); - const authentication = Object.assign(response.authentication, { - type: "token", - tokenType: "oauth" - }); - await emitEvent(state, { - name: "token", - action: "refreshed", - token: response.authentication.token, - authentication: authentication, - octokit: new state.Octokit({ - authStrategy: authOauthUser.createOAuthUserAuth, - auth: { - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: response.authentication.token - } - }) - }); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function scopeTokenWithState(state, options) { - if (state.clientType === "oauth-app") { - throw new Error("[@octokit/oauth-app] app.scopeToken() is not supported for OAuth Apps"); - } - - const response = await OAuthMethods.scopeToken(_objectSpread2({ - clientType: "github-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request - }, options)); - const authentication = Object.assign(response.authentication, { - type: "token", - tokenType: "oauth" - }); - await emitEvent(state, { - name: "token", - action: "scoped", - token: response.authentication.token, - authentication: authentication, - octokit: new state.Octokit({ - authStrategy: authOauthUser.createOAuthUserAuth, - auth: { - clientType: state.clientType, - clientId: state.clientId, - clientSecret: state.clientSecret, - token: response.authentication.token - } - }) - }); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function deleteTokenWithState(state, options) { - const optionsWithDefaults = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request - }, options); - - const response = state.clientType === "oauth-app" ? await OAuthMethods.deleteToken(_objectSpread2({ - clientType: "oauth-app" - }, optionsWithDefaults)) : // istanbul ignore next - await OAuthMethods.deleteToken(_objectSpread2({ - clientType: "github-app" - }, optionsWithDefaults)); - await emitEvent(state, { - name: "token", - action: "deleted", - token: options.token, - octokit: new state.Octokit({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `Handling "token.deleted" event. The access for the token has been revoked.` - } - }) - }); - return response; -} - -async function deleteAuthorizationWithState(state, options) { - const optionsWithDefaults = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.octokit.request - }, options); - - const response = state.clientType === "oauth-app" ? await OAuthMethods.deleteAuthorization(_objectSpread2({ - clientType: "oauth-app" - }, optionsWithDefaults)) : // istanbul ignore next - await OAuthMethods.deleteAuthorization(_objectSpread2({ - clientType: "github-app" - }, optionsWithDefaults)); - await emitEvent(state, { - name: "token", - action: "deleted", - token: options.token, - octokit: new state.Octokit({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `Handling "token.deleted" event. The access for the token has been revoked.` - } - }) - }); - await emitEvent(state, { - name: "authorization", - action: "deleted", - token: options.token, - octokit: new state.Octokit({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `Handling "authorization.deleted" event. The access for the app has been revoked.` - } - }) - }); - return response; -} - -function parseRequest(request) { - const { - method, - url, - headers - } = request; - - async function text() { - const text = await new Promise((resolve, reject) => { - let bodyChunks = []; - request.on("error", reject).on("data", chunk => bodyChunks.push(chunk)).on("end", () => resolve(Buffer.concat(bodyChunks).toString())); - }); - return text; - } - - return { - method, - url, - headers, - text - }; -} - -function sendResponse(octokitResponse, response) { - response.writeHead(octokitResponse.status, octokitResponse.headers); - response.end(octokitResponse.text); -} - -function onUnhandledRequestDefault(request) { - return { - status: 404, - headers: { - "content-type": "application/json" - }, - text: JSON.stringify({ - error: `Unknown route: ${request.method} ${request.url}` - }) - }; -} - -async function handleRequest(app, { - pathPrefix = "/api/github/oauth" -}, request) { - if (request.method === "OPTIONS") { - return { - status: 200, - headers: { - "access-control-allow-origin": "*", - "access-control-allow-methods": "*", - "access-control-allow-headers": "Content-Type, User-Agent, Authorization" - } - }; - } // request.url may include ?query parameters which we don't want for `route` - // hence the workaround using new URL() - - - const { - pathname - } = new URL(request.url, "http://localhost"); - const route = [request.method, pathname].join(" "); - const routes = { - getLogin: `GET ${pathPrefix}/login`, - getCallback: `GET ${pathPrefix}/callback`, - createToken: `POST ${pathPrefix}/token`, - getToken: `GET ${pathPrefix}/token`, - patchToken: `PATCH ${pathPrefix}/token`, - patchRefreshToken: `PATCH ${pathPrefix}/refresh-token`, - scopeToken: `POST ${pathPrefix}/token/scoped`, - deleteToken: `DELETE ${pathPrefix}/token`, - deleteGrant: `DELETE ${pathPrefix}/grant` - }; // handle unknown routes - - if (!Object.values(routes).includes(route)) { - return null; - } - - let json; - - try { - const text = await request.text(); - json = text ? JSON.parse(text) : {}; - } catch (error) { - return { - status: 400, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify({ - error: "[@octokit/oauth-app] request error" - }) - }; - } - - const { - searchParams - } = new URL(request.url, "http://localhost"); - const query = fromEntries(searchParams); - const headers = request.headers; - - try { - var _headers$authorizatio6; - - if (route === routes.getLogin) { - const { - url - } = app.getWebFlowAuthorizationUrl({ - state: query.state, - scopes: query.scopes ? query.scopes.split(",") : undefined, - allowSignup: query.allowSignup !== "false", - redirectUrl: query.redirectUrl - }); - return { - status: 302, - headers: { - location: url - } - }; - } - - if (route === routes.getCallback) { - if (query.error) { - throw new Error(`[@octokit/oauth-app] ${query.error} ${query.error_description}`); - } - - if (!query.state || !query.code) { - throw new Error('[@octokit/oauth-app] Both "code" & "state" parameters are required'); - } - - const { - authentication: { - token - } - } = await app.createToken({ - state: query.state, - code: query.code - }); - return { - status: 200, - headers: { - "content-type": "text/html" - }, - text: `

Token created successfull

- -

Your token is: ${token}. Copy it now as it cannot be shown again.

` - }; - } - - if (route === routes.createToken) { - const { - state: oauthState, - code, - redirectUrl - } = json; - - if (!oauthState || !code) { - throw new Error('[@octokit/oauth-app] Both "code" & "state" parameters are required'); - } - - const result = await app.createToken({ - state: oauthState, - code, - redirectUrl - }); // @ts-ignore - - delete result.authentication.clientSecret; - return { - status: 201, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify(result) - }; - } - - if (route === routes.getToken) { - var _headers$authorizatio; - - const token = (_headers$authorizatio = headers.authorization) === null || _headers$authorizatio === void 0 ? void 0 : _headers$authorizatio.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - const result = await app.checkToken({ - token - }); // @ts-ignore - - delete result.authentication.clientSecret; - return { - status: 200, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify(result) - }; - } - - if (route === routes.patchToken) { - var _headers$authorizatio2; - - const token = (_headers$authorizatio2 = headers.authorization) === null || _headers$authorizatio2 === void 0 ? void 0 : _headers$authorizatio2.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - const result = await app.resetToken({ - token - }); // @ts-ignore - - delete result.authentication.clientSecret; - return { - status: 200, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify(result) - }; - } - - if (route === routes.patchRefreshToken) { - var _headers$authorizatio3; - - const token = (_headers$authorizatio3 = headers.authorization) === null || _headers$authorizatio3 === void 0 ? void 0 : _headers$authorizatio3.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - const { - refreshToken - } = json; - - if (!refreshToken) { - throw new Error("[@octokit/oauth-app] refreshToken must be sent in request body"); - } - - const result = await app.refreshToken({ - refreshToken - }); // @ts-ignore - - delete result.authentication.clientSecret; - return { - status: 200, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify(result) - }; - } - - if (route === routes.scopeToken) { - var _headers$authorizatio4; - - const token = (_headers$authorizatio4 = headers.authorization) === null || _headers$authorizatio4 === void 0 ? void 0 : _headers$authorizatio4.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - const result = await app.scopeToken(_objectSpread2({ - token - }, json)); // @ts-ignore - - delete result.authentication.clientSecret; - return { - status: 200, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify(result) - }; - } - - if (route === routes.deleteToken) { - var _headers$authorizatio5; - - const token = (_headers$authorizatio5 = headers.authorization) === null || _headers$authorizatio5 === void 0 ? void 0 : _headers$authorizatio5.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - await app.deleteToken({ - token - }); - return { - status: 204, - headers: { - "access-control-allow-origin": "*" - } - }; - } // route === routes.deleteGrant - - - const token = (_headers$authorizatio6 = headers.authorization) === null || _headers$authorizatio6 === void 0 ? void 0 : _headers$authorizatio6.substr("token ".length); - - if (!token) { - throw new Error('[@octokit/oauth-app] "Authorization" header is required'); - } - - await app.deleteAuthorization({ - token - }); - return { - status: 204, - headers: { - "access-control-allow-origin": "*" - } - }; - } catch (error) { - return { - status: 400, - headers: { - "content-type": "application/json", - "access-control-allow-origin": "*" - }, - text: JSON.stringify({ - error: error.message - }) - }; - } -} - -function onUnhandledRequestDefaultNode(request, response) { - const octokitRequest = parseRequest(request); - const octokitResponse = onUnhandledRequestDefault(octokitRequest); - sendResponse(octokitResponse, response); -} - -function createNodeMiddleware(app, { - pathPrefix, - onUnhandledRequest = onUnhandledRequestDefaultNode -} = {}) { - return async function (request, response, next) { - const octokitRequest = parseRequest(request); - const octokitResponse = await handleRequest(app, { - pathPrefix - }, octokitRequest); - - if (octokitResponse) { - sendResponse(octokitResponse, response); - } else if (typeof next === "function") { - next(); - } else { - onUnhandledRequest(request, response); - } - }; -} - -function parseRequest$1(request) { - // @ts-ignore Worker environment supports fromEntries/entries. - const headers = Object.fromEntries(request.headers.entries()); - return { - method: request.method, - url: request.url, - headers, - text: () => request.text() - }; -} - -function sendResponse$1(octokitResponse) { - return new Response(octokitResponse.text, { - status: octokitResponse.status, - headers: octokitResponse.headers - }); -} - -async function onUnhandledRequestDefaultCloudflare(request) { - const octokitRequest = parseRequest$1(request); - const octokitResponse = onUnhandledRequestDefault(octokitRequest); - return sendResponse$1(octokitResponse); -} - -function createCloudflareHandler(app, { - pathPrefix, - onUnhandledRequest = onUnhandledRequestDefaultCloudflare -} = {}) { - return async function (request) { - const octokitRequest = parseRequest$1(request); - const octokitResponse = await handleRequest(app, { - pathPrefix - }, octokitRequest); - return octokitResponse ? sendResponse$1(octokitResponse) : await onUnhandledRequest(request); - }; -} - -function parseRequest$2(request) { - const { - method - } = request.requestContext.http; - let url = request.rawPath; - const { - stage - } = request.requestContext; - if (url.startsWith("/" + stage)) url = url.substring(stage.length + 1); - if (request.rawQueryString) url += "?" + request.rawQueryString; - const headers = request.headers; - - const text = async () => request.body || ""; - - return { - method, - url, - headers, - text - }; -} - -function sendResponse$2(octokitResponse) { - return { - statusCode: octokitResponse.status, - headers: octokitResponse.headers, - body: octokitResponse.text - }; -} - -async function onUnhandledRequestDefaultAWSAPIGatewayV2(event) { - const request = parseRequest$2(event); - const response = onUnhandledRequestDefault(request); - return sendResponse$2(response); -} - -function createAWSLambdaAPIGatewayV2Handler(app, { - pathPrefix, - onUnhandledRequest = onUnhandledRequestDefaultAWSAPIGatewayV2 -} = {}) { - return async function (event) { - const request = parseRequest$2(event); - const response = await handleRequest(app, { - pathPrefix - }, request); - return response ? sendResponse$2(response) : onUnhandledRequest(event); - }; -} - -class OAuthApp { - constructor(options) { - const Octokit = options.Octokit || OAuthAppOctokit; - this.type = options.clientType || "oauth-app"; - const octokit = new Octokit({ - authStrategy: OAuthAppAuth.createOAuthAppAuth, - auth: { - clientType: this.type, - clientId: options.clientId, - clientSecret: options.clientSecret - } - }); - const state = { - clientType: this.type, - clientId: options.clientId, - clientSecret: options.clientSecret, - // @ts-expect-error defaultScopes not permitted for GitHub Apps - defaultScopes: options.defaultScopes || [], - allowSignup: options.allowSignup, - baseUrl: options.baseUrl, - log: options.log, - Octokit, - octokit, - eventHandlers: {} - }; - this.on = addEventHandler.bind(null, state); // @ts-expect-error TODO: figure this out - - this.octokit = octokit; - this.getUserOctokit = getUserOctokitWithState.bind(null, state); - this.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrlWithState.bind(null, state); - this.createToken = createTokenWithState.bind(null, state); - this.checkToken = checkTokenWithState.bind(null, state); - this.resetToken = resetTokenWithState.bind(null, state); - this.refreshToken = refreshTokenWithState.bind(null, state); - this.scopeToken = scopeTokenWithState.bind(null, state); - this.deleteToken = deleteTokenWithState.bind(null, state); - this.deleteAuthorization = deleteAuthorizationWithState.bind(null, state); - } - - static defaults(defaults) { - const OAuthAppWithDefaults = class extends this { - constructor(...args) { - super(_objectSpread2(_objectSpread2({}, defaults), args[0])); - } - - }; - return OAuthAppWithDefaults; - } - -} -OAuthApp.VERSION = VERSION; - -exports.OAuthApp = OAuthApp; -exports.createAWSLambdaAPIGatewayV2Handler = createAWSLambdaAPIGatewayV2Handler; -exports.createCloudflareHandler = createCloudflareHandler; -exports.createNodeMiddleware = createNodeMiddleware; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 3063: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function oauthAuthorizationUrl(options) { - const clientType = options.clientType || "oauth-app"; - const baseUrl = options.baseUrl || "https://github.com"; - const result = { - clientType, - allowSignup: options.allowSignup === false ? false : true, - clientId: options.clientId, - login: options.login || null, - redirectUrl: options.redirectUrl || null, - state: options.state || Math.random().toString(36).substr(2), - url: "" - }; - - if (clientType === "oauth-app") { - const scopes = "scopes" in options ? options.scopes : []; - result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes; - } - - result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result); - return result; -} - -function urlBuilderAuthorize(base, options) { - const map = { - allowSignup: "allow_signup", - clientId: "client_id", - login: "login", - redirectUrl: "redirect_uri", - scopes: "scope", - state: "state" - }; - let url = base; - Object.keys(map) // Filter out keys that are null and remove the url key - .filter(k => options[k] !== null) // Filter out empty scopes array - .filter(k => { - if (k !== "scopes") return true; - if (options.clientType === "github-app") return false; - return !Array.isArray(options[k]) || options[k].length > 0; - }) // Map Array with the proper URL parameter names and change the value to a string using template strings - // @ts-ignore - .map(key => [map[key], `${options[key]}`]) // Finally, build the URL - .forEach(([key, value], index) => { - url += index === 0 ? `?` : "&"; - url += `${key}=${encodeURIComponent(value)}`; - }); - return url; -} - -exports.oauthAuthorizationUrl = oauthAuthorizationUrl; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 9261: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var oauthAuthorizationUrl = __nccwpck_require__(3063); -var request = __nccwpck_require__(9436); -var requestError = __nccwpck_require__(4381); -var btoa = _interopDefault(__nccwpck_require__(1119)); - -const VERSION = "1.2.6"; - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -function requestToOAuthBaseUrl(request) { - const endpointDefaults = request.endpoint.DEFAULTS; - return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); -} -async function oauthRequest(request, route, parameters) { - const withOAuthParameters = _objectSpread2({ - baseUrl: requestToOAuthBaseUrl(request), - headers: { - accept: "application/json" - } - }, parameters); - - const response = await request(route, withOAuthParameters); - - if ("error" in response.data) { - const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { - request: request.endpoint.merge(route, withOAuthParameters), - headers: response.headers - }); // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved - - error.response = response; - throw error; - } - - return response; -} - -const _excluded = ["request"]; -function getWebFlowAuthorizationUrl(_ref) { - let { - request: request$1 = request.request - } = _ref, - options = _objectWithoutProperties(_ref, _excluded); - - const baseUrl = requestToOAuthBaseUrl(request$1); // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯ - - return oauthAuthorizationUrl.oauthAuthorizationUrl(_objectSpread2(_objectSpread2({}, options), {}, { - baseUrl - })); -} - -async function exchangeWebFlowCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - code: options.code, - redirect_uri: options.redirectUrl - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.access_token, - scopes: response.data.scope.split(/\s+/).filter(Boolean) - }; - - if (options.clientType === "github-app") { - if ("refresh_token" in response.data) { - const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in); - } - - delete authentication.scopes; - } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -function toTimestamp(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); -} - -async function createDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const parameters = { - client_id: options.clientId - }; - - if ("scopes" in options && Array.isArray(options.scopes)) { - parameters.scope = options.scopes.join(" "); - } - - return oauthRequest(request$1, "POST /login/device/code", parameters); -} - -async function exchangeDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - device_code: options.code, - grant_type: "urn:ietf:params:oauth:grant-type:device_code" - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - token: response.data.access_token, - scopes: response.data.scope.split(/\s+/).filter(Boolean) - }; - - if ("clientSecret" in options) { - authentication.clientSecret = options.clientSecret; - } - - if (options.clientType === "github-app") { - if ("refresh_token" in response.data) { - const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in); - } - - delete authentication.scopes; - } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -function toTimestamp$1(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); -} - -async function checkToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await request$1("POST /applications/{client_id}/token", { - headers: { - authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` - }, - client_id: options.clientId, - access_token: options.token - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: options.token, - scopes: response.data.scopes - }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; - - if (options.clientType === "github-app") { - delete authentication.scopes; - } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function refreshToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - grant_type: "refresh_token", - refresh_token: options.refreshToken - }); - const apiTimeInMs = new Date(response.headers.date).getTime(); - const authentication = { - clientType: "github-app", - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.access_token, - refreshToken: response.data.refresh_token, - expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in), - refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in) - }; - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -function toTimestamp$2(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); -} - -const _excluded$1 = ["request", "clientType", "clientId", "clientSecret", "token"]; -async function scopeToken(options) { - const { - request: request$1, - clientType, - clientId, - clientSecret, - token - } = options, - requestOptions = _objectWithoutProperties(options, _excluded$1); - - const response = await (request$1 || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request)("POST /applications/{client_id}/token/scoped", _objectSpread2({ - headers: { - authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}` - }, - client_id: clientId, - access_token: token - }, requestOptions)); - const authentication = Object.assign({ - clientType, - clientId, - clientSecret, - token: response.data.token - }, response.data.expires_at ? { - expiresAt: response.data.expires_at - } : {}); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function resetToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - const response = await request$1("PATCH /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); - const authentication = { - clientType: options.clientType, - clientId: options.clientId, - clientSecret: options.clientSecret, - token: response.data.token, - scopes: response.data.scopes - }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; - - if (options.clientType === "github-app") { - delete authentication.scopes; - } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); -} - -async function deleteToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); -} - -async function deleteAuthorization(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/grant", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); -} - -exports.VERSION = VERSION; -exports.checkToken = checkToken; -exports.createDeviceCode = createDeviceCode; -exports.deleteAuthorization = deleteAuthorization; -exports.deleteToken = deleteToken; -exports.exchangeDeviceCode = exchangeDeviceCode; -exports.exchangeWebFlowCode = exchangeWebFlowCode; -exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl; -exports.refreshToken = refreshToken; -exports.resetToken = resetToken; -exports.scopeToken = scopeToken; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 6045: @@ -8791,90 +5681,6 @@ exports.restEndpointMethods = restEndpointMethods; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 4064: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Bottleneck = _interopDefault(__nccwpck_require__(994)); - -// @ts-ignore -async function errorRequest(octokit, state, error, options) { - if (!error.request || !error.request.request) { - // address https://github.com/octokit/plugin-retry.js/issues/8 - throw error; - } // retry all >= 400 && not doNotRetry - - - if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error, retries, retryAfter); - } // Maybe eventually there will be more cases here - - - throw error; -} - -// @ts-ignore - -async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); // @ts-ignore - - limiter.on("failed", function (error, info) { - const maxRetries = ~~error.request.request.retries; - const after = ~~error.request.request.retryAfter; - options.request.retryCount = info.retryCount + 1; - - if (maxRetries > info.retryCount) { - // Returning a number instructs the limiter to retry - // the request after that number of milliseconds have passed - return after * state.retryAfterBaseValue; - } - }); - return limiter.schedule(request, options); -} - -const VERSION = "3.0.9"; -function retry(octokit, octokitOptions) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1000, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - - if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); - } - - return { - retry: { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter - }); - return error; - } - } - }; -} -retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 4381: @@ -9142,569 +5948,6 @@ exports.request = request; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 6670: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var crypto = __nccwpck_require__(6113); -var buffer = __nccwpck_require__(4300); - -const VERSION = "2.0.0"; - -var Algorithm; - -(function (Algorithm) { - Algorithm["SHA1"] = "sha1"; - Algorithm["SHA256"] = "sha256"; -})(Algorithm || (Algorithm = {})); - -async function sign(options, payload) { - const { - secret, - algorithm - } = typeof options === "object" ? { - secret: options.secret, - algorithm: options.algorithm || Algorithm.SHA256 - } : { - secret: options, - algorithm: Algorithm.SHA256 - }; - - if (!secret || !payload) { - throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()"); - } - - if (!Object.values(Algorithm).includes(algorithm)) { - throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); - } - - return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; -} -sign.VERSION = VERSION; - -const getAlgorithm = signature => { - return signature.startsWith("sha256=") ? "sha256" : "sha1"; -}; - -async function verify(secret, eventPayload, signature) { - if (!secret || !eventPayload || !signature) { - throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required"); - } - - const signatureBuffer = buffer.Buffer.from(signature); - const algorithm = getAlgorithm(signature); - const verificationBuffer = buffer.Buffer.from(await sign({ - secret, - algorithm - }, eventPayload)); - - if (signatureBuffer.length !== verificationBuffer.length) { - return false; - } // constant time comparison to prevent timing attachs - // https://stackoverflow.com/a/31096242/206879 - // https://en.wikipedia.org/wiki/Timing_attack - - - return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); -} -verify.VERSION = VERSION; - -exports.sign = sign; -exports.verify = verify; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 5080: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var AggregateError = _interopDefault(__nccwpck_require__(6840)); -var webhooksMethods = __nccwpck_require__(6670); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const createLogger = logger => _objectSpread2({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) -}, logger); - -// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY -// make edits in scripts/generate-types.ts -const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.reopen", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_run", "workflow_run.completed", "workflow_run.requested"]; - -function handleEventHandlers(state, webhookName, handler) { - if (!state.hooks[webhookName]) { - state.hooks[webhookName] = []; - } - - state.hooks[webhookName].push(handler); -} - -function receiverOn(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); - return; - } - - if (["*", "error"].includes(webhookNameOrNames)) { - const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; - const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`; - throw new Error(message); - } - - if (!emitterEventNames.includes(webhookNameOrNames)) { - state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); - } - - handleEventHandlers(state, webhookNameOrNames, handler); -} -function receiverOnAny(state, handler) { - handleEventHandlers(state, "*", handler); -} -function receiverOnError(state, handler) { - handleEventHandlers(state, "error", handler); -} - -// Errors thrown or rejected Promises in "error" event handlers are not handled -// as they are in the webhook event handlers. If errors occur, we log a -// "Fatal: Error occurred" message to stdout -function wrapErrorHandler(handler, error) { - let returnValue; - - try { - returnValue = handler(error); - } catch (error) { - console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); - } - - if (returnValue && returnValue.catch) { - returnValue.catch(error => { - console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); - }); - } -} - -// @ts-ignore to address #245 - -function getHooks(state, eventPayloadAction, eventName) { - const hooks = [state.hooks[eventName], state.hooks["*"]]; - - if (eventPayloadAction) { - hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]); - } - - return [].concat(...hooks.filter(Boolean)); -} // main handler function - - -function receiverHandle(state, event) { - const errorHandlers = state.hooks.error || []; - - if (event instanceof Error) { - const error = Object.assign(new AggregateError([event]), { - event, - errors: [event] - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - return Promise.reject(error); - } - - if (!event || !event.name) { - throw new AggregateError(["Event name not passed"]); - } - - if (!event.payload) { - throw new AggregateError(["Event payload not passed"]); - } // flatten arrays of event listeners and remove undefined values - - - const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name); - - if (hooks.length === 0) { - return Promise.resolve(); - } - - const errors = []; - const promises = hooks.map(handler => { - let promise = Promise.resolve(event); - - if (state.transform) { - promise = promise.then(state.transform); - } - - return promise.then(event => { - return handler(event); - }).catch(error => errors.push(Object.assign(error, { - event - }))); - }); - return Promise.all(promises).then(() => { - if (errors.length === 0) { - return; - } - - const error = new AggregateError(errors); - Object.assign(error, { - event, - errors - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - throw error; - }); -} - -function removeListener(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); - return; - } - - if (!state.hooks[webhookNameOrNames]) { - return; - } // remove last hook that has been added, that way - // it behaves the same as removeListener - - - for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { - if (state.hooks[webhookNameOrNames][i] === handler) { - state.hooks[webhookNameOrNames].splice(i, 1); - return; - } - } -} - -function createEventHandler(options) { - const state = { - hooks: {}, - log: createLogger(options && options.log) - }; - - if (options && options.transform) { - state.transform = options.transform; - } - - return { - on: receiverOn.bind(null, state), - onAny: receiverOnAny.bind(null, state), - onError: receiverOnError.bind(null, state), - removeListener: removeListener.bind(null, state), - receive: receiverHandle.bind(null, state) - }; -} - -/** - * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end - */ -function toNormalizedJsonString(payload) { - const payloadString = JSON.stringify(payload); - return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => { - return s.substr(0, 3) + s.substr(3).toUpperCase(); - }); -} - -async function sign(secret, payload) { - return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload)); -} - -async function verify(secret, payload, signature) { - return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature); -} - -async function verifyAndReceive(state, event) { - // verify will validate that the secret is not undefined - const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature); - - if (!matchesSignature) { - const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); - return state.eventHandler.receive(Object.assign(error, { - event, - status: 400 - })); - } - - return state.eventHandler.receive({ - id: event.id, - name: event.name, - payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload - }); -} - -const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers - -function getMissingHeaders(request) { - return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); -} - -// @ts-ignore to address #245 -function getPayload(request) { - // If request.body already exists we can stop here - // See https://github.com/octokit/webhooks.js/pull/23 - if (request.body) return Promise.resolve(request.body); - return new Promise((resolve, reject) => { - let data = ""; - request.setEncoding("utf8"); // istanbul ignore next - - request.on("error", error => reject(new AggregateError([error]))); - request.on("data", chunk => data += chunk); - request.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (error) { - error.message = "Invalid JSON"; - error.status = 400; - reject(new AggregateError([error])); - } - }); - }); -} - -async function middleware(webhooks, options, request, response, next) { - let pathname; - - try { - pathname = new URL(request.url, "http://localhost").pathname; - } catch (error) { - response.writeHead(422, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Request URL could not be parsed: ${request.url}` - })); - return; - } - - const isUnknownRoute = request.method !== "POST" || pathname !== options.path; - const isExpressMiddleware = typeof next === "function"; - - if (isUnknownRoute) { - if (isExpressMiddleware) { - return next(); - } else { - return options.onUnhandledRequest(request, response); - } - } - - const missingHeaders = getMissingHeaders(request).join(", "); - - if (missingHeaders) { - response.writeHead(400, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Required headers missing: ${missingHeaders}` - })); - return; - } - - const eventName = request.headers["x-github-event"]; - const signatureSHA256 = request.headers["x-hub-signature-256"]; - const id = request.headers["x-github-delivery"]; - options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s - // See https://github.com/octokit/webhooks.js/issues/185 - - let didTimeout = false; - const timeout = setTimeout(() => { - didTimeout = true; - response.statusCode = 202; - response.end("still processing\n"); - }, 9000).unref(); - - try { - const payload = await getPayload(request); - await webhooks.verifyAndReceive({ - id: id, - name: eventName, - payload: payload, - signature: signatureSHA256 - }); - clearTimeout(timeout); - if (didTimeout) return; - response.end("ok\n"); - } catch (error) { - clearTimeout(timeout); - if (didTimeout) return; - const statusCode = Array.from(error)[0].status; - response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500; - response.end(String(error)); - } -} - -function onUnhandledRequestDefault(request, response) { - response.writeHead(404, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Unknown route: ${request.method} ${request.url}` - })); -} - -function createNodeMiddleware(webhooks, { - path = "/api/github/webhooks", - onUnhandledRequest = onUnhandledRequestDefault, - log = createLogger() -} = {}) { - return middleware.bind(null, webhooks, { - path, - onUnhandledRequest, - log - }); -} - -class Webhooks { - constructor(options) { - if (!options || !options.secret) { - throw new Error("[@octokit/webhooks] options.secret required"); - } - - const state = { - eventHandler: createEventHandler(options), - secret: options.secret, - hooks: {}, - log: createLogger(options.log) - }; - this.sign = sign.bind(null, options.secret); - this.verify = verify.bind(null, options.secret); - this.on = state.eventHandler.on; - this.onAny = state.eventHandler.onAny; - this.onError = state.eventHandler.onError; - this.removeListener = state.eventHandler.removeListener; - this.receive = state.eventHandler.receive; - this.verifyAndReceive = verifyAndReceive.bind(null, state); - } - -} - -exports.Webhooks = Webhooks; -exports.createEventHandler = createEventHandler; -exports.createNodeMiddleware = createNodeMiddleware; -exports.emitterEventNames = emitterEventNames; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 6840: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const indentString = __nccwpck_require__(7290); -const cleanStack = __nccwpck_require__(3151); - -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } - - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - - return new Error(error); - }); - - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - - this.name = 'AggregateError'; - - Object.defineProperty(this, '_errors', {value: errors}); - } - - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -} - -module.exports = AggregateError; - - /***/ }), /***/ 1661: @@ -9882,1643 +6125,6 @@ function removeHook(state, name, method) { } -/***/ }), - -/***/ 994: -/***/ (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; - -}))); - - -/***/ }), - -/***/ 1119: -/***/ ((module) => { - -module.exports = function btoa(str) { - return new Buffer(str).toString('base64') -} - - -/***/ }), - -/***/ 3040: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*jshint node:true */ - -var Buffer = (__nccwpck_require__(4300).Buffer); // browserify -var SlowBuffer = (__nccwpck_require__(4300).SlowBuffer); - -module.exports = bufferEq; - -function bufferEq(a, b) { - - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } - - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } - - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} - -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; - -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; - - -/***/ }), - -/***/ 3151: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const os = __nccwpck_require__(2037); - -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); - -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); - - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } - - const match = pathMatches[1]; - - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } - - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } - - return line; - }) - .join('\n'); -}; - - /***/ }), /***/ 9325: @@ -11547,289 +6153,6 @@ class Deprecation extends Error { exports.Deprecation = Deprecation; -/***/ }), - -/***/ 1069: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(3851).Buffer); - -var getParamBytesForAlg = __nccwpck_require__(2507); - -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } - - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} - -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - - var inputLength = signature.length; - - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } - - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } - - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } - - var rLength = signature[offset++]; - - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } - - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var rOffset = offset; - offset += rLength; - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } - - var sLength = signature[offset++]; - - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } - - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var sOffset = offset; - offset += sLength; - - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } - - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; - - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - - offset = paramBytes; - - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - - dst = dst.toString('base64'); - dst = base64Url(dst); - - return dst; -} - -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } - - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } - - return padding; -} - -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } - - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; - - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - - var shortLength = rsBytes < MAX_OCTET; - - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } - - return dst; -} - -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; - - -/***/ }), - -/***/ 2507: -/***/ ((module) => { - -"use strict"; - - -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} - -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; - -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } - - throw new Error('Unknown algorithm "' + alg + '"'); -} - -module.exports = getParamBytesForAlg; - - -/***/ }), - -/***/ 8257: -/***/ ((module) => { - -/*! fromentries. MIT License. Feross Aboukhadijeh */ -module.exports = function fromEntries (iterable) { - return [...iterable].reduce((obj, [key, val]) => { - obj[key] = val - return obj - }, {}) -} - - -/***/ }), - -/***/ 7290: -/***/ ((module) => { - -"use strict"; - - -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } - - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } - - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } - - if (count === 0) { - return string; - } - - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - - return string.replace(regex, options.indent.repeat(count)); -}; - - /***/ }), /***/ 9877: @@ -11876,4912 +6199,6 @@ function isPlainObject(o) { exports.isPlainObject = isPlainObject; -/***/ }), - -/***/ 7296: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var jws = __nccwpck_require__(1915); - -module.exports = function (jwt, options) { - options = options || {}; - var decoded = jws.decode(jwt, options); - if (!decoded) { return null; } - var payload = decoded.payload; - - //try parse the payload - if(typeof payload === 'string') { - try { - var obj = JSON.parse(payload); - if(obj !== null && typeof obj === 'object') { - payload = obj; - } - } catch (e) { } - } - - //return header if `complete` option is enabled. header includes claims - //such as `kid` and `alg` used to select the key within a JWKS needed to - //verify the signature - if (options.complete === true) { - return { - header: decoded.header, - payload: payload, - signature: decoded.signature - }; - } - return payload; -}; - - -/***/ }), - -/***/ 93: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { - decode: __nccwpck_require__(7296), - verify: __nccwpck_require__(3224), - sign: __nccwpck_require__(6749), - JsonWebTokenError: __nccwpck_require__(2811), - NotBeforeError: __nccwpck_require__(9850), - TokenExpiredError: __nccwpck_require__(3735), -}; - - -/***/ }), - -/***/ 2811: -/***/ ((module) => { - -var JsonWebTokenError = function (message, error) { - Error.call(this, message); - if(Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = 'JsonWebTokenError'; - this.message = message; - if (error) this.inner = error; -}; - -JsonWebTokenError.prototype = Object.create(Error.prototype); -JsonWebTokenError.prototype.constructor = JsonWebTokenError; - -module.exports = JsonWebTokenError; - - -/***/ }), - -/***/ 9850: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var JsonWebTokenError = __nccwpck_require__(2811); - -var NotBeforeError = function (message, date) { - JsonWebTokenError.call(this, message); - this.name = 'NotBeforeError'; - this.date = date; -}; - -NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); - -NotBeforeError.prototype.constructor = NotBeforeError; - -module.exports = NotBeforeError; - -/***/ }), - -/***/ 3735: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var JsonWebTokenError = __nccwpck_require__(2811); - -var TokenExpiredError = function (message, expiredAt) { - JsonWebTokenError.call(this, message); - this.name = 'TokenExpiredError'; - this.expiredAt = expiredAt; -}; - -TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); - -TokenExpiredError.prototype.constructor = TokenExpiredError; - -module.exports = TokenExpiredError; - -/***/ }), - -/***/ 9904: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var semver = __nccwpck_require__(1768); - -module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); - - -/***/ }), - -/***/ 5898: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var ms = __nccwpck_require__(2771); - -module.exports = function (time, iat) { - var timestamp = iat || Math.floor(Date.now() / 1000); - - if (typeof time === 'string') { - var milliseconds = ms(time); - if (typeof milliseconds === 'undefined') { - return; - } - return Math.floor(timestamp + milliseconds / 1000); - } else if (typeof time === 'number') { - return timestamp + time; - } else { - return; - } - -}; - -/***/ }), - -/***/ 1768: -/***/ ((module, exports) => { - -exports = module.exports = SemVer - -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' - -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' - -src[FULL] = '^' + FULLPLAIN + '$' - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' - -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' - -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} - -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } - - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} - -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} - -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} - -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) -} - -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set -} - -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} - -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - var match = version.match(re[COERCE]) - - if (match == null) { - return null - } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} - - -/***/ }), - -/***/ 6749: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var timespan = __nccwpck_require__(5898); -var PS_SUPPORTED = __nccwpck_require__(9904); -var jws = __nccwpck_require__(1915); -var includes = __nccwpck_require__(5925); -var isBoolean = __nccwpck_require__(9140); -var isInteger = __nccwpck_require__(9187); -var isNumber = __nccwpck_require__(8628); -var isPlainObject = __nccwpck_require__(330); -var isString = __nccwpck_require__(4715); -var once = __nccwpck_require__(5839); - -var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] -if (PS_SUPPORTED) { - SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} - -var sign_options_schema = { - expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, - notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, - audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, - algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, - header: { isValid: isPlainObject, message: '"header" must be an object' }, - encoding: { isValid: isString, message: '"encoding" must be a string' }, - issuer: { isValid: isString, message: '"issuer" must be a string' }, - subject: { isValid: isString, message: '"subject" must be a string' }, - jwtid: { isValid: isString, message: '"jwtid" must be a string' }, - noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, - keyid: { isValid: isString, message: '"keyid" must be a string' }, - mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } -}; - -var registered_claims_schema = { - iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, - exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, - nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } -}; - -function validate(schema, allowUnknown, object, parameterName) { - if (!isPlainObject(object)) { - throw new Error('Expected "' + parameterName + '" to be a plain object.'); - } - Object.keys(object) - .forEach(function(key) { - var validator = schema[key]; - if (!validator) { - if (!allowUnknown) { - throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); - } - return; - } - if (!validator.isValid(object[key])) { - throw new Error(validator.message); - } - }); -} - -function validateOptions(options) { - return validate(sign_options_schema, false, options, 'options'); -} - -function validatePayload(payload) { - return validate(registered_claims_schema, true, payload, 'payload'); -} - -var options_to_payload = { - 'audience': 'aud', - 'issuer': 'iss', - 'subject': 'sub', - 'jwtid': 'jti' -}; - -var options_for_objects = [ - 'expiresIn', - 'notBefore', - 'noTimestamp', - 'audience', - 'issuer', - 'subject', - 'jwtid', -]; - -module.exports = function (payload, secretOrPrivateKey, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else { - options = options || {}; - } - - var isObjectPayload = typeof payload === 'object' && - !Buffer.isBuffer(payload); - - var header = Object.assign({ - alg: options.algorithm || 'HS256', - typ: isObjectPayload ? 'JWT' : undefined, - kid: options.keyid - }, options.header); - - function failure(err) { - if (callback) { - return callback(err); - } - throw err; - } - - if (!secretOrPrivateKey && options.algorithm !== 'none') { - return failure(new Error('secretOrPrivateKey must have a value')); - } - - if (typeof payload === 'undefined') { - return failure(new Error('payload is required')); - } else if (isObjectPayload) { - try { - validatePayload(payload); - } - catch (error) { - return failure(error); - } - if (!options.mutatePayload) { - payload = Object.assign({},payload); - } - } else { - var invalid_options = options_for_objects.filter(function (opt) { - return typeof options[opt] !== 'undefined'; - }); - - if (invalid_options.length > 0) { - return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); - } - } - - if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { - return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); - } - - if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { - return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); - } - - try { - validateOptions(options); - } - catch (error) { - return failure(error); - } - - var timestamp = payload.iat || Math.floor(Date.now() / 1000); - - if (options.noTimestamp) { - delete payload.iat; - } else if (isObjectPayload) { - payload.iat = timestamp; - } - - if (typeof options.notBefore !== 'undefined') { - try { - payload.nbf = timespan(options.notBefore, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.nbf === 'undefined') { - return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - } - - if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { - try { - payload.exp = timespan(options.expiresIn, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.exp === 'undefined') { - return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - } - - Object.keys(options_to_payload).forEach(function (key) { - var claim = options_to_payload[key]; - if (typeof options[key] !== 'undefined') { - if (typeof payload[claim] !== 'undefined') { - return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); - } - payload[claim] = options[key]; - } - }); - - var encoding = options.encoding || 'utf8'; - - if (typeof callback === 'function') { - callback = callback && once(callback); - - jws.createSign({ - header: header, - privateKey: secretOrPrivateKey, - payload: payload, - encoding: encoding - }).once('error', callback) - .once('done', function (signature) { - callback(null, signature); - }); - } else { - return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); - } -}; - - -/***/ }), - -/***/ 3224: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var JsonWebTokenError = __nccwpck_require__(2811); -var NotBeforeError = __nccwpck_require__(9850); -var TokenExpiredError = __nccwpck_require__(3735); -var decode = __nccwpck_require__(7296); -var timespan = __nccwpck_require__(5898); -var PS_SUPPORTED = __nccwpck_require__(9904); -var jws = __nccwpck_require__(1915); - -var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; -var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; -var HS_ALGS = ['HS256', 'HS384', 'HS512']; - -if (PS_SUPPORTED) { - PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); - RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} - -module.exports = function (jwtString, secretOrPublicKey, options, callback) { - if ((typeof options === 'function') && !callback) { - callback = options; - options = {}; - } - - if (!options) { - options = {}; - } - - //clone this object since we are going to mutate it. - options = Object.assign({}, options); - - var done; - - if (callback) { - done = callback; - } else { - done = function(err, data) { - if (err) throw err; - return data; - }; - } - - if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { - return done(new JsonWebTokenError('clockTimestamp must be a number')); - } - - if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { - return done(new JsonWebTokenError('nonce must be a non-empty string')); - } - - var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); - - if (!jwtString){ - return done(new JsonWebTokenError('jwt must be provided')); - } - - if (typeof jwtString !== 'string') { - return done(new JsonWebTokenError('jwt must be a string')); - } - - var parts = jwtString.split('.'); - - if (parts.length !== 3){ - return done(new JsonWebTokenError('jwt malformed')); - } - - var decodedToken; - - try { - decodedToken = decode(jwtString, { complete: true }); - } catch(err) { - return done(err); - } - - if (!decodedToken) { - return done(new JsonWebTokenError('invalid token')); - } - - var header = decodedToken.header; - var getSecret; - - if(typeof secretOrPublicKey === 'function') { - if(!callback) { - return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); - } - - getSecret = secretOrPublicKey; - } - else { - getSecret = function(header, secretCallback) { - return secretCallback(null, secretOrPublicKey); - }; - } - - return getSecret(header, function(err, secretOrPublicKey) { - if(err) { - return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); - } - - var hasSignature = parts[2].trim() !== ''; - - if (!hasSignature && secretOrPublicKey){ - return done(new JsonWebTokenError('jwt signature is required')); - } - - if (hasSignature && !secretOrPublicKey) { - return done(new JsonWebTokenError('secret or public key must be provided')); - } - - if (!hasSignature && !options.algorithms) { - options.algorithms = ['none']; - } - - if (!options.algorithms) { - options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || - ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : - ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; - - } - - if (!~options.algorithms.indexOf(decodedToken.header.alg)) { - return done(new JsonWebTokenError('invalid algorithm')); - } - - var valid; - - try { - valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); - } catch (e) { - return done(e); - } - - if (!valid) { - return done(new JsonWebTokenError('invalid signature')); - } - - var payload = decodedToken.payload; - - if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { - if (typeof payload.nbf !== 'number') { - return done(new JsonWebTokenError('invalid nbf value')); - } - if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { - return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); - } - } - - if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { - if (typeof payload.exp !== 'number') { - return done(new JsonWebTokenError('invalid exp value')); - } - if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); - } - } - - if (options.audience) { - var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; - var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; - - var match = target.some(function (targetAudience) { - return audiences.some(function (audience) { - return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; - }); - }); - - if (!match) { - return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); - } - } - - if (options.issuer) { - var invalid_issuer = - (typeof options.issuer === 'string' && payload.iss !== options.issuer) || - (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); - - if (invalid_issuer) { - return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); - } - } - - if (options.subject) { - if (payload.sub !== options.subject) { - return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); - } - } - - if (options.jwtid) { - if (payload.jti !== options.jwtid) { - return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); - } - } - - if (options.nonce) { - if (payload.nonce !== options.nonce) { - return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); - } - } - - if (options.maxAge) { - if (typeof payload.iat !== 'number') { - return done(new JsonWebTokenError('iat required when maxAge is specified')); - } - - var maxAgeTimestamp = timespan(options.maxAge, payload.iat); - if (typeof maxAgeTimestamp === 'undefined') { - return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); - } - } - - if (options.complete === true) { - var signature = decodedToken.signature; - - return done(null, { - header: header, - payload: payload, - signature: signature - }); - } - - return done(null, payload); - }); -}; - - -/***/ }), - -/***/ 1304: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var bufferEqual = __nccwpck_require__(3040); -var Buffer = (__nccwpck_require__(3851).Buffer); -var crypto = __nccwpck_require__(6113); -var formatEcdsa = __nccwpck_require__(1069); -var util = __nccwpck_require__(3837); - -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; - -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} - -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; - -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - - if (typeof key === 'object') { - return; - } - - throw typeError(MSG_INVALID_SIGNER_KEY); -}; - -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return key; - } - - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } - - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); - } - - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } - - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); - } -} - -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function toBase64(base64url) { - base64url = base64url.toString(); - - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } - - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} - -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} - -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} - -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} - -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); - } -} - -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } -} - -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} - -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} - -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); - } -} - -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); - } -} - -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} - -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; -} - -function createNoneSigner() { - return function sign() { - return ''; - } -} - -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } -} - -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; - - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; - - -/***/ }), - -/***/ 1915: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -/*global exports*/ -var SignStream = __nccwpck_require__(7859); -var VerifyStream = __nccwpck_require__(9077); - -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; - -exports.ALGORITHMS = ALGORITHMS; -exports.sign = SignStream.sign; -exports.verify = VerifyStream.verify; -exports.decode = VerifyStream.decode; -exports.isValid = VerifyStream.isValid; -exports.createSign = function createSign(opts) { - return new SignStream(opts); -}; -exports.createVerify = function createVerify(opts) { - return new VerifyStream(opts); -}; - - -/***/ }), - -/***/ 9878: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module, process*/ -var Buffer = (__nccwpck_require__(3851).Buffer); -var Stream = __nccwpck_require__(2781); -var util = __nccwpck_require__(3837); - -function DataStream(data) { - this.buffer = null; - this.writable = true; - this.readable = true; - - // No input - if (!data) { - this.buffer = Buffer.alloc(0); - return this; - } - - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; - } - - // Buffer or String - // or Object (assumedly a passworded key) - if (data.length || typeof data === 'object') { - this.buffer = data; - this.writable = false; - process.nextTick(function () { - this.emit('end', data); - this.readable = false; - this.emit('close'); - }.bind(this)); - return this; - } - - throw new TypeError('Unexpected data type ('+ typeof data + ')'); -} -util.inherits(DataStream, Stream); - -DataStream.prototype.write = function write(data) { - this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); - this.emit('data', data); -}; - -DataStream.prototype.end = function end(data) { - if (data) - this.write(data); - this.emit('end', data); - this.emit('close'); - this.writable = false; - this.readable = false; -}; - -module.exports = DataStream; - - -/***/ }), - -/***/ 7859: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(3851).Buffer); -var DataStream = __nccwpck_require__(9878); -var jwa = __nccwpck_require__(1304); -var Stream = __nccwpck_require__(2781); -var toString = __nccwpck_require__(21); -var util = __nccwpck_require__(3837); - -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function jwsSecuredInput(header, payload, encoding) { - encoding = encoding || 'utf8'; - var encodedHeader = base64url(toString(header), 'binary'); - var encodedPayload = base64url(toString(payload), encoding); - return util.format('%s.%s', encodedHeader, encodedPayload); -} - -function jwsSign(opts) { - var header = opts.header; - var payload = opts.payload; - var secretOrKey = opts.secret || opts.privateKey; - var encoding = opts.encoding; - var algo = jwa(header.alg); - var securedInput = jwsSecuredInput(header, payload, encoding); - var signature = algo.sign(securedInput, secretOrKey); - return util.format('%s.%s', securedInput, signature); -} - -function SignStream(opts) { - var secret = opts.secret||opts.privateKey||opts.key; - var secretStream = new DataStream(secret); - this.readable = true; - this.header = opts.header; - this.encoding = opts.encoding; - this.secret = this.privateKey = this.key = secretStream; - this.payload = new DataStream(opts.payload); - this.secret.once('close', function () { - if (!this.payload.writable && this.readable) - this.sign(); - }.bind(this)); - - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); -} -util.inherits(SignStream, Stream); - -SignStream.prototype.sign = function sign() { - try { - var signature = jwsSign({ - header: this.header, - payload: this.payload.buffer, - secret: this.secret.buffer, - encoding: this.encoding - }); - this.emit('done', signature); - this.emit('data', signature); - this.emit('end'); - this.readable = false; - return signature; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; - -SignStream.sign = jwsSign; - -module.exports = SignStream; - - -/***/ }), - -/***/ 21: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(4300).Buffer); - -module.exports = function toString(obj) { - if (typeof obj === 'string') - return obj; - if (typeof obj === 'number' || Buffer.isBuffer(obj)) - return obj.toString(); - return JSON.stringify(obj); -}; - - -/***/ }), - -/***/ 9077: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*global module*/ -var Buffer = (__nccwpck_require__(3851).Buffer); -var DataStream = __nccwpck_require__(9878); -var jwa = __nccwpck_require__(1304); -var Stream = __nccwpck_require__(2781); -var toString = __nccwpck_require__(21); -var util = __nccwpck_require__(3837); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} - -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} - -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} - -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} - -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} - -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} - -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} - -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); -} - -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); - - if (!isValidJws(jwsSig)) - return null; - - var header = headerFromJWS(jwsSig); - - if (!header) - return null; - - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); - - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} - -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); - - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; - -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; - -module.exports = VerifyStream; - - -/***/ }), - -/***/ 5925: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - stringTag = '[object String]', - symbolTag = '[object Symbol]'; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; - -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); - } - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; -} - -/** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ -function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); -} - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} - -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; -} - -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} - -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values(object) { - return object ? baseValues(object, keys(object)) : []; -} - -module.exports = includes; - - -/***/ }), - -/***/ 9140: -/***/ ((module) => { - -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ - -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]'; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && objectToString.call(value) == boolTag); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -module.exports = isBoolean; - - -/***/ }), - -/***/ 9187: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; - -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; - -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ -function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} - -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; -} - -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} - -module.exports = isInteger; - - -/***/ }), - -/***/ 8628: -/***/ ((module) => { - -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ - -/** `Object#toString` result references. */ -var numberTag = '[object Number]'; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified - * as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && objectToString.call(value) == numberTag); -} - -module.exports = isNumber; - - -/***/ }), - -/***/ 330: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; - -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} - -module.exports = isPlainObject; - - -/***/ }), - -/***/ 4715: -/***/ ((module) => { - -/** - * lodash 4.0.1 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ - -/** `Object#toString` result references. */ -var stringTag = '[object String]'; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @type Function - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); -} - -module.exports = isString; - - -/***/ }), - -/***/ 5839: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; - -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; - -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ -function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; -} - -/** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ -function once(func) { - return before(2, func); -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; -} - -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; -} - -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); -} - -module.exports = once; - - -/***/ }), - -/***/ 1493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// A linked list to keep track of recently-used-ness -const Yallist = __nccwpck_require__(4487) - -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') - -const naiveLength = () => 1 - -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } - - if (!options) - options = {} - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity - - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA - trim(this) - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) - } - trim(this) - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } - } - - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } - - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } - - const node = this[CACHE].get(key) - const item = node.value - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } - - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } - - const hit = new Entry(key, value, len, now, maxAge) - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) - - return false - } - - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } - - get (key) { - return get(this, key, true) - } - - peek (key) { - return get(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null - - del(this, node) - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)) - } - - load (arr) { - // reset the cache - this.reset() - - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) - } -} - -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } - } - return hit.value - } -} - -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} - -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } - } -} - -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) - - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} - -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 - } -} - -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined - } - if (hit) - fn.call(thisp, hit.value, hit.key, self) -} - -module.exports = LRUCache - - -/***/ }), - -/***/ 2771: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - /***/ }), /***/ 6399: @@ -18487,75 +7904,6 @@ exports.Response = Response; exports.FetchError = FetchError; -/***/ }), - -/***/ 3979: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ value: true }); - -var core = __nccwpck_require__(8299); -var pluginPaginateRest = __nccwpck_require__(6045); -var pluginRestEndpointMethods = __nccwpck_require__(6943); -var pluginRetry = __nccwpck_require__(4064); -var app = __nccwpck_require__(5150); -var oauthApp = __nccwpck_require__(2804); - -const VERSION = "1.7.1"; - -const Octokit = core.Octokit.plugin(pluginRestEndpointMethods.restEndpointMethods, pluginPaginateRest.paginateRest, pluginRetry.retry // throttling -).defaults({ - userAgent: `octokit-rest.js/${VERSION}`, - throttle: { - onRateLimit, - onAbuseLimit - } -}); // istanbul ignore next no need to test internals of the throttle plugin - -function onRateLimit(retryAfter, options, octokit) { - octokit.log.warn(`Request quota exhausted for request ${options.method} ${options.url}`); - - if (options.request.retryCount === 0) { - // only retries once - octokit.log.info(`Retrying after ${retryAfter} seconds!`); - return true; - } -} // istanbul ignore next no need to test internals of the throttle plugin - - -function onAbuseLimit(retryAfter, options, octokit) { - octokit.log.warn(`Abuse detected for request ${options.method} ${options.url}`); - - if (options.request.retryCount === 0) { - // only retries once - octokit.log.info(`Retrying after ${retryAfter} seconds!`); - return true; - } -} - -const App = app.App.defaults({ - Octokit -}); -const OAuthApp = oauthApp.OAuthApp.defaults({ - Octokit -}); - -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return app.createNodeMiddleware; - } -}); -__webpack_unused_export__ = App; -__webpack_unused_export__ = OAuthApp; -exports.vd = Octokit; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 6770: @@ -18605,78 +7953,6 @@ function onceStrict (fn) { } -/***/ }), - -/***/ 3851: -/***/ ((module, exports, __nccwpck_require__) => { - -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(4300) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - - /***/ }), /***/ 280: @@ -20761,61 +10037,6 @@ if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { exports.debug = debug; // for test -/***/ }), - -/***/ 6988: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var jsonwebtoken = _interopDefault(__nccwpck_require__(93)); - -async function getToken({ - privateKey, - payload -}) { - return jsonwebtoken.sign(payload, privateKey, { - algorithm: "RS256" - }); -} - -async function githubAppJwt({ - id, - privateKey, - now = Math.floor(Date.now() / 1000) -}) { - // When creating a JSON Web Token, it sets the "issued at time" (iat) to 30s - // in the past as we have seen people running situations where the GitHub API - // claimed the iat would be in future. It turned out the clocks on the - // different machine were not in sync. - const nowWithSafetyMargin = now - 30; - const expiration = nowWithSafetyMargin + 60 * 10; // JWT expiration time (10 minute maximum) - - const payload = { - iat: nowWithSafetyMargin, - exp: expiration, - iss: id - }; - const token = await getToken({ - privateKey, - payload - }); - return { - appId: id, - expiration, - token - }; -} - -exports.githubAppJwt = githubAppJwt; -//# sourceMappingURL=index.js.map - - /***/ }), /***/ 958: @@ -22927,456 +12148,6 @@ function wrappy (fn, cb) { } -/***/ }), - -/***/ 8237: -/***/ ((module) => { - -"use strict"; - -module.exports = function (Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value - } - } -} - - -/***/ }), - -/***/ 4487: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Yallist - -Yallist.Node = Node -Yallist.create = Yallist - -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } - - self.tail = null - self.head = null - self.length = 0 - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) - } - } - - return self -} - -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next - var prev = node.prev - - if (next) { - next.prev = prev - } - - if (prev) { - prev.next = next - } - - if (node === this.head) { - this.head = next - } - if (node === this.tail) { - this.tail = prev - } - - node.list.length-- - node.next = null - node.prev = null - node.list = null - - return next -} - -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node - } - - this.head = node - if (!this.tail) { - this.tail = node - } - this.length++ -} - -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node) - } - - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node - } - - this.tail = node - if (!this.head) { - this.head = node - } - this.length++ -} - -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) - } - return this.length -} - -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null - } - this.length-- - return res -} - -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null - } else { - this.tail = null - } - this.length-- - return res -} - -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next - } -} - -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev - } -} - -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev - } - if (i === n && walker !== null) { - return walker.value - } -} - -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next - } - return res -} - -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev - } - return res -} - -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next - } - - return acc -} - -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev - } - - return acc -} - -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next - } - return arr -} - -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev - } - return arr -} - -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) - } - return ret -} - -Yallist.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1 - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next - } - - var ret = [] - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value) - walker = this.removeNode(walker) - } - if (walker === null) { - walker = this.tail - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]) - } - return ret; -} - -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p - } - this.head = tail - this.tail = head - return this -} - -function insert (self, node, value) { - var inserted = node === self.head ? - new Node(value, null, node, self) : - new Node(value, node, node.next, self) - - if (inserted.next === null) { - self.tail = inserted - } - if (inserted.prev === null) { - self.head = inserted - } - - self.length++ - - return inserted -} - -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail - } - self.length++ -} - -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ -} - -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } - - this.list = list - this.value = value - - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null - } - - if (next) { - next.prev = this - this.next = next - } else { - this.next = null - } -} - -try { - // add if support for Symbol.iterator is present - __nccwpck_require__(8237)(Yallist) -} catch (er) {} - - /***/ }), /***/ 7336: @@ -23395,14 +12166,6 @@ module.exports = require("assert"); /***/ }), -/***/ 4300: -/***/ ((module) => { - -"use strict"; -module.exports = require("buffer"); - -/***/ }), - /***/ 2081: /***/ ((module) => { @@ -23668,9 +12431,51 @@ class StackerCLI { constructor(executable) { this.executable = executable; } - build(stackerfile, layerType, substitutes) { + convertDockerfile(dockerfile) { return __awaiter(this, void 0, void 0, function* () { - const args = ["--debug", "build"]; + const args = ["--debug"]; + const stackerfile = "stacker.yaml"; + const subfile = "stacker-subs.yaml"; + args.push("convert"); + args.push("--docker-file"); + args.push(dockerfile); + args.push("--output-file"); + args.push(stackerfile); + args.push("--substitute-file"); + args.push(subfile); + const res = this.execute(args).then((res) => { + if (res.exitCode == 0) { + core.info("printing resulting stacker.yaml after converting dockerfile"); + exec.exec('/bin/bash -c "cat stacker.yaml"', []); + core.info("printing resulting substitutes file after converting dockerfile"); + exec.exec('/bin/bash -c "cat stacker-subs.yaml"', []); + } + return res; + }); + const cres = { + stackerfile: stackerfile, + subfile: subfile, + }; + return [res, cres]; + }); + } + build(stackerfile, cachedir, stackerdir, stackerfilePattern, layerType, substitutes, subfile) { + return __awaiter(this, void 0, void 0, function* () { + const args = ["--debug"]; + args.push("--stacker-dir"); + args.push(cachedir); + if (stackerdir) { + args.push("recursive-build"); + args.push("--search-dir"); + args.push(stackerdir); + args.push("--stacker-file-pattern"); + args.push(stackerfilePattern); + } + else { + args.push("build"); + args.push("-f"); + args.push(stackerfile); + } layerType.forEach((layerType) => { args.push("--layer-type"); args.push(layerType); @@ -23679,8 +12484,10 @@ class StackerCLI { args.push("--substitute"); args.push(substitute); }); - args.push("-f"); - args.push(stackerfile); + if (subfile) { + args.push("--substitute-file"); + args.push(subfile); + } const res = this.execute(args).then((res) => { if (res.exitCode == 0) { core.info("printing oci layout index.json"); @@ -23691,9 +12498,12 @@ class StackerCLI { return res; }); } - publish(stackerfile, layerType, substitutes, url, tags, username, password, skipTLS) { + publish(stackerfile, cachedir, stackerdir, stackerfilePattern, layerType, substitutes, subfile, url, tags, username, password, skipTLS) { return __awaiter(this, void 0, void 0, function* () { - const args = ["--debug", "publish"]; + const args = ["--debug"]; + args.push("--stacker-dir"); + args.push(cachedir); + args.push("publish"); layerType.forEach((layerType) => { args.push("--layer-type"); args.push(layerType); @@ -23702,6 +12512,10 @@ class StackerCLI { args.push("--substitute"); args.push(substitute); }); + if (subfile) { + args.push("--substitute-file"); + args.push(subfile); + } args.push("--url"); args.push(url); tags.forEach((tag) => { @@ -23719,8 +12533,16 @@ class StackerCLI { if (skipTLS) { args.push("--skip-tls"); } - args.push("-f"); - args.push(stackerfile); + if (stackerdir) { + args.push("--search-dir"); + args.push(stackerdir); + args.push("--stacker-file-pattern"); + args.push(stackerfilePattern); + } + else { + args.push("-f"); + args.push(stackerfile); + } return this.execute(args); }); } @@ -23771,8 +12593,8 @@ class StackerCLI { } } -// EXTERNAL MODULE: ./node_modules/octokit/dist-node/index.js -var dist_node = __nccwpck_require__(3979); +// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js +var github = __nccwpck_require__(1528); ;// CONCATENATED MODULE: ./src/installer.ts var installer_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -23793,16 +12615,13 @@ function resolveReleaseData() { return installer_awaiter(this, void 0, void 0, function* () { let version = core.getInput('version'); let token = core.getInput('token'); - const octokit = new dist_node/* Octokit */.vd(); + const octokit = github.getOctokit(token); let releaseData = {}; if ((!version) || (version.toLowerCase() === 'latest')) { core.info("Get release info for latest version"); releaseData = yield octokit.rest.repos.getLatestRelease({ "owner": stackerOrg, "repo": stackerRepo, - "header": { - authorization: `token ${token}`, - } }); } else { @@ -23902,20 +12721,33 @@ function run() { else { core.info(`${stackerBin} version ${version} already installed`); } - const stackerPath = yield io.which("stacker", true); + const stackerPath = yield io.which(stackerBin, true); const cli = new StackerCLI(stackerPath); yield cli.execute(["--version"], { group: true }); - const stackerfile = core.getInput("file"); + const cachedir = core.getInput("cache-dir"); + var stackerfile = core.getInput("file"); + const dockerfile = core.getInput('dockerfile'); + const stackerdir = core.getInput("dir"); + const stackerfilePattern = core.getInput("file-pattern"); const substitutes = getInputList("build-args"); + var subfile = core.getInput("build-args-file"); const layerTypes = getSpaceSeparatedInput("layer-type"); - yield cli.build(stackerfile, layerTypes, substitutes); - const tags = getSpaceSeparatedInput("tags"); + core.info(`dockerfile val: ${dockerfile}`); + if (dockerfile) { + let [cmdRes, convertRes] = yield cli.convertDockerfile(dockerfile); + if (convertRes && (yield cmdRes).exitCode == 0) { + stackerfile = convertRes.stackerfile; + subfile = convertRes.subfile; + } + } + yield cli.build(stackerfile, cachedir, stackerdir, stackerfilePattern, layerTypes, substitutes, subfile); const registryURL = core.getInput("url"); - const username = core.getInput("username"); - const password = core.getInput("password"); - const skipTLS = core.getInput("skip-tls") === "true"; if (registryURL) { - yield cli.publish(stackerfile, layerTypes, substitutes, registryURL, tags, username, password, skipTLS); + const tags = getSpaceSeparatedInput("tags"); + const username = core.getInput("username"); + const password = core.getInput("password"); + const skipTLS = core.getInput("skip-tls") === "true"; + yield cli.publish(stackerfile, cachedir, stackerdir, stackerfilePattern, layerTypes, substitutes, subfile, registryURL, tags, username, password, skipTLS); } }); } diff --git a/dist/licenses.txt b/dist/licenses.txt index 74ef7b6..4034c43 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -22,6 +22,18 @@ The above copyright notice and this permission notice shall be included in all c 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. +@actions/github +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + @actions/http-client MIT Actions Http Client for Node.js @@ -59,6 +71,516 @@ The above copyright notice and this permission notice shall be included in all c 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. +@actions/tool-cache +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + +@octokit/auth-token +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/core +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/endpoint +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/graphql +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/plugin-paginate-rest +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/plugin-rest-endpoint-methods +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/request +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/request-error +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@vercel/ncc +MIT +Copyright 2018 ZEIT, Inc. + +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. + +before-after-hook +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Gregor Martynus and other contributors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +deprecation +ISC +The ISC License + +Copyright (c) Gregor Martynus and contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +is-plain-object +MIT +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +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. + + +node-fetch +MIT +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +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. + + + +once +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +semver +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +tr46 +MIT + tunnel MIT The MIT License (MIT) @@ -82,3 +604,99 @@ 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. + + +universal-user-agent +ISC +# [ISC License](https://spdx.org/licenses/ISC) + +Copyright (c) 2018, Gregor Martynus (https://github.com/gr2m) + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +uuid +MIT +The MIT License (MIT) + +Copyright (c) 2010-2016 Robert Kieffer and other 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. + + +webidl-conversions +BSD-2-Clause +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +whatwg-url +MIT +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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. + + +wrappy +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/src/index.ts b/src/index.ts index 3285ef9..23d7cff 100644 --- a/src/index.ts +++ b/src/index.ts @@ -31,33 +31,58 @@ export async function run(): Promise { } // get stacker cli - const stackerPath = await io.which("stacker", true); + const stackerPath = await io.which(stackerBin, true); const cli: StackerCLI = new StackerCLI(stackerPath); // print stacker version await cli.execute(["--version"], { group: true }); + // get stacker cache dir + const cachedir = core.getInput("cache-dir"); + // get stacker file path from input - const stackerfile = core.getInput("file"); + var stackerfile = core.getInput("file"); + + // get dockerfile path from input if any + const dockerfile = core.getInput('dockerfile'); + + // get stacker dir to recursive search for stacker files + const stackerdir = core.getInput("dir"); + + // get stacker file pattern + const stackerfilePattern = core.getInput("file-pattern"); // get build-args from input const substitutes = utils.getInputList("build-args"); + // get build-args file from input + var subfile = core.getInput("build-args-file"); + // get layer-type from input const layerTypes = utils.getSpaceSeparatedInput("layer-type"); - await cli.build(stackerfile, layerTypes, substitutes); + core.info(`dockerfile val: ${dockerfile}`); + if (dockerfile) { + let [cmdRes, convertRes] = await cli.convertDockerfile(dockerfile); - // get tags from input - const tags = utils.getSpaceSeparatedInput("tags"); + if (convertRes && (await cmdRes).exitCode == 0) { + // update stackerfile, subfile values + stackerfile = convertRes.stackerfile; + subfile = convertRes.subfile; + } + } + + await cli.build(stackerfile, cachedir, stackerdir, stackerfilePattern, layerTypes, substitutes, subfile); const registryURL = core.getInput("url"); - const username = core.getInput("username"); - const password = core.getInput("password"); - const skipTLS = core.getInput("skip-tls") === "true"; - if (registryURL) { - await cli.publish(stackerfile, layerTypes, substitutes, + // get tags from input + const tags = utils.getSpaceSeparatedInput("tags"); + const username = core.getInput("username"); + const password = core.getInput("password"); + const skipTLS = core.getInput("skip-tls") === "true"; + + await cli.publish(stackerfile, cachedir, stackerdir, stackerfilePattern, layerTypes, substitutes, subfile, registryURL, tags, username, password, skipTLS); } } diff --git a/src/stacker.ts b/src/stacker.ts index dc33a97..ae00d06 100644 --- a/src/stacker.ts +++ b/src/stacker.ts @@ -12,6 +12,10 @@ export type CommandResult = { error: string }; +export type ConvertResult = { + stackerfile: string + subfile: string +} export class StackerCLI { private readonly executable: string; @@ -20,8 +24,60 @@ export class StackerCLI { this.executable = executable; } - async build(stackerfile: string, layerType: string[], substitutes: string[]): Promise { - const args: string[] = ["--debug", "build"]; + async convertDockerfile(dockerfile: string): Promise<[Promise, ConvertResult]> { + const args: string[] = ["--debug"]; + + const stackerfile = "stacker.yaml" + const subfile = "stacker-subs.yaml" + + args.push("convert"); + args.push("--docker-file"); + args.push(dockerfile); + + args.push("--output-file"); + args.push(stackerfile); + + args.push("--substitute-file"); + args.push(subfile); + + const res = this.execute(args).then((res) => { + if (res.exitCode == 0) { + core.info("printing resulting stacker.yaml after converting dockerfile"); + exec.exec('/bin/bash -c "cat stacker.yaml"', []); + + core.info("printing resulting substitutes file after converting dockerfile"); + exec.exec('/bin/bash -c "cat stacker-subs.yaml"', []); + } + + return res; + }) + + const cres : ConvertResult = { + stackerfile: stackerfile, + subfile: subfile, + } + + return [res, cres]; + } + + async build(stackerfile: string, cachedir: string, stackerdir: string, stackerfilePattern: string, + layerType: string[], substitutes: string[], subfile: string): Promise { + const args: string[] = ["--debug"]; + + args.push("--stacker-dir"); + args.push(cachedir); + + if (stackerdir) { + args.push("recursive-build"); + args.push("--search-dir"); + args.push(stackerdir); + args.push("--stacker-file-pattern"); + args.push(stackerfilePattern); + } else { + args.push("build") + args.push("-f"); + args.push(stackerfile); + } layerType.forEach((layerType) => { args.push("--layer-type"); @@ -33,8 +89,10 @@ export class StackerCLI { args.push(substitute); }) - args.push("-f"); - args.push(stackerfile); + if (subfile) { + args.push("--substitute-file"); + args.push(subfile); + } const res = this.execute(args).then((res) => { if (res.exitCode == 0) { @@ -48,9 +106,14 @@ export class StackerCLI { return res; } - async publish(stackerfile: string, layerType: string[], substitutes: string[], - url: string, tags: string[], username: string, password: string, skipTLS: boolean): Promise { - const args: string[] = ["--debug", "publish"]; + async publish(stackerfile: string, cachedir: string, stackerdir: string, stackerfilePattern: string, layerType: string[], substitutes: string[], + subfile: string, url: string, tags: string[], username: string, password: string, skipTLS: boolean): Promise { + const args: string[] = ["--debug"]; + + args.push("--stacker-dir"); + args.push(cachedir); + + args.push("publish"); layerType.forEach((layerType) => { args.push("--layer-type"); @@ -62,6 +125,11 @@ export class StackerCLI { args.push(substitute); }); + if (subfile) { + args.push("--substitute-file"); + args.push(subfile); + } + args.push("--url"); args.push(url); @@ -84,8 +152,15 @@ export class StackerCLI { args.push("--skip-tls"); } - args.push("-f"); - args.push(stackerfile); + if (stackerdir) { + args.push("--search-dir"); + args.push(stackerdir); + args.push("--stacker-file-pattern"); + args.push(stackerfilePattern); + } else { + args.push("-f"); + args.push(stackerfile); + } return this.execute(args); } diff --git a/test/Dockerfile b/test/Dockerfile new file mode 100644 index 0000000..40f2182 --- /dev/null +++ b/test/Dockerfile @@ -0,0 +1,25 @@ +FROM alpine:3.16 + +VOLUME /tmp + +ARG VERSION=1.0.0 +LABEL AUTHOR="unknown" + +ENV ENV_VERSION1 \$VERSION +ENV ENV_VERSION2=\$VERSION +ENV ENV_VERSION3=\$\{VERSION\} +ENV TEST_PATH="/usr/share/test/bin:$PATH" \ + TEST_PATHS_CONFIG="/etc/test/test.ini" \ + TEST_PATHS_DATA="/var/lib/test" \ + TEST_PATHS_HOME="/usr/share/test" \ + TEST_PATHS_LOGS="/var/log/test" \ + TEST_PATHS_PLUGINS="/var/lib/test/plugins" \ + TEST_PATHS_PROVISIONING="/etc/test/provisioning" +ENV COMMIT_SHA=${COMMIT_SHA} + +RUN echo \$VERSION +RUN echo \$\{VERSION\} + +RUN apk add --no-cache lua5.3 lua-filesystem lua-lyaml lua-http + +ENTRYPOINT [ "/usr/local/bin/fetch-latest-releases.lua" ] diff --git a/test/builds/first/importfile1 b/test/builds/first/importfile1 new file mode 100644 index 0000000..7776427 --- /dev/null +++ b/test/builds/first/importfile1 @@ -0,0 +1 @@ +import1 diff --git a/test/builds/first/stacker.yaml b/test/builds/first/stacker.yaml new file mode 100644 index 0000000..88fcfa1 --- /dev/null +++ b/test/builds/first/stacker.yaml @@ -0,0 +1,14 @@ +layer1_1: + from: + type: docker + url: docker://centos:latest + import: + - import1 + run: | + cp /stacker/imports/import1 /root/import1 +layer1_2: + from: + type: docker + url: docker://centos:latest + run: + touch /root/import0 diff --git a/test/builds/second/importfile2 b/test/builds/second/importfile2 new file mode 100644 index 0000000..847d6c3 --- /dev/null +++ b/test/builds/second/importfile2 @@ -0,0 +1 @@ +import2 diff --git a/test/builds/second/stacker.yaml b/test/builds/second/stacker.yaml new file mode 100644 index 0000000..bac37cb --- /dev/null +++ b/test/builds/second/stacker.yaml @@ -0,0 +1,12 @@ +config: + prerequisites: + - ../sub1/stacker.yaml +layer2: + from: + type: built + tag: layer1_1 + import: + - import2 + run: | + cp /stacker/imports/import2 /root/import2 + cp /root/import1 /root/import1_copied diff --git a/test/builds/third/stacker.yaml b/test/builds/third/stacker.yaml new file mode 100644 index 0000000..89f9a81 --- /dev/null +++ b/test/builds/third/stacker.yaml @@ -0,0 +1,16 @@ +config: + prerequisites: + - ../sub1/stacker.yaml + - ../sub2/stacker.yaml +layer3_1: + from: + type: built + tag: layer2 + run: | + cp /root/import2 /root/import2_copied +layer3_2: + from: + type: built + tag: layer1_2 + run: | + cp /root/import0 /root/import0_copied