This commit is contained in:
eric sciple 2020-01-24 12:20:19 -05:00
parent beb1329f9f
commit 2b95e76931
7736 changed files with 1874747 additions and 51184 deletions

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 +1,28 @@
module.exports = octokitDebug
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, '')
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
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
})
})
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,9 @@
module.exports = paginatePlugin
module.exports = paginatePlugin;
const iterator = require('./iterator')
const paginate = require('./paginate')
const iterator = require("./iterator");
const paginate = require("./paginate");
function paginatePlugin (octokit) {
octokit.paginate = paginate.bind(null, octokit)
octokit.paginate.iterator = iterator.bind(null, octokit)
function paginatePlugin(octokit) {
octokit.paginate = paginate.bind(null, octokit);
octokit.paginate.iterator = iterator.bind(null, octokit);
}

View file

@ -1,31 +1,34 @@
module.exports = iterator
module.exports = iterator;
const normalizePaginatedListResponse = require('./normalize-paginated-list-response')
const normalizePaginatedListResponse = require("./normalize-paginated-list-response");
function iterator (octokit, options) {
const headers = options.headers
let url = octokit.request.endpoint(options).url
function iterator(octokit, options) {
const headers = options.headers;
let url = octokit.request.endpoint(options).url;
return {
[Symbol.asyncIterator]: () => ({
next () {
next() {
if (!url) {
return Promise.resolve({ done: true })
return Promise.resolve({ done: true });
}
return octokit.request({ url, headers })
return octokit
.request({ url, headers })
.then((response) => {
normalizePaginatedListResponse(octokit, url, response)
.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]
url = ((response.headers.link || "").match(
/<([^>]+)>;\s*rel="next"/
) || [])[1];
return { value: response }
})
return { value: response };
});
}
})
}
};
}

View file

@ -10,6 +10,7 @@
* - 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`)
* - https://developer.github.com/v3/orgs/#list-installations-for-an-organization (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
@ -19,73 +20,97 @@
* property because it also exists in the response of Get the combined status for a specific ref.
*/
module.exports = normalizePaginatedListResponse
module.exports = normalizePaginatedListResponse;
const { Deprecation } = require('deprecation')
const once = require('once')
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 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/
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/;
const REGEX_IS_ORG_INSTALLATIONS_PATH = /^\/orgs\/[^/]+\/installations/;
function normalizePaginatedListResponse (octokit, url, response) {
const path = url.replace(octokit.request.endpoint.DEFAULTS.baseUrl, '')
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)
!REGEX_IS_USER_INSTALLATIONS_PATH.test(path) &&
!REGEX_IS_ORG_INSTALLATIONS_PATH.test(path)
) {
return
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 incompleteResults = response.data.incomplete_results;
const repositorySelection = response.data.repository_selection;
const totalCount = response.data.total_count;
delete response.data.incomplete_results;
delete response.data.repository_selection;
delete response.data.total_count;
const namespaceKey = Object.keys(response.data)[0]
const namespaceKey = Object.keys(response.data)[0];
response.data = response.data[namespaceKey]
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
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 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
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
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 +1,40 @@
module.exports = paginate
module.exports = paginate;
const iterator = require('./iterator')
const iterator = require("./iterator");
function paginate (octokit, route, options, mapFn) {
if (typeof options === 'function') {
mapFn = options
options = undefined
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)
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
}
function gather(octokit, results, iterator, mapFn) {
return iterator.next().then(result => {
if (result.done) {
return results;
}
let earlyExit = false
function done () {
earlyExit = true
}
let earlyExit = false;
function done() {
earlyExit = true;
}
results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data)
results = results.concat(
mapFn ? mapFn(result.value, done) : result.value.data
);
if (earlyExit) {
return results
}
if (earlyExit) {
return results;
}
return gather(octokit, results, iterator, mapFn)
})
return gather(octokit, results, iterator, mapFn);
});
}

View file

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

View file

@ -1,87 +1,98 @@
module.exports = registerEndpoints
module.exports = registerEndpoints;
const { Deprecation } = require('deprecation')
const { Deprecation } = require("deprecation");
function registerEndpoints (octokit, routes) {
function registerEndpoints(octokit, routes) {
Object.keys(routes).forEach(namespaceName => {
if (!octokit[namespaceName]) {
octokit[namespaceName] = {}
octokit[namespaceName] = {};
}
Object.keys(routes[namespaceName]).forEach(apiName => {
const apiOptions = routes[namespaceName][apiName]
const apiOptions = routes[namespaceName][apiName];
const endpointDefaults = ['method', 'url', 'headers'].reduce((map, key) => {
if (typeof apiOptions[key] !== 'undefined') {
map[key] = apiOptions[key]
}
const endpointDefaults = ["method", "url", "headers"].reduce(
(map, key) => {
if (typeof apiOptions[key] !== "undefined") {
map[key] = apiOptions[key];
}
return map
}, {})
return map;
},
{}
);
endpointDefaults.request = {
validate: apiOptions.params
}
};
let request = octokit.request.defaults(endpointDefaults)
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)
const hasDeprecatedParam = Object.keys(apiOptions.params || {}).find(
key => apiOptions.params[key].deprecated
);
if (hasDeprecatedParam) {
const patch = patchForDeprecation.bind(null, octokit, apiOptions)
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)
}
octokit[namespaceName][apiName] = function deprecatedEndpointMethod() {
octokit.log.warn(
new Deprecation(`[@octokit/rest] ${apiOptions.deprecated}`)
);
octokit[namespaceName][apiName] = request;
return request.apply(null, arguments);
};
return
return;
}
octokit[namespaceName][apiName] = request
})
})
octokit[namespaceName][apiName] = request;
});
});
}
function patchForDeprecation (octokit, apiOptions, method, methodName) {
const patchedMethod = (options) => {
options = Object.assign({}, options)
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
const aliasKey = apiOptions.params[key].alias;
octokit.log.warn(new Deprecation(`[@octokit/rest] "${key}" parameter is deprecated for "${methodName}". Use "${aliasKey}" instead`))
octokit.log.warn(
new Deprecation(
`[@octokit/rest] "${key}" parameter is deprecated for "${methodName}". Use "${aliasKey}" instead`
)
);
if (!(aliasKey in options)) {
options[aliasKey] = options[key]
options[aliasKey] = options[key];
}
delete options[key]
delete options[key];
}
})
});
return method(options)
}
return method(options);
};
Object.keys(method).forEach(key => {
patchedMethod[key] = method[key]
})
patchedMethod[key] = method[key];
});
return patchedMethod
return patchedMethod;
}

View file

@ -1,13 +1,13 @@
module.exports = octokitRestApiEndpoints
module.exports = octokitRestApiEndpoints;
const ROUTES = require('./routes.json')
const ROUTES = require("./routes.json");
function octokitRestApiEndpoints (octokit) {
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
ROUTES.gitdata = ROUTES.git;
ROUTES.authorization = ROUTES.oauthAuthorizations;
ROUTES.pullRequests = ROUTES.pulls;
octokit.registerEndpoints(ROUTES)
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;
}