Bump actions/github to 2.2.0 to support GHES (#72)

* Bumping actions/github to 2.2.0

* Husky commit correct node modules
This commit is contained in:
PJ Quirk
2020-05-15 09:52:23 -04:00
committed by GitHub
parent 04aa5dbc72
commit c5c9bd0f54
7791 changed files with 2209804 additions and 49075 deletions

22
node_modules/@octokit/rest/README.md generated vendored
View File

@@ -3,11 +3,11 @@
> GitHub REST API client for JavaScript
[![@latest](https://img.shields.io/npm/v/@octokit/rest.svg)](https://www.npmjs.com/package/@octokit/rest)
[![Build Status](https://travis-ci.org/octokit/rest.js.svg?branch=master)](https://travis-ci.org/octokit/rest.js)
[![Coverage Status](https://coveralls.io/repos/github/octokit/rest.js/badge.svg)](https://coveralls.io/github/octokit/rest.js)
![Build Status](https://github.com/octokit/rest.js/workflows/Test/badge.svg)
[![Greenkeeper](https://badges.greenkeeper.io/octokit/rest.js.svg)](https://greenkeeper.io/)
## Installation
```shell
npm install @octokit/rest
```
@@ -15,16 +15,18 @@ npm install @octokit/rest
## Usage
```js
const Octokit = require('@octokit/rest')
const octokit = new Octokit()
const { Octokit } = require("@octokit/rest");
const octokit = new Octokit();
// Compare: https://developer.github.com/v3/repos/#list-organization-repositories
octokit.repos.listForOrg({
org: 'octokit',
type: 'public'
}).then(({ data }) => {
// handle data
})
octokit.repos
.listForOrg({
org: "octokit",
type: "public"
})
.then(({ data }) => {
// handle data
});
```
See https://octokit.github.io/rest.js/ for full documentation.

60922
node_modules/@octokit/rest/index.d.ts generated vendored

File diff suppressed because it is too large Load Diff

51
node_modules/@octokit/rest/index.js generated vendored
View File

@@ -1,16 +1,43 @@
const Octokit = require('./lib/core')
const { requestLog } = require("@octokit/plugin-request-log");
const {
restEndpointMethods
} = require("@octokit/plugin-rest-endpoint-methods");
const Core = require("./lib/core");
const CORE_PLUGINS = [
require('./plugins/log'),
require('./plugins/authentication-deprecated'), // deprecated: remove in v17
require('./plugins/authentication'),
require('./plugins/pagination'),
require('./plugins/normalize-git-reference-responses'),
require('./plugins/register-endpoints'),
require('./plugins/rest-api-endpoints'),
require('./plugins/validate'),
require("./plugins/authentication"),
require("./plugins/authentication-deprecated"), // deprecated: remove in v17
requestLog,
require("./plugins/pagination"),
restEndpointMethods,
require("./plugins/validate"),
require('octokit-pagination-methods') // deprecated: remove in v17
]
require("octokit-pagination-methods") // deprecated: remove in v17
];
module.exports = Octokit.plugin(CORE_PLUGINS)
const OctokitRest = Core.plugin(CORE_PLUGINS);
function DeprecatedOctokit(options) {
const warn =
options && options.log && options.log.warn
? options.log.warn
: console.warn;
warn(
'[@octokit/rest] `const Octokit = require("@octokit/rest")` is deprecated. Use `const { Octokit } = require("@octokit/rest")` instead'
);
return new OctokitRest(options);
}
const Octokit = Object.assign(DeprecatedOctokit, {
Octokit: OctokitRest
});
Object.keys(OctokitRest).forEach(key => {
/* istanbul ignore else */
if (OctokitRest.hasOwnProperty(key)) {
Octokit[key] = OctokitRest[key];
}
});
module.exports = Octokit;

View File

@@ -1,26 +1,29 @@
module.exports = Octokit
module.exports = Octokit;
const { request } = require('@octokit/request')
const Hook = require('before-after-hook')
const { request } = require("@octokit/request");
const Hook = require("before-after-hook");
const parseClientOptions = require('./parse-client-options')
const parseClientOptions = require("./parse-client-options");
function Octokit (plugins, options) {
options = options || {}
const hook = new Hook.Collection()
const log = Object.assign({
debug: () => {},
info: () => {},
warn: console.warn,
error: console.error
}, options && options.log)
function Octokit(plugins, options) {
options = options || {};
const hook = new Hook.Collection();
const log = Object.assign(
{
debug: () => {},
info: () => {},
warn: console.warn,
error: console.error
},
options && options.log
);
const api = {
hook,
log,
request: request.defaults(parseClientOptions(options, log, hook))
}
};
plugins.forEach(pluginFunction => pluginFunction(api, options))
plugins.forEach(pluginFunction => pluginFunction(api, options));
return api
return api;
}

View File

@@ -1,3 +1,3 @@
const factory = require('./factory')
const factory = require("./factory");
module.exports = factory()
module.exports = factory();

View File

@@ -1,10 +1,10 @@
module.exports = factory
module.exports = factory;
const Octokit = require('./constructor')
const registerPlugin = require('./register-plugin')
const Octokit = require("./constructor");
const registerPlugin = require("./register-plugin");
function factory (plugins) {
const Api = Octokit.bind(null, plugins || [])
Api.plugin = registerPlugin.bind(null, plugins || [])
return Api
function factory(plugins) {
const Api = Octokit.bind(null, plugins || []);
Api.plugin = registerPlugin.bind(null, plugins || []);
return Api;
}

View File

@@ -1,21 +1,25 @@
module.exports = parseOptions
module.exports = parseOptions;
const { Deprecation } = require('deprecation')
const getUserAgent = require('universal-user-agent')
const once = require('once')
const { Deprecation } = require("deprecation");
const { getUserAgent } = require("universal-user-agent");
const once = require("once");
const pkg = require('../package.json')
const pkg = require("../package.json");
const deprecateOptionsTimeout = once((log, deprecation) => log.warn(deprecation))
const deprecateOptionsAgent = once((log, deprecation) => log.warn(deprecation))
const deprecateOptionsHeaders = once((log, deprecation) => log.warn(deprecation))
const deprecateOptionsTimeout = once((log, deprecation) =>
log.warn(deprecation)
);
const deprecateOptionsAgent = once((log, deprecation) => log.warn(deprecation));
const deprecateOptionsHeaders = once((log, deprecation) =>
log.warn(deprecation)
);
function parseOptions (options, log, hook) {
function parseOptions(options, log, hook) {
if (options.headers) {
options.headers = Object.keys(options.headers).reduce((newObj, key) => {
newObj[key.toLowerCase()] = options.headers[key]
return newObj
}, {})
newObj[key.toLowerCase()] = options.headers[key];
return newObj;
}, {});
}
const clientDefaults = {
@@ -23,42 +27,63 @@ function parseOptions (options, log, hook) {
request: options.request || {},
mediaType: {
previews: [],
format: ''
format: ""
}
}
};
if (options.baseUrl) {
clientDefaults.baseUrl = options.baseUrl
clientDefaults.baseUrl = options.baseUrl;
}
if (options.userAgent) {
clientDefaults.headers['user-agent'] = options.userAgent
clientDefaults.headers["user-agent"] = options.userAgent;
}
if (options.previews) {
clientDefaults.mediaType.previews = options.previews
clientDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
clientDefaults.headers["time-zone"] = options.timeZone;
}
if (options.timeout) {
deprecateOptionsTimeout(log, new Deprecation('[@octokit/rest] new Octokit({timeout}) is deprecated. Use {request: {timeout}} instead. See https://github.com/octokit/request.js#request'))
clientDefaults.request.timeout = options.timeout
deprecateOptionsTimeout(
log,
new Deprecation(
"[@octokit/rest] new Octokit({timeout}) is deprecated. Use {request: {timeout}} instead. See https://github.com/octokit/request.js#request"
)
);
clientDefaults.request.timeout = options.timeout;
}
if (options.agent) {
deprecateOptionsAgent(log, new Deprecation('[@octokit/rest] new Octokit({agent}) is deprecated. Use {request: {agent}} instead. See https://github.com/octokit/request.js#request'))
clientDefaults.request.agent = options.agent
deprecateOptionsAgent(
log,
new Deprecation(
"[@octokit/rest] new Octokit({agent}) is deprecated. Use {request: {agent}} instead. See https://github.com/octokit/request.js#request"
)
);
clientDefaults.request.agent = options.agent;
}
if (options.headers) {
deprecateOptionsHeaders(log, new Deprecation('[@octokit/rest] new Octokit({headers}) is deprecated. Use {userAgent, previews} instead. See https://github.com/octokit/request.js#request'))
deprecateOptionsHeaders(
log,
new Deprecation(
"[@octokit/rest] new Octokit({headers}) is deprecated. Use {userAgent, previews} instead. See https://github.com/octokit/request.js#request"
)
);
}
const userAgentOption = clientDefaults.headers['user-agent']
const defaultUserAgent = `octokit.js/${pkg.version} ${getUserAgent()}`
const userAgentOption = clientDefaults.headers["user-agent"];
const defaultUserAgent = `octokit.js/${pkg.version} ${getUserAgent()}`;
clientDefaults.headers['user-agent'] = [userAgentOption, defaultUserAgent].filter(Boolean).join(' ')
clientDefaults.headers["user-agent"] = [userAgentOption, defaultUserAgent]
.filter(Boolean)
.join(" ");
clientDefaults.request.hook = hook.bind(null, 'request')
clientDefaults.request.hook = hook.bind(null, "request");
return clientDefaults
return clientDefaults;
}

View File

@@ -1,7 +1,9 @@
module.exports = registerPlugin
module.exports = registerPlugin;
const factory = require('./factory')
const factory = require("./factory");
function registerPlugin (plugins, pluginFunction) {
return factory(plugins.includes(pluginFunction) ? plugins : plugins.concat(pluginFunction))
function registerPlugin(plugins, pluginFunction) {
return factory(
plugins.includes(pluginFunction) ? plugins : plugins.concat(pluginFunction)
);
}

View File

@@ -0,0 +1,21 @@
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.

View File

@@ -0,0 +1,68 @@
# http-error.js
> Error class for Octokit request errors
[![@latest](https://img.shields.io/npm/v/@octokit/request-error.svg)](https://www.npmjs.com/package/@octokit/request-error)
[![Build Status](https://travis-ci.com/octokit/request-error.js.svg?branch=master)](https://travis-ci.com/octokit/request-error.js)
[![Greenkeeper](https://badges.greenkeeper.io/octokit/request-error.js.svg)](https://greenkeeper.io/)
## Usage
<table>
<tbody valign=top align=left>
<tr><th>
Browsers
</th><td width=100%>
Load <code>@octokit/request-error</code> directly from <a href="https://cdn.pika.dev">cdn.pika.dev</a>
```html
<script type="module">
import { RequestError } from "https://cdn.pika.dev/@octokit/request-error";
</script>
```
</td></tr>
<tr><th>
Node
</th><td>
Install with <code>npm install @octokit/request-error</code>
```js
const { RequestError } = require("@octokit/request-error");
// or: import { RequestError } from "@octokit/request-error";
```
</td></tr>
</tbody>
</table>
```js
const error = new RequestError("Oops", 500, {
headers: {
"x-github-request-id": "1:2:3:4"
}, // response headers
request: {
method: "POST",
url: "https://api.github.com/foo",
body: {
bar: "baz"
},
headers: {
authorization: "token secret123"
}
}
});
error.message; // Oops
error.status; // 500
error.headers; // { 'x-github-request-id': '1:2:3:4' }
error.request.method; // POST
error.request.url; // https://api.github.com/foo
error.request.body; // { bar: 'baz' }
error.request.headers; // { authorization: 'token [REDACTED]' }
```
## LICENSE
[MIT](LICENSE)

View File

@@ -0,0 +1,55 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deprecation = require('deprecation');
var once = _interopDefault(require('once'));
const logOnce = once(deprecation => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {}; // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
}
exports.RequestError = RequestError;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["import { Deprecation } from \"deprecation\";\nimport once from \"once\";\nconst logOnce = once((deprecation) => console.warn(deprecation));\n/**\n * Error with extra properties to help with debugging\n */\nexport class RequestError extends Error {\n constructor(message, statusCode, options) {\n super(message);\n // Maintains proper stack trace (only available on V8)\n /* istanbul ignore next */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = \"HttpError\";\n this.status = statusCode;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnce(new Deprecation(\"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"));\n return statusCode;\n }\n });\n this.headers = options.headers || {};\n // redact request credentials without mutating original request options\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(/ .*$/, \" [REDACTED]\")\n });\n }\n requestCopy.url = requestCopy.url\n // client_id & client_secret can be passed as URL query parameters to increase rate limit\n // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications\n .replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\")\n // OAuth tokens can be passed as URL query parameters, although it is not recommended\n // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header\n .replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n}\n"],"names":["logOnce","once","deprecation","console","warn","RequestError","Error","constructor","message","statusCode","options","captureStackTrace","name","status","Object","defineProperty","get","Deprecation","headers","requestCopy","assign","request","authorization","replace","url"],"mappings":";;;;;;;;;AAEA,MAAMA,OAAO,GAAGC,IAAI,CAAEC,WAAD,IAAiBC,OAAO,CAACC,IAAR,CAAaF,WAAb,CAAlB,CAApB;;;;;AAIA,AAAO,MAAMG,YAAN,SAA2BC,KAA3B,CAAiC;EACpCC,WAAW,CAACC,OAAD,EAAUC,UAAV,EAAsBC,OAAtB,EAA+B;UAChCF,OAAN,EADsC;;;;QAIlCF,KAAK,CAACK,iBAAV,EAA6B;MACzBL,KAAK,CAACK,iBAAN,CAAwB,IAAxB,EAA8B,KAAKJ,WAAnC;;;SAECK,IAAL,GAAY,WAAZ;SACKC,MAAL,GAAcJ,UAAd;IACAK,MAAM,CAACC,cAAP,CAAsB,IAAtB,EAA4B,MAA5B,EAAoC;MAChCC,GAAG,GAAG;QACFhB,OAAO,CAAC,IAAIiB,uBAAJ,CAAgB,0EAAhB,CAAD,CAAP;eACOR,UAAP;;;KAHR;SAMKS,OAAL,GAAeR,OAAO,CAACQ,OAAR,IAAmB,EAAlC,CAfsC;;UAiBhCC,WAAW,GAAGL,MAAM,CAACM,MAAP,CAAc,EAAd,EAAkBV,OAAO,CAACW,OAA1B,CAApB;;QACIX,OAAO,CAACW,OAAR,CAAgBH,OAAhB,CAAwBI,aAA5B,EAA2C;MACvCH,WAAW,CAACD,OAAZ,GAAsBJ,MAAM,CAACM,MAAP,CAAc,EAAd,EAAkBV,OAAO,CAACW,OAAR,CAAgBH,OAAlC,EAA2C;QAC7DI,aAAa,EAAEZ,OAAO,CAACW,OAAR,CAAgBH,OAAhB,CAAwBI,aAAxB,CAAsCC,OAAtC,CAA8C,MAA9C,EAAsD,aAAtD;OADG,CAAtB;;;IAIJJ,WAAW,CAACK,GAAZ,GAAkBL,WAAW,CAACK,GAAZ;;KAGbD,OAHa,CAGL,sBAHK,EAGmB,0BAHnB;;KAMbA,OANa,CAML,qBANK,EAMkB,yBANlB,CAAlB;SAOKF,OAAL,GAAeF,WAAf;;;;;;;"}

View File

@@ -0,0 +1,40 @@
import { Deprecation } from "deprecation";
import once from "once";
const logOnce = once((deprecation) => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
export class RequestError extends Error {
constructor(message, statusCode, options) {
super(message);
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {};
// redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url
// client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]")
// OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
}

View File

@@ -0,0 +1,27 @@
import { RequestOptions, ResponseHeaders } from "@octokit/types";
import { RequestErrorOptions } from "./types";
/**
* Error with extra properties to help with debugging
*/
export declare class RequestError extends Error {
name: "HttpError";
/**
* http status code
*/
status: number;
/**
* http status code
*
* @deprecated `error.code` is deprecated in favor of `error.status`
*/
code: number;
/**
* error response headers
*/
headers: ResponseHeaders;
/**
* Request options that lead to the error.
*/
request: RequestOptions;
constructor(message: string, statusCode: number, options: RequestErrorOptions);
}

View File

@@ -0,0 +1,5 @@
import { RequestOptions, ResponseHeaders } from "@octokit/types";
export declare type RequestErrorOptions = {
headers?: ResponseHeaders;
request: RequestOptions;
};

View File

@@ -0,0 +1,44 @@
import { Deprecation } from 'deprecation';
import once from 'once';
const logOnce = once((deprecation) => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
class RequestError extends Error {
constructor(message, statusCode, options) {
super(message);
// Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {};
// redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url
// client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]")
// OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
}
export { RequestError };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["import { Deprecation } from \"deprecation\";\nimport once from \"once\";\nconst logOnce = once((deprecation) => console.warn(deprecation));\n/**\n * Error with extra properties to help with debugging\n */\nexport class RequestError extends Error {\n constructor(message, statusCode, options) {\n super(message);\n // Maintains proper stack trace (only available on V8)\n /* istanbul ignore next */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n this.name = \"HttpError\";\n this.status = statusCode;\n Object.defineProperty(this, \"code\", {\n get() {\n logOnce(new Deprecation(\"[@octokit/request-error] `error.code` is deprecated, use `error.status`.\"));\n return statusCode;\n }\n });\n this.headers = options.headers || {};\n // redact request credentials without mutating original request options\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(/ .*$/, \" [REDACTED]\")\n });\n }\n requestCopy.url = requestCopy.url\n // client_id & client_secret can be passed as URL query parameters to increase rate limit\n // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications\n .replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\")\n // OAuth tokens can be passed as URL query parameters, although it is not recommended\n // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header\n .replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n}\n"],"names":[],"mappings":";;;AAEA,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;;;;AAIjE,AAAO,MAAM,YAAY,SAAS,KAAK,CAAC;IACpC,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE;QACtC,KAAK,CAAC,OAAO,CAAC,CAAC;;;QAGf,IAAI,KAAK,CAAC,iBAAiB,EAAE;YACzB,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;SACnD;QACD,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC;QACzB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE;YAChC,GAAG,GAAG;gBACF,OAAO,CAAC,IAAI,WAAW,CAAC,0EAA0E,CAAC,CAAC,CAAC;gBACrG,OAAO,UAAU,CAAC;aACrB;SACJ,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC;;QAErC,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACvD,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE;YACvC,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE;gBAC7D,aAAa,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,aAAa,CAAC;aACtF,CAAC,CAAC;SACN;QACD,WAAW,CAAC,GAAG,GAAG,WAAW,CAAC,GAAG;;;aAG5B,OAAO,CAAC,sBAAsB,EAAE,0BAA0B,CAAC;;;aAG3D,OAAO,CAAC,qBAAqB,EAAE,yBAAyB,CAAC,CAAC;QAC/D,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC;KAC9B;CACJ;;;;"}

View File

@@ -0,0 +1,80 @@
{
"_from": "@octokit/request-error@^1.0.2",
"_id": "@octokit/request-error@1.2.1",
"_inBundle": false,
"_integrity": "sha512-+6yDyk1EES6WK+l3viRDElw96MvwfJxCt45GvmjDUKWjYIb3PJZQkq3i46TwGwoPD4h8NmTrENmtyA1FwbmhRA==",
"_location": "/@octokit/rest/@octokit/request-error",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@octokit/request-error@^1.0.2",
"name": "@octokit/request-error",
"escapedName": "@octokit%2frequest-error",
"scope": "@octokit",
"rawSpec": "^1.0.2",
"saveSpec": null,
"fetchSpec": "^1.0.2"
},
"_requiredBy": [
"/@octokit/rest"
],
"_resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-1.2.1.tgz",
"_shasum": "ede0714c773f32347576c25649dc013ae6b31801",
"_spec": "@octokit/request-error@^1.0.2",
"_where": "/Users/pjquirk/Source/GitHub/actions/labeler/node_modules/@octokit/rest",
"bugs": {
"url": "https://github.com/octokit/request-error.js/issues"
},
"bundleDependencies": false,
"dependencies": {
"@octokit/types": "^2.0.0",
"deprecation": "^2.0.0",
"once": "^1.4.0"
},
"deprecated": false,
"description": "Error class for Octokit request errors",
"devDependencies": {
"@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.8.1",
"@pika/plugin-build-web": "^0.8.1",
"@pika/plugin-bundle-web": "^0.8.1",
"@pika/plugin-ts-standard-pkg": "^0.8.1",
"@types/jest": "^25.1.0",
"@types/node": "^13.1.0",
"@types/once": "^1.4.0",
"jest": "^24.7.1",
"pika-plugin-unpkg-field": "^1.1.0",
"prettier": "^1.17.0",
"semantic-release": "^17.0.0",
"ts-jest": "^24.0.2",
"typescript": "^3.4.5"
},
"files": [
"dist-*/",
"bin/"
],
"homepage": "https://github.com/octokit/request-error.js#readme",
"keywords": [
"octokit",
"github",
"api",
"error"
],
"license": "MIT",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"name": "@octokit/request-error",
"pika": true,
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/octokit/request-error.js.git"
},
"sideEffects": false,
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"version": "1.2.1"
}

View File

@@ -1,35 +0,0 @@
language: node_js
cache: npm
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- master
- /^greenkeeper.*$/
stages:
- test
- name: release
if: branch = master AND type IN (push)
jobs:
include:
- stage: test
node_js: 12
script: npm run test
- node_js: 8
script: npm run test
- node_js: 10
env: Node 10 & coverage upload
script:
- npm run test
- npm run coverage:upload
- node_js: lts/*
env: browser tests
script: npm run test:browser
- stage: release
node_js: lts/*
env: semantic-release
script: npm run semantic-release

View File

@@ -4,13 +4,13 @@
[![@latest](https://img.shields.io/npm/v/universal-user-agent.svg)](https://www.npmjs.com/package/universal-user-agent)
[![Build Status](https://travis-ci.com/gr2m/universal-user-agent.svg?branch=master)](https://travis-ci.com/gr2m/universal-user-agent)
[![Coverage Status](https://coveralls.io/repos/github/gr2m/universal-user-agent/badge.svg)](https://coveralls.io/github/gr2m/universal-user-agent)
[![Greenkeeper](https://badges.greenkeeper.io/gr2m/universal-user-agent.svg)](https://greenkeeper.io/)
```js
const getUserAgent = require('universal-user-agent')
const userAgent = getUserAgent()
const { getUserAgent } = require("universal-user-agent");
// or import { getUserAgent } from "universal-user-agent";
const userAgent = getUserAgent();
// userAgent will look like this
// in browser: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
// in node: Node.js/v8.9.4 (macOS High Sierra; x64)

View File

@@ -1,6 +0,0 @@
module.exports = getUserAgentBrowser
function getUserAgentBrowser () {
/* global navigator */
return navigator.userAgent
}

View File

@@ -1,4 +0,0 @@
{
"integrationFolder": "test",
"video": false
}

View File

@@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var osName = _interopDefault(require('os-name'));
function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/node.js"],"sourcesContent":["import osName from \"os-name\";\nexport function getUserAgent() {\n try {\n return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;\n }\n catch (error) {\n if (/wmic os get Caption/.test(error.message)) {\n return \"Windows <version undetectable>\";\n }\n throw error;\n }\n}\n"],"names":["getUserAgent","process","version","substr","osName","arch","error","test","message"],"mappings":";;;;;;;;AACO,SAASA,YAAT,GAAwB;MACvB;WACQ,WAAUC,OAAO,CAACC,OAAR,CAAgBC,MAAhB,CAAuB,CAAvB,CAA0B,KAAIC,MAAM,EAAG,KAAIH,OAAO,CAACI,IAAK,GAA1E;GADJ,CAGA,OAAOC,KAAP,EAAc;QACN,sBAAsBC,IAAtB,CAA2BD,KAAK,CAACE,OAAjC,CAAJ,EAA+C;aACpC,gCAAP;;;UAEEF,KAAN;;;;;;"}

View File

@@ -0,0 +1,8 @@
export function getUserAgent() {
try {
return navigator.userAgent;
}
catch (e) {
return "<environment unknown>";
}
}

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1,12 @@
import osName from "os-name";
export function getUserAgent() {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`;
}
catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return "Windows <version undetectable>";
}
throw error;
}
}

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1 @@
export { getUserAgent } from "./node";

View File

@@ -0,0 +1 @@
export declare function getUserAgent(): string;

View File

@@ -0,0 +1,11 @@
function getUserAgent() {
try {
return navigator.userAgent;
}
catch (e) {
return "<environment unknown>";
}
}
export { getUserAgent };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../dist-src/browser.js"],"sourcesContent":["export function getUserAgent() {\n try {\n return navigator.userAgent;\n }\n catch (e) {\n return \"<environment unknown>\";\n }\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;IAC3B,IAAI;QACA,OAAO,SAAS,CAAC,SAAS,CAAC;KAC9B;IACD,OAAO,CAAC,EAAE;QACN,OAAO,uBAAuB,CAAC;KAClC;CACJ;;;;"}

View File

@@ -1 +0,0 @@
export default function getUserAgentNode(): string;

View File

@@ -1,15 +0,0 @@
module.exports = getUserAgentNode
const osName = require('os-name')
function getUserAgentNode () {
try {
return `Node.js/${process.version.substr(1)} (${osName()}; ${process.arch})`
} catch (error) {
if (/wmic os get Caption/.test(error.message)) {
return 'Windows <version undetectable>'
}
throw error
}
}

View File

@@ -1,85 +1,65 @@
{
"_args": [
[
"universal-user-agent@3.0.0",
"C:\\Users\\damccorm\\Documents\\labeler"
]
],
"_from": "universal-user-agent@3.0.0",
"_id": "universal-user-agent@3.0.0",
"_from": "universal-user-agent@^4.0.0",
"_id": "universal-user-agent@4.0.1",
"_inBundle": false,
"_integrity": "sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA==",
"_integrity": "sha512-LnST3ebHwVL2aNe4mejI9IQh2HfZ1RLo8Io2HugSif8ekzD1TlWpHpColOB/eh8JHMLkGH3Akqf040I+4ylNxg==",
"_location": "/@octokit/rest/universal-user-agent",
"_phantomChildren": {},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "universal-user-agent@3.0.0",
"raw": "universal-user-agent@^4.0.0",
"name": "universal-user-agent",
"escapedName": "universal-user-agent",
"rawSpec": "3.0.0",
"rawSpec": "^4.0.0",
"saveSpec": null,
"fetchSpec": "3.0.0"
"fetchSpec": "^4.0.0"
},
"_requiredBy": [
"/@octokit/rest"
],
"_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-3.0.0.tgz",
"_spec": "3.0.0",
"_where": "C:\\Users\\damccorm\\Documents\\labeler",
"author": {
"name": "Gregor Martynus",
"url": "https://github.com/gr2m"
},
"browser": "browser.js",
"_resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.1.tgz",
"_shasum": "fd8d6cb773a679a709e967ef8288a31fcc03e557",
"_spec": "universal-user-agent@^4.0.0",
"_where": "/Users/pjquirk/Source/GitHub/actions/labeler/node_modules/@octokit/rest",
"bugs": {
"url": "https://github.com/gr2m/universal-user-agent/issues"
},
"bundleDependencies": false,
"dependencies": {
"os-name": "^3.0.0"
"os-name": "^3.1.0"
},
"deprecated": false,
"description": "Get a user agent string in both browser and node",
"devDependencies": {
"chai": "^4.1.2",
"coveralls": "^3.0.2",
"cypress": "^3.1.0",
"mocha": "^6.0.0",
"nyc": "^14.0.0",
"proxyquire": "^2.1.0",
"semantic-release": "^15.9.15",
"sinon": "^7.2.4",
"sinon-chai": "^3.2.0",
"standard": "^13.0.1",
"test": "^0.6.0",
"travis-deploy-once": "^5.0.7"
"@gr2m/pika-plugin-build-web": "^0.6.0-issue-84.1",
"@pika/pack": "^0.5.0",
"@pika/plugin-build-node": "^0.9.1",
"@pika/plugin-ts-standard-pkg": "^0.9.1",
"@types/jest": "^25.1.0",
"jest": "^24.9.0",
"prettier": "^1.18.2",
"semantic-release": "^17.0.0",
"ts-jest": "^25.1.0",
"typescript": "^3.6.2"
},
"files": [
"dist-*/",
"bin/"
],
"homepage": "https://github.com/gr2m/universal-user-agent#readme",
"keywords": [],
"license": "ISC",
"main": "index.js",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"name": "universal-user-agent",
"pika": true,
"repository": {
"type": "git",
"url": "git+https://github.com/gr2m/universal-user-agent.git"
},
"scripts": {
"coverage": "nyc report --reporter=html && open coverage/index.html",
"coverage:upload": "nyc report --reporter=text-lcov | coveralls",
"pretest": "standard",
"semantic-release": "semantic-release",
"test": "nyc mocha \"test/*-test.js\"",
"test:browser": "cypress run --browser chrome",
"travis-deploy-once": "travis-deploy-once"
},
"standard": {
"globals": [
"describe",
"it",
"beforeEach",
"afterEach",
"expect"
]
},
"types": "index.d.ts",
"version": "3.0.0"
"sideEffects": false,
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"version": "4.0.1"
}

View File

@@ -1,57 +0,0 @@
// make tests run in both Node & Express
if (!global.cy) {
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
global.expect = chai.expect
let sandbox
beforeEach(() => {
sandbox = sinon.createSandbox()
global.cy = {
stub: function () {
return sandbox.stub.apply(sandbox, arguments)
},
log () {
console.log.apply(console, arguments)
}
}
})
afterEach(() => {
sandbox.restore()
})
}
const getUserAgent = require('..')
describe('smoke', () => {
it('works', () => {
expect(getUserAgent()).to.be.a('string')
expect(getUserAgent().length).to.be.above(10)
})
if (!process.browser) { // test on node only
const proxyquire = require('proxyquire').noCallThru()
it('works around wmic error on Windows (#5)', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('Command failed: wmic os get Caption')
}
})
expect(getUserAgent()).to.equal('Windows <version undetectable>')
})
it('does not swallow unexpected errors', () => {
const getUserAgent = proxyquire('..', {
'os-name': () => {
throw new Error('oops')
}
})
expect(getUserAgent).to.throw('oops')
})
}
})

View File

@@ -1,35 +1,33 @@
{
"_args": [
[
"@octokit/rest@16.28.7",
"C:\\Users\\damccorm\\Documents\\labeler"
]
],
"_from": "@octokit/rest@16.28.7",
"_id": "@octokit/rest@16.28.7",
"_from": "@octokit/rest@^16.43.1",
"_id": "@octokit/rest@16.43.1",
"_inBundle": false,
"_integrity": "sha512-cznFSLEhh22XD3XeqJw51OLSfyL2fcFKUO+v2Ep9MTAFfFLS1cK1Zwd1yEgQJmJoDnj4/vv3+fGGZweG+xsbIA==",
"_integrity": "sha512-gfFKwRT/wFxq5qlNjnW2dh+qh74XgTQ2B179UX5K1HYCluioWj8Ndbgqw2PVqa1NnVJkGHp2ovMpVn/DImlmkw==",
"_location": "/@octokit/rest",
"_phantomChildren": {
"@octokit/types": "2.16.2",
"deprecation": "2.3.1",
"once": "1.4.0",
"os-name": "3.1.0"
},
"_requested": {
"type": "version",
"type": "range",
"registry": true,
"raw": "@octokit/rest@16.28.7",
"raw": "@octokit/rest@^16.43.1",
"name": "@octokit/rest",
"escapedName": "@octokit%2frest",
"scope": "@octokit",
"rawSpec": "16.28.7",
"rawSpec": "^16.43.1",
"saveSpec": null,
"fetchSpec": "16.28.7"
"fetchSpec": "^16.43.1"
},
"_requiredBy": [
"/@actions/github"
],
"_resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.28.7.tgz",
"_spec": "16.28.7",
"_where": "C:\\Users\\damccorm\\Documents\\labeler",
"_resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.43.1.tgz",
"_shasum": "3b11e7d1b1ac2bbeeb23b08a17df0b20947eda6b",
"_spec": "@octokit/rest@^16.43.1",
"_where": "/Users/pjquirk/Source/GitHub/actions/labeler/node_modules/@actions/github",
"author": {
"name": "Gregor Martynus",
"url": "https://github.com/gr2m"
@@ -37,6 +35,7 @@
"bugs": {
"url": "https://github.com/octokit/rest.js/issues"
},
"bundleDependencies": false,
"bundlesize": [
{
"path": "./dist/octokit-rest.min.js.gz",
@@ -62,7 +61,11 @@
}
],
"dependencies": {
"@octokit/request": "^5.0.0",
"@octokit/auth-token": "^2.4.0",
"@octokit/plugin-paginate-rest": "^1.1.1",
"@octokit/plugin-request-log": "^1.0.0",
"@octokit/plugin-rest-endpoint-methods": "2.4.0",
"@octokit/request": "^5.2.0",
"@octokit/request-error": "^1.0.2",
"atob-lite": "^2.0.0",
"before-after-hook": "^2.0.0",
@@ -73,37 +76,38 @@
"lodash.uniq": "^4.5.0",
"octokit-pagination-methods": "^1.1.0",
"once": "^1.4.0",
"universal-user-agent": "^3.0.0",
"url-template": "^2.0.8"
"universal-user-agent": "^4.0.0"
},
"deprecated": false,
"description": "GitHub REST API client for Node.js",
"devDependencies": {
"@gimenete/type-writer": "^0.1.3",
"@octokit/fixtures-server": "^5.0.1",
"@octokit/routes": "20.9.2",
"@types/node": "^12.0.0",
"@octokit/auth": "^1.1.1",
"@octokit/fixtures-server": "^5.0.6",
"@octokit/graphql": "^4.2.0",
"@types/node": "^13.1.0",
"bundlesize": "^0.18.0",
"chai": "^4.1.2",
"compression-webpack-plugin": "^3.0.0",
"coveralls": "^3.0.0",
"compression-webpack-plugin": "^3.1.0",
"cypress": "^3.0.0",
"glob": "^7.1.2",
"http-proxy-agent": "^2.1.0",
"http-proxy-agent": "^4.0.0",
"lodash.camelcase": "^4.3.0",
"lodash.merge": "^4.6.1",
"lodash.upperfirst": "^4.3.1",
"mkdirp": "^0.5.1",
"mocha": "^6.0.0",
"mustache": "^3.0.0",
"nock": "^10.0.0",
"lolex": "^5.1.2",
"mkdirp": "^1.0.0",
"mocha": "^7.0.1",
"mustache": "^4.0.0",
"nock": "^11.3.3",
"npm-run-all": "^4.1.2",
"nyc": "^14.0.0",
"nyc": "^15.0.0",
"prettier": "^1.14.2",
"proxy": "^0.2.4",
"semantic-release": "^15.0.0",
"sinon": "^7.2.4",
"proxy": "^1.0.0",
"semantic-release": "^17.0.0",
"sinon": "^8.0.0",
"sinon-chai": "^3.0.0",
"sort-keys": "^3.0.0",
"standard": "^13.0.1",
"sort-keys": "^4.0.0",
"string-to-arraybuffer": "^1.0.0",
"string-to-jsdoc-comment": "^1.0.0",
"typescript": "^3.3.1",
@@ -155,35 +159,23 @@
"build:browser": "npm-run-all build:browser:*",
"build:browser:development": "webpack --mode development --entry . --output-library=Octokit --output=./dist/octokit-rest.js --profile --json > dist/bundle-stats.json",
"build:browser:production": "webpack --mode production --entry . --plugin=compression-webpack-plugin --output-library=Octokit --output-path=./dist --output-filename=octokit-rest.min.js --devtool source-map",
"build:ts": "node scripts/generate-types",
"build:ts": "npm run -s update-endpoints:typescript",
"coverage": "nyc report --reporter=html && open coverage/index.html",
"generate-bundle-report": "webpack-bundle-analyzer dist/bundle-stats.json --mode=static --no-open --report dist/bundle-report.html",
"generate-routes": "node scripts/generate-routes",
"lint": "prettier --check '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json",
"lint:fix": "prettier --write '{lib,plugins,scripts,test}/**/*.{js,json,ts}' 'docs/*.{js,json}' 'docs/src/**/*' index.js README.md package.json",
"postvalidate:ts": "tsc --noEmit --target es6 test/typescript-validate.ts",
"prebuild:browser": "mkdirp dist/",
"pretest": "standard",
"pretest": "npm run -s lint",
"prevalidate:ts": "npm run -s build:ts",
"start-fixtures-server": "octokit-fixtures-server",
"test": "nyc mocha test/mocha-node-setup.js \"test/*/**/*-test.js\"",
"test:browser": "cypress run --browser chrome",
"test:memory": "mocha test/memory-test",
"update-endpoints": "npm-run-all update-endpoints:*",
"update-endpoints:fetch-json": "node scripts/update-endpoints/fetch-json",
"update-endpoints:typescript": "node scripts/update-endpoints/typescript",
"validate:ts": "tsc --target es6 --noImplicitAny index.d.ts"
},
"standard": {
"globals": [
"describe",
"before",
"beforeEach",
"afterEach",
"after",
"it",
"expect",
"cy"
],
"ignore": [
"/docs"
]
},
"types": "index.d.ts",
"version": "16.28.7"
"version": "16.43.1"
}

View File

@@ -1,41 +1,52 @@
module.exports = authenticate
module.exports = authenticate;
const { Deprecation } = require('deprecation')
const once = require('once')
const { Deprecation } = require("deprecation");
const once = require("once");
const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation))
const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation));
function authenticate (state, options) {
deprecateAuthenticate(state.octokit.log, new Deprecation('[@octokit/rest] octokit.authenticate() is deprecated. Use "auth" constructor option instead.'))
function authenticate(state, options) {
deprecateAuthenticate(
state.octokit.log,
new Deprecation(
'[@octokit/rest] octokit.authenticate() is deprecated. Use "auth" constructor option instead.'
)
);
if (!options) {
state.auth = false
return
state.auth = false;
return;
}
switch (options.type) {
case 'basic':
case "basic":
if (!options.username || !options.password) {
throw new Error('Basic authentication requires both a username and password to be set')
throw new Error(
"Basic authentication requires both a username and password to be set"
);
}
break
break;
case 'oauth':
case "oauth":
if (!options.token && !(options.key && options.secret)) {
throw new Error('OAuth2 authentication requires a token or key & secret to be set')
throw new Error(
"OAuth2 authentication requires a token or key & secret to be set"
);
}
break
break;
case 'token':
case 'app':
case "token":
case "app":
if (!options.token) {
throw new Error('Token authentication requires a token to be set')
throw new Error("Token authentication requires a token to be set");
}
break
break;
default:
throw new Error("Invalid authentication type, must be 'basic', 'oauth', 'token' or 'app'")
throw new Error(
"Invalid authentication type, must be 'basic', 'oauth', 'token' or 'app'"
);
}
state.auth = options
state.auth = options;
}

View File

@@ -1,40 +1,43 @@
module.exports = authenticationBeforeRequest
module.exports = authenticationBeforeRequest;
const btoa = require('btoa-lite')
const uniq = require('lodash.uniq')
const btoa = require("btoa-lite");
const uniq = require("lodash.uniq");
function authenticationBeforeRequest (state, options) {
function authenticationBeforeRequest(state, options) {
if (!state.auth.type) {
return
return;
}
if (state.auth.type === 'basic') {
const hash = btoa(`${state.auth.username}:${state.auth.password}`)
options.headers['authorization'] = `Basic ${hash}`
return
if (state.auth.type === "basic") {
const hash = btoa(`${state.auth.username}:${state.auth.password}`);
options.headers.authorization = `Basic ${hash}`;
return;
}
if (state.auth.type === 'token') {
options.headers['authorization'] = `token ${state.auth.token}`
return
if (state.auth.type === "token") {
options.headers.authorization = `token ${state.auth.token}`;
return;
}
if (state.auth.type === 'app') {
options.headers['authorization'] = `Bearer ${state.auth.token}`
const acceptHeaders = options.headers['accept'].split(',')
.concat('application/vnd.github.machine-man-preview+json')
options.headers['accept'] = uniq(acceptHeaders).filter(Boolean).join(',')
return
if (state.auth.type === "app") {
options.headers.authorization = `Bearer ${state.auth.token}`;
const acceptHeaders = options.headers.accept
.split(",")
.concat("application/vnd.github.machine-man-preview+json");
options.headers.accept = uniq(acceptHeaders)
.filter(Boolean)
.join(",");
return;
}
options.url += options.url.indexOf('?') === -1 ? '?' : '&'
options.url += options.url.indexOf("?") === -1 ? "?" : "&";
if (state.auth.token) {
options.url += `access_token=${encodeURIComponent(state.auth.token)}`
return
options.url += `access_token=${encodeURIComponent(state.auth.token)}`;
return;
}
const key = encodeURIComponent(state.auth.key)
const secret = encodeURIComponent(state.auth.secret)
options.url += `client_id=${key}&client_secret=${secret}`
const key = encodeURIComponent(state.auth.key);
const secret = encodeURIComponent(state.auth.secret);
options.url += `client_id=${key}&client_secret=${secret}`;
}

View File

@@ -1,26 +1,31 @@
module.exports = authenticationPlugin
module.exports = authenticationPlugin;
const { Deprecation } = require('deprecation')
const once = require('once')
const { Deprecation } = require("deprecation");
const once = require("once");
const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation))
const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation));
const authenticate = require('./authenticate')
const beforeRequest = require('./before-request')
const requestError = require('./request-error')
const authenticate = require("./authenticate");
const beforeRequest = require("./before-request");
const requestError = require("./request-error");
function authenticationPlugin (octokit, options) {
function authenticationPlugin(octokit, options) {
if (options.auth) {
octokit.authenticate = () => {
deprecateAuthenticate(octokit.log, new Deprecation('[@octokit/rest] octokit.authenticate() is deprecated and has no effect when "auth" option is set on Octokit constructor'))
}
return
deprecateAuthenticate(
octokit.log,
new Deprecation(
'[@octokit/rest] octokit.authenticate() is deprecated and has no effect when "auth" option is set on Octokit constructor'
)
);
};
return;
}
const state = {
octokit,
auth: false
}
octokit.authenticate = authenticate.bind(null, state)
octokit.hook.before('request', beforeRequest.bind(null, state))
octokit.hook.error('request', requestError.bind(null, state))
};
octokit.authenticate = authenticate.bind(null, state);
octokit.hook.before("request", beforeRequest.bind(null, state));
octokit.hook.error("request", requestError.bind(null, state));
}

View File

@@ -1,39 +1,55 @@
module.exports = authenticationRequestError
module.exports = authenticationRequestError;
const { RequestError } = require('@octokit/request-error')
const { RequestError } = require("@octokit/request-error");
function authenticationRequestError (state, error, options) {
function authenticationRequestError(state, error, options) {
/* istanbul ignore next */
if (!error.headers) throw error
if (!error.headers) throw error;
const otpRequired = /required/.test(error.headers['x-github-otp'] || '')
const otpRequired = /required/.test(error.headers["x-github-otp"] || "");
// handle "2FA required" error only
if (error.status !== 401 || !otpRequired) {
throw error
throw error;
}
if (error.status === 401 && otpRequired && error.request && error.request.headers['x-github-otp']) {
throw new RequestError('Invalid one-time password for two-factor authentication', 401, {
headers: error.headers,
request: options
})
if (
error.status === 401 &&
otpRequired &&
error.request &&
error.request.headers["x-github-otp"]
) {
throw new RequestError(
"Invalid one-time password for two-factor authentication",
401,
{
headers: error.headers,
request: options
}
);
}
if (typeof state.auth.on2fa !== 'function') {
throw new RequestError('2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication', 401, {
headers: error.headers,
request: options
})
if (typeof state.auth.on2fa !== "function") {
throw new RequestError(
"2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication",
401,
{
headers: error.headers,
request: options
}
);
}
return Promise.resolve()
.then(() => {
return state.auth.on2fa()
return state.auth.on2fa();
})
.then((oneTimePassword) => {
.then(oneTimePassword => {
const newOptions = Object.assign(options, {
headers: Object.assign({ 'x-github-otp': oneTimePassword }, options.headers)
})
return state.octokit.request(newOptions)
})
headers: Object.assign(
{ "x-github-otp": oneTimePassword },
options.headers
)
});
return state.octokit.request(newOptions);
});
}

View File

@@ -1,30 +1,22 @@
module.exports = authenticationBeforeRequest
module.exports = authenticationBeforeRequest;
const btoa = require('btoa-lite')
const btoa = require("btoa-lite");
const withAuthorizationPrefix = require('./with-authorization-prefix')
const withAuthorizationPrefix = require("./with-authorization-prefix");
function authenticationBeforeRequest (state, options) {
if (typeof state.auth === 'string') {
options.headers['authorization'] = withAuthorizationPrefix(state.auth)
// https://developer.github.com/v3/previews/#integrations
if (/^bearer /i.test(state.auth) && !/machine-man/.test(options.headers['accept'])) {
const acceptHeaders = options.headers['accept'].split(',')
.concat('application/vnd.github.machine-man-preview+json')
options.headers['accept'] = acceptHeaders.filter(Boolean).join(',')
}
return
function authenticationBeforeRequest(state, options) {
if (typeof state.auth === "string") {
options.headers.authorization = withAuthorizationPrefix(state.auth);
return;
}
if (state.auth.username) {
const hash = btoa(`${state.auth.username}:${state.auth.password}`)
options.headers['authorization'] = `Basic ${hash}`
const hash = btoa(`${state.auth.username}:${state.auth.password}`);
options.headers.authorization = `Basic ${hash}`;
if (state.otp) {
options.headers['x-github-otp'] = state.otp
options.headers["x-github-otp"] = state.otp;
}
return
return;
}
if (state.auth.clientId) {
@@ -39,23 +31,23 @@ function authenticationBeforeRequest (state, options) {
// We identify by checking the URL. It must merge both "/applications/:client_id/tokens/:access_token"
// as well as "/applications/123/tokens/token456"
if (/\/applications\/:?[\w_]+\/tokens\/:?[\w_]+($|\?)/.test(options.url)) {
const hash = btoa(`${state.auth.clientId}:${state.auth.clientSecret}`)
options.headers['authorization'] = `Basic ${hash}`
return
const hash = btoa(`${state.auth.clientId}:${state.auth.clientSecret}`);
options.headers.authorization = `Basic ${hash}`;
return;
}
options.url += options.url.indexOf('?') === -1 ? '?' : '&'
options.url += `client_id=${state.auth.clientId}&client_secret=${state.auth.clientSecret}`
return
options.url += options.url.indexOf("?") === -1 ? "?" : "&";
options.url += `client_id=${state.auth.clientId}&client_secret=${state.auth.clientSecret}`;
return;
}
return Promise.resolve()
.then(() => {
return state.auth()
return state.auth();
})
.then((authorization) => {
options.headers['authorization'] = withAuthorizationPrefix(authorization)
})
.then(authorization => {
options.headers.authorization = withAuthorizationPrefix(authorization);
});
}

View File

@@ -1,21 +1,76 @@
module.exports = authenticationPlugin
module.exports = authenticationPlugin;
const beforeRequest = require('./before-request')
const requestError = require('./request-error')
const validate = require('./validate')
const { createTokenAuth } = require("@octokit/auth-token");
const { Deprecation } = require("deprecation");
const once = require("once");
function authenticationPlugin (octokit, options) {
if (!options.auth) {
return
const beforeRequest = require("./before-request");
const requestError = require("./request-error");
const validate = require("./validate");
const withAuthorizationPrefix = require("./with-authorization-prefix");
const deprecateAuthBasic = once((log, deprecation) => log.warn(deprecation));
const deprecateAuthObject = once((log, deprecation) => log.warn(deprecation));
function authenticationPlugin(octokit, options) {
// If `options.authStrategy` is set then use it and pass in `options.auth`
if (options.authStrategy) {
const auth = options.authStrategy(options.auth);
octokit.hook.wrap("request", auth.hook);
octokit.auth = auth;
return;
}
validate(options.auth)
// If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `octokit.auth()` method is a no-op and no request hook is registred.
if (!options.auth) {
octokit.auth = () =>
Promise.resolve({
type: "unauthenticated"
});
return;
}
const isBasicAuthString =
typeof options.auth === "string" &&
/^basic/.test(withAuthorizationPrefix(options.auth));
// If only `options.auth` is set to a string, use the default token authentication strategy.
if (typeof options.auth === "string" && !isBasicAuthString) {
const auth = createTokenAuth(options.auth);
octokit.hook.wrap("request", auth.hook);
octokit.auth = auth;
return;
}
// Otherwise log a deprecation message
const [deprecationMethod, deprecationMessapge] = isBasicAuthString
? [
deprecateAuthBasic,
'Setting the "new Octokit({ auth })" option to a Basic Auth string is deprecated. Use https://github.com/octokit/auth-basic.js instead. See (https://octokit.github.io/rest.js/#authentication)'
]
: [
deprecateAuthObject,
'Setting the "new Octokit({ auth })" option to an object without also setting the "authStrategy" option is deprecated and will be removed in v17. See (https://octokit.github.io/rest.js/#authentication)'
];
deprecationMethod(
octokit.log,
new Deprecation("[@octokit/rest] " + deprecationMessapge)
);
octokit.auth = () =>
Promise.resolve({
type: "deprecated",
message: deprecationMessapge
});
validate(options.auth);
const state = {
octokit,
auth: options.auth
}
};
octokit.hook.before('request', beforeRequest.bind(null, state))
octokit.hook.error('request', requestError.bind(null, state))
octokit.hook.before("request", beforeRequest.bind(null, state));
octokit.hook.error("request", requestError.bind(null, state));
}

View File

@@ -1,47 +1,61 @@
module.exports = authenticationRequestError
module.exports = authenticationRequestError;
const { RequestError } = require('@octokit/request-error')
const { RequestError } = require("@octokit/request-error");
function authenticationRequestError (state, error, options) {
if (!error.headers) throw error
function authenticationRequestError(state, error, options) {
if (!error.headers) throw error;
const otpRequired = /required/.test(error.headers['x-github-otp'] || '')
const otpRequired = /required/.test(error.headers["x-github-otp"] || "");
// handle "2FA required" error only
if (error.status !== 401 || !otpRequired) {
throw error
throw error;
}
if (error.status === 401 && otpRequired && error.request && error.request.headers['x-github-otp']) {
if (
error.status === 401 &&
otpRequired &&
error.request &&
error.request.headers["x-github-otp"]
) {
if (state.otp) {
delete state.otp // no longer valid, request again
delete state.otp; // no longer valid, request again
} else {
throw new RequestError('Invalid one-time password for two-factor authentication', 401, {
headers: error.headers,
request: options
})
throw new RequestError(
"Invalid one-time password for two-factor authentication",
401,
{
headers: error.headers,
request: options
}
);
}
}
if (typeof state.auth.on2fa !== 'function') {
throw new RequestError('2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication', 401, {
headers: error.headers,
request: options
})
if (typeof state.auth.on2fa !== "function") {
throw new RequestError(
"2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication",
401,
{
headers: error.headers,
request: options
}
);
}
return Promise.resolve()
.then(() => {
return state.auth.on2fa()
return state.auth.on2fa();
})
.then((oneTimePassword) => {
.then(oneTimePassword => {
const newOptions = Object.assign(options, {
headers: Object.assign(options.headers, { 'x-github-otp': oneTimePassword })
})
return state.octokit.request(newOptions)
.then(response => {
// If OTP still valid, then persist it for following requests
state.otp = oneTimePassword
return response
headers: Object.assign(options.headers, {
"x-github-otp": oneTimePassword
})
})
});
return state.octokit.request(newOptions).then(response => {
// If OTP still valid, then persist it for following requests
state.otp = oneTimePassword;
return response;
});
});
}

View File

@@ -1,21 +1,21 @@
module.exports = validateAuth
module.exports = validateAuth;
function validateAuth (auth) {
if (typeof auth === 'string') {
return
function validateAuth(auth) {
if (typeof auth === "string") {
return;
}
if (typeof auth === 'function') {
return
if (typeof auth === "function") {
return;
}
if (auth.username && auth.password) {
return
return;
}
if (auth.clientId && auth.clientSecret) {
return
return;
}
throw new Error(`Invalid "auth" option: ${JSON.stringify(auth)}`)
throw new Error(`Invalid "auth" option: ${JSON.stringify(auth)}`);
}

View File

@@ -1,23 +1,23 @@
module.exports = withAuthorizationPrefix
module.exports = withAuthorizationPrefix;
const atob = require('atob-lite')
const atob = require("atob-lite");
const REGEX_IS_BASIC_AUTH = /^[\w-]+:/
const REGEX_IS_BASIC_AUTH = /^[\w-]+:/;
function withAuthorizationPrefix (authorization) {
function withAuthorizationPrefix(authorization) {
if (/^(basic|bearer|token) /i.test(authorization)) {
return authorization
return authorization;
}
try {
if (REGEX_IS_BASIC_AUTH.test(atob(authorization))) {
return `basic ${authorization}`
return `basic ${authorization}`;
}
} catch (error) { }
} catch (error) {}
if (authorization.split(/\./).length === 3) {
return `bearer ${authorization}`
return `bearer ${authorization}`;
}
return `token ${authorization}`
return `token ${authorization}`;
}

View File

@@ -1,22 +0,0 @@
module.exports = octokitDebug
function octokitDebug (octokit) {
octokit.hook.wrap('request', (request, options) => {
octokit.log.debug(`request`, options)
const start = Date.now()
const requestOptions = octokit.request.endpoint.parse(options)
const path = requestOptions.url.replace(options.baseUrl, '')
return request(options)
.then(response => {
octokit.log.info(`${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`)
return response
})
.catch(error => {
octokit.log.info(`${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`)
throw error
})
})
}

View File

@@ -1,53 +0,0 @@
module.exports = octokitRestNormalizeGitReferenceResponses
const { RequestError } = require('@octokit/request-error')
function octokitRestNormalizeGitReferenceResponses (octokit) {
octokit.hook.wrap('request', (request, options) => {
const isGetOrListRefRequest = /\/repos\/:?\w+\/:?\w+\/git\/refs\/:?\w+/.test(options.url)
if (!isGetOrListRefRequest) {
return request(options)
}
const isGetRefRequest = 'ref' in options
return request(options)
.then(response => {
// request single reference
if (isGetRefRequest) {
if (Array.isArray(response.data)) {
throw new RequestError(`More than one reference found for "${options.ref}"`, 404, {
request: options
})
}
// ✅ received single reference
return response
}
// request list of references
if (!Array.isArray(response.data)) {
response.data = [response.data]
}
return response
})
.catch(error => {
if (isGetRefRequest) {
throw error
}
if (error.status === 404) {
return {
status: 200,
headers: error.headers,
data: []
}
}
throw error
})
})
}

View File

@@ -1,9 +1,7 @@
module.exports = paginatePlugin
module.exports = paginatePlugin;
const iterator = require('./iterator')
const paginate = require('./paginate')
const { paginateRest } = require("@octokit/plugin-paginate-rest");
function paginatePlugin (octokit) {
octokit.paginate = paginate.bind(null, octokit)
octokit.paginate.iterator = iterator.bind(null, octokit)
function paginatePlugin(octokit) {
Object.assign(octokit, paginateRest(octokit));
}

View File

@@ -1,31 +0,0 @@
module.exports = iterator
const normalizePaginatedListResponse = require('./normalize-paginated-list-response')
function iterator (octokit, options) {
const headers = options.headers
let url = octokit.request.endpoint(options).url
return {
[Symbol.asyncIterator]: () => ({
next () {
if (!url) {
return Promise.resolve({ done: true })
}
return octokit.request({ url, headers })
.then((response) => {
normalizePaginatedListResponse(octokit, url, response)
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((response.headers.link || '').match(/<([^>]+)>;\s*rel="next"/) || [])[1]
return { value: response }
})
}
})
}
}

View File

@@ -1,91 +0,0 @@
/**
* Some “list” response that can be paginated have a different response structure
*
* They have a `total_count` key in the response (search also has `incomplete_results`,
* /installation/repositories also has `repository_selection`), as well as a key with
* the list of the items which name varies from endpoint to endpoint:
*
* - https://developer.github.com/v3/search/#example (key `items`)
* - https://developer.github.com/v3/checks/runs/#response-3 (key: `check_runs`)
* - https://developer.github.com/v3/checks/suites/#response-1 (key: `check_suites`)
* - https://developer.github.com/v3/apps/installations/#list-repositories (key: `repositories`)
* - https://developer.github.com/v3/apps/installations/#list-installations-for-a-user (key `installations`)
*
* Octokit normalizes these responses so that paginated results are always returned following
* the same structure. One challenge is that if the list response has only one page, no Link
* header is provided, so this header alone is not sufficient to check wether a response is
* paginated or not. For the exceptions with the namespace, a fallback check for the route
* paths has to be added in order to normalize the response. We cannot check for the total_count
* property because it also exists in the response of Get the combined status for a specific ref.
*/
module.exports = normalizePaginatedListResponse
const { Deprecation } = require('deprecation')
const once = require('once')
const deprecateIncompleteResults = once((log, deprecation) => log.warn(deprecation))
const deprecateTotalCount = once((log, deprecation) => log.warn(deprecation))
const deprecateNamespace = once((log, deprecation) => log.warn(deprecation))
const REGEX_IS_SEARCH_PATH = /^\/search\//
const REGEX_IS_CHECKS_PATH = /^\/repos\/[^/]+\/[^/]+\/commits\/[^/]+\/(check-runs|check-suites)/
const REGEX_IS_INSTALLATION_REPOSITORIES_PATH = /^\/installation\/repositories/
const REGEX_IS_USER_INSTALLATIONS_PATH = /^\/user\/installations/
function normalizePaginatedListResponse (octokit, url, response) {
const path = url.replace(octokit.request.endpoint.DEFAULTS.baseUrl, '')
if (
!REGEX_IS_SEARCH_PATH.test(path) &&
!REGEX_IS_CHECKS_PATH.test(path) &&
!REGEX_IS_INSTALLATION_REPOSITORIES_PATH.test(path) &&
!REGEX_IS_USER_INSTALLATIONS_PATH.test(path)
) {
return
}
// keep the additional properties intact to avoid a breaking change,
// but log a deprecation warning when accessed
const incompleteResults = response.data.incomplete_results
const repositorySelection = response.data.repository_selection
const totalCount = response.data.total_count
delete response.data.incomplete_results
delete response.data.repository_selection
delete response.data.total_count
const namespaceKey = Object.keys(response.data)[0]
response.data = response.data[namespaceKey]
Object.defineProperty(response.data, namespaceKey, {
get () {
deprecateNamespace(octokit.log, new Deprecation(`[@octokit/rest] "result.data.${namespaceKey}" is deprecated. Use "result.data" instead`))
return response.data
}
})
if (typeof incompleteResults !== 'undefined') {
Object.defineProperty(response.data, 'incomplete_results', {
get () {
deprecateIncompleteResults(octokit.log, new Deprecation('[@octokit/rest] "result.data.incomplete_results" is deprecated.'))
return incompleteResults
}
})
}
if (typeof repositorySelection !== 'undefined') {
Object.defineProperty(response.data, 'repository_selection', {
get () {
deprecateTotalCount(octokit.log, new Deprecation('[@octokit/rest] "result.data.repository_selection" is deprecated.'))
return repositorySelection
}
})
}
Object.defineProperty(response.data, 'total_count', {
get () {
deprecateTotalCount(octokit.log, new Deprecation('[@octokit/rest] "result.data.total_count" is deprecated.'))
return totalCount
}
})
}

View File

@@ -1,34 +0,0 @@
module.exports = paginate
const iterator = require('./iterator')
function paginate (octokit, route, options, mapFn) {
if (typeof options === 'function') {
mapFn = options
options = undefined
}
options = octokit.request.endpoint.merge(route, options)
return gather(octokit, [], iterator(octokit, options)[Symbol.asyncIterator](), mapFn)
}
function gather (octokit, results, iterator, mapFn) {
return iterator.next()
.then(result => {
if (result.done) {
return results
}
let earlyExit = false
function done () {
earlyExit = true
}
results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data)
if (earlyExit) {
return results
}
return gather(octokit, results, iterator, mapFn)
})
}

View File

@@ -1,7 +0,0 @@
module.exports = octokitRegisterEndpoints
const registerEndpoints = require('./register-endpoints')
function octokitRegisterEndpoints (octokit) {
octokit.registerEndpoints = registerEndpoints.bind(null, octokit)
}

View File

@@ -1,87 +0,0 @@
module.exports = registerEndpoints
const { Deprecation } = require('deprecation')
function registerEndpoints (octokit, routes) {
Object.keys(routes).forEach(namespaceName => {
if (!octokit[namespaceName]) {
octokit[namespaceName] = {}
}
Object.keys(routes[namespaceName]).forEach(apiName => {
const apiOptions = routes[namespaceName][apiName]
const endpointDefaults = ['method', 'url', 'headers'].reduce((map, key) => {
if (typeof apiOptions[key] !== 'undefined') {
map[key] = apiOptions[key]
}
return map
}, {})
endpointDefaults.request = {
validate: apiOptions.params
}
let request = octokit.request.defaults(endpointDefaults)
// patch request & endpoint methods to support deprecated parameters.
// Not the most elegant solution, but we dont want to move deprecation
// logic into octokit/endpoint.js as its out of scope
const hasDeprecatedParam = Object.keys(apiOptions.params || {}).find(key => apiOptions.params[key].deprecated)
if (hasDeprecatedParam) {
const patch = patchForDeprecation.bind(null, octokit, apiOptions)
request = patch(
octokit.request.defaults(endpointDefaults),
`.${namespaceName}.${apiName}()`
)
request.endpoint = patch(
request.endpoint,
`.${namespaceName}.${apiName}.endpoint()`
)
request.endpoint.merge = patch(
request.endpoint.merge,
`.${namespaceName}.${apiName}.endpoint.merge()`
)
}
if (apiOptions.deprecated) {
octokit[namespaceName][apiName] = function deprecatedEndpointMethod () {
octokit.log.warn(new Deprecation(`[@octokit/rest] ${apiOptions.deprecated}`))
octokit[namespaceName][apiName] = request
return request.apply(null, arguments)
}
return
}
octokit[namespaceName][apiName] = request
})
})
}
function patchForDeprecation (octokit, apiOptions, method, methodName) {
const patchedMethod = (options) => {
options = Object.assign({}, options)
Object.keys(options).forEach(key => {
if (apiOptions.params[key] && apiOptions.params[key].deprecated) {
const aliasKey = apiOptions.params[key].alias
octokit.log.warn(new Deprecation(`[@octokit/rest] "${key}" parameter is deprecated for "${methodName}". Use "${aliasKey}" instead`))
if (!(aliasKey in options)) {
options[aliasKey] = options[key]
}
delete options[key]
}
})
return method(options)
}
Object.keys(method).forEach(key => {
patchedMethod[key] = method[key]
})
return patchedMethod
}

View File

@@ -1,13 +0,0 @@
module.exports = octokitRestApiEndpoints
const ROUTES = require('./routes.json')
function octokitRestApiEndpoints (octokit) {
// Aliasing scopes for backward compatibility
// See https://github.com/octokit/rest.js/pull/1134
ROUTES.gitdata = ROUTES.git
ROUTES.authorization = ROUTES.oauthAuthorizations
ROUTES.pullRequests = ROUTES.pulls
octokit.registerEndpoints(ROUTES)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
module.exports = octokitValidate
module.exports = octokitValidate;
const validate = require('./validate')
const validate = require("./validate");
function octokitValidate (octokit) {
octokit.hook.before('request', validate.bind(null, octokit))
function octokitValidate(octokit) {
octokit.hook.before("request", validate.bind(null, octokit));
}

View File

@@ -1,113 +1,151 @@
'use strict'
"use strict";
module.exports = validate
module.exports = validate;
const { RequestError } = require('@octokit/request-error')
const get = require('lodash.get')
const set = require('lodash.set')
const { RequestError } = require("@octokit/request-error");
const get = require("lodash.get");
const set = require("lodash.set");
function validate (octokit, options) {
function validate(octokit, options) {
if (!options.request.validate) {
return
return;
}
const { validate: params } = options.request
const { validate: params } = options.request;
Object.keys(params).forEach(parameterName => {
const parameter = get(params, parameterName)
const parameter = get(params, parameterName);
const expectedType = parameter.type
let parentParameterName
let parentValue
let parentParamIsPresent = true
let parentParameterIsArray = false
const expectedType = parameter.type;
let parentParameterName;
let parentValue;
let parentParamIsPresent = true;
let parentParameterIsArray = false;
if (/\./.test(parameterName)) {
parentParameterName = parameterName.replace(/\.[^.]+$/, '')
parentParameterIsArray = parentParameterName.slice(-2) === '[]'
parentParameterName = parameterName.replace(/\.[^.]+$/, "");
parentParameterIsArray = parentParameterName.slice(-2) === "[]";
if (parentParameterIsArray) {
parentParameterName = parentParameterName.slice(0, -2)
parentParameterName = parentParameterName.slice(0, -2);
}
parentValue = get(options, parentParameterName)
parentParamIsPresent = parentParameterName === 'headers' || (typeof parentValue === 'object' && parentValue !== null)
parentValue = get(options, parentParameterName);
parentParamIsPresent =
parentParameterName === "headers" ||
(typeof parentValue === "object" && parentValue !== null);
}
const values = parentParameterIsArray
? (get(options, parentParameterName) || []).map(value => value[parameterName.split(/\./).pop()])
: [get(options, parameterName)]
? (get(options, parentParameterName) || []).map(
value => value[parameterName.split(/\./).pop()]
)
: [get(options, parameterName)];
values.forEach((value, i) => {
const valueIsPresent = typeof value !== 'undefined'
const valueIsNull = value === null
const valueIsPresent = typeof value !== "undefined";
const valueIsNull = value === null;
const currentParameterName = parentParameterIsArray
? parameterName.replace(/\[\]/, `[${i}]`)
: parameterName
: parameterName;
if (!parameter.required && !valueIsPresent) {
return
return;
}
// if the parent parameter is of type object but allows null
// then the child parameters can be ignored
if (!parentParamIsPresent) {
return
return;
}
if (parameter.allowNull && valueIsNull) {
return
return;
}
if (!parameter.allowNull && valueIsNull) {
throw new RequestError(`'${currentParameterName}' cannot be null`, 400, {
request: options
})
throw new RequestError(
`'${currentParameterName}' cannot be null`,
400,
{
request: options
}
);
}
if (parameter.required && !valueIsPresent) {
throw new RequestError(`Empty value for parameter '${currentParameterName}': ${JSON.stringify(value)}`, 400, {
request: options
})
throw new RequestError(
`Empty value for parameter '${currentParameterName}': ${JSON.stringify(
value
)}`,
400,
{
request: options
}
);
}
// parse to integer before checking for enum
// so that string "1" will match enum with number 1
if (expectedType === 'integer') {
const unparsedValue = value
value = parseInt(value, 10)
if (expectedType === "integer") {
const unparsedValue = value;
value = parseInt(value, 10);
if (isNaN(value)) {
throw new RequestError(`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(unparsedValue)} is NaN`, 400, {
request: options
})
throw new RequestError(
`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(
unparsedValue
)} is NaN`,
400,
{
request: options
}
);
}
}
if (parameter.enum && parameter.enum.indexOf(value) === -1) {
throw new RequestError(`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(value)}`, 400, {
request: options
})
if (parameter.enum && parameter.enum.indexOf(String(value)) === -1) {
throw new RequestError(
`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(
value
)}`,
400,
{
request: options
}
);
}
if (parameter.validation) {
const regex = new RegExp(parameter.validation)
const regex = new RegExp(parameter.validation);
if (!regex.test(value)) {
throw new RequestError(`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(value)}`, 400, {
request: options
})
throw new RequestError(
`Invalid value for parameter '${currentParameterName}': ${JSON.stringify(
value
)}`,
400,
{
request: options
}
);
}
}
if (expectedType === 'object' && typeof value === 'string') {
if (expectedType === "object" && typeof value === "string") {
try {
value = JSON.parse(value)
value = JSON.parse(value);
} catch (exception) {
throw new RequestError(`JSON parse error of value for parameter '${currentParameterName}': ${JSON.stringify(value)}`, 400, {
request: options
})
throw new RequestError(
`JSON parse error of value for parameter '${currentParameterName}': ${JSON.stringify(
value
)}`,
400,
{
request: options
}
);
}
}
set(options, parameter.mapTo || currentParameterName, value)
})
})
set(options, parameter.mapTo || currentParameterName, value);
});
});
return options
return options;
}