Compare commits
2 Commits
server-202
...
gh-package
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da42e109fb | ||
|
|
448d63b3cb |
@@ -4,6 +4,12 @@ main_steps: &main_steps
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
@@ -12,6 +18,11 @@ main_steps: &main_steps
|
||||
# We don't need to install the Cypress binary in jobs that aren't actually running Cypress.
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
|
||||
- save_cache:
|
||||
paths:
|
||||
- node_modules
|
||||
key: v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
|
||||
- run:
|
||||
name: Linter
|
||||
when: always
|
||||
@@ -45,6 +56,12 @@ integration_steps: &integration_steps
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
@@ -66,6 +83,12 @@ services_steps: &services_steps
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
@@ -86,12 +109,30 @@ services_steps: &services_steps
|
||||
- store_test_results:
|
||||
path: junit
|
||||
|
||||
run_package_tests: &run_package_tests
|
||||
when: always
|
||||
command: |
|
||||
# https://discuss.circleci.com/t/switch-nodejs-version-on-machine-executor-solved/26675/3
|
||||
set +e
|
||||
export NVM_DIR="/opt/circleci/.nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
|
||||
nvm install $NODE_VERSION
|
||||
nvm use $NODE_VERSION
|
||||
node --version
|
||||
npm run test:package
|
||||
|
||||
package_steps: &package_steps
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install node and npm
|
||||
name: Install dependencies
|
||||
command: |
|
||||
set +e
|
||||
export NVM_DIR="/opt/circleci/.nvm"
|
||||
@@ -99,74 +140,102 @@ package_steps: &package_steps
|
||||
nvm install v12
|
||||
nvm use v12
|
||||
npm install -g npm
|
||||
npm ci
|
||||
environment:
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
|
||||
# Run the package tests on each currently supported node version. See:
|
||||
# https://github.com/badges/shields/blob/master/badge-maker/README.md#node-version-support
|
||||
# https://nodejs.org/en/about/releases/
|
||||
# https://github.com/badges/shields/blob/master/gh-badges/README.md#node-version-support
|
||||
|
||||
- run:
|
||||
<<: *run_package_tests
|
||||
environment:
|
||||
mocha_reporter: mocha-junit-reporter
|
||||
MOCHA_FILE: junit/badge-maker/v10/results.xml
|
||||
MOCHA_FILE: junit/gh-badges/v8/results.xml
|
||||
NODE_VERSION: v8
|
||||
name: Run package tests on Node 8
|
||||
|
||||
- run:
|
||||
<<: *run_package_tests
|
||||
environment:
|
||||
mocha_reporter: mocha-junit-reporter
|
||||
MOCHA_FILE: junit/gh-badges/v10/results.xml
|
||||
NODE_VERSION: v10
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
name: Run package tests on Node 10
|
||||
command: scripts/run_package_tests.sh
|
||||
|
||||
- run:
|
||||
<<: *run_package_tests
|
||||
environment:
|
||||
mocha_reporter: mocha-junit-reporter
|
||||
MOCHA_FILE: junit/badge-maker/v12/results.xml
|
||||
MOCHA_FILE: junit/gh-badges/v12/results.xml
|
||||
NODE_VERSION: v12
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
name: Run package tests on Node 12
|
||||
command: scripts/run_package_tests.sh
|
||||
|
||||
- run:
|
||||
environment:
|
||||
mocha_reporter: mocha-junit-reporter
|
||||
MOCHA_FILE: junit/badge-maker/v14/results.xml
|
||||
NODE_VERSION: v14
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
name: Run package tests on Node 14
|
||||
command: scripts/run_package_tests.sh
|
||||
|
||||
- store_test_results:
|
||||
path: junit
|
||||
|
||||
jobs:
|
||||
npm-install:
|
||||
docker:
|
||||
- image: circleci/node:8
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# fallback to using the latest cache if no exact match is found
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
environment:
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
|
||||
- save_cache:
|
||||
paths:
|
||||
- node_modules
|
||||
key: v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
|
||||
main:
|
||||
docker:
|
||||
- image: circleci/node:12
|
||||
- image: circleci/node:8
|
||||
|
||||
<<: *main_steps
|
||||
|
||||
main@node-14:
|
||||
main@node-latest:
|
||||
docker:
|
||||
- image: circleci/node:14
|
||||
- image: circleci/node:latest
|
||||
|
||||
<<: *main_steps
|
||||
|
||||
integration:
|
||||
docker:
|
||||
- image: circleci/node:12
|
||||
- image: circleci/node:8
|
||||
- image: redis
|
||||
|
||||
<<: *integration_steps
|
||||
|
||||
integration@node-14:
|
||||
integration@node-latest:
|
||||
docker:
|
||||
- image: circleci/node:14
|
||||
- image: circleci/node:latest
|
||||
- image: redis
|
||||
|
||||
<<: *integration_steps
|
||||
|
||||
danger:
|
||||
docker:
|
||||
- image: circleci/node:12
|
||||
- image: circleci/node:8
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
@@ -183,10 +252,16 @@ jobs:
|
||||
|
||||
frontend:
|
||||
docker:
|
||||
- image: circleci/node:12
|
||||
- image: circleci/node:8
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- run:
|
||||
name: Install dependencies
|
||||
command: npm ci
|
||||
@@ -224,22 +299,29 @@ jobs:
|
||||
|
||||
services:
|
||||
docker:
|
||||
- image: circleci/node:12
|
||||
- image: circleci/node:8
|
||||
|
||||
<<: *services_steps
|
||||
|
||||
services@node-14:
|
||||
services@node-latest:
|
||||
docker:
|
||||
- image: circleci/node:14
|
||||
- image: circleci/node:latest
|
||||
|
||||
<<: *services_steps
|
||||
|
||||
e2e:
|
||||
docker:
|
||||
- image: cypress/base:12
|
||||
- image: cypress/base:8
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- restore_cache:
|
||||
name: Restore node_modules
|
||||
keys:
|
||||
- v2-dependencies-{{ checksum "package-lock.json" }}
|
||||
# https://github.com/badges/shields/issues/1937
|
||||
- v2-dependencies-
|
||||
|
||||
- restore_cache:
|
||||
name: Restore Cypress binary
|
||||
keys:
|
||||
@@ -285,11 +367,11 @@ workflows:
|
||||
filters:
|
||||
branches:
|
||||
ignore: gh-pages
|
||||
- main@node-14:
|
||||
- main@node-latest:
|
||||
filters:
|
||||
branches:
|
||||
ignore: gh-pages
|
||||
- integration@node-14:
|
||||
- integration@node-latest:
|
||||
filters:
|
||||
branches:
|
||||
ignore: gh-pages
|
||||
@@ -307,7 +389,7 @@ workflows:
|
||||
ignore:
|
||||
- master
|
||||
- gh-pages
|
||||
- services@node-14:
|
||||
- services@node-latest:
|
||||
filters:
|
||||
branches:
|
||||
ignore:
|
||||
|
||||
@@ -4,35 +4,8 @@ update_configs:
|
||||
- package_manager: 'javascript'
|
||||
directory: '/'
|
||||
update_schedule: 'weekly'
|
||||
automerged_updates:
|
||||
- match:
|
||||
dependency_name: 'chai*'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'cypress'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'eslint*'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'mocha*'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'sazerac'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'sinon*'
|
||||
update_type: 'semver:minor'
|
||||
- match:
|
||||
dependency_name: 'snap-shot-it'
|
||||
update_type: 'semver:minor'
|
||||
|
||||
# badge-maker package dependencies
|
||||
# gh-badges package dependencies
|
||||
- package_manager: 'javascript'
|
||||
directory: '/badge-maker'
|
||||
update_schedule: 'weekly'
|
||||
|
||||
# approve-bot package dependencies
|
||||
- package_manager: 'javascript'
|
||||
directory: '.github/actions/approve-bot'
|
||||
directory: '/gh-badges'
|
||||
update_schedule: 'weekly'
|
||||
|
||||
@@ -3,5 +3,4 @@
|
||||
/coverage
|
||||
/__snapshots__
|
||||
/public
|
||||
badge-maker/node_modules/
|
||||
!.github/
|
||||
gh-badges/node_modules/
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
extends:
|
||||
- standard
|
||||
- standard-jsx
|
||||
- standard-react
|
||||
- plugin:@typescript-eslint/recommended
|
||||
- prettier
|
||||
- prettier/@typescript-eslint
|
||||
- prettier/standard
|
||||
- prettier/react
|
||||
@@ -17,8 +15,6 @@ parserOptions:
|
||||
settings:
|
||||
react:
|
||||
version: '16.8'
|
||||
jsdoc:
|
||||
mode: jsdoc
|
||||
|
||||
plugins:
|
||||
- chai-friendly
|
||||
@@ -43,6 +39,7 @@ overrides:
|
||||
es6: true
|
||||
rules:
|
||||
no-console: 'off'
|
||||
'@typescript-eslint/no-var-requires': off
|
||||
|
||||
- files:
|
||||
- '**/*.@(ts|tsx)'
|
||||
@@ -51,13 +48,8 @@ overrides:
|
||||
parser: '@typescript-eslint/parser'
|
||||
rules:
|
||||
# Argh.
|
||||
'@typescript-eslint/explicit-function-return-type':
|
||||
['error', { 'allowExpressions': true }]
|
||||
'@typescript-eslint/no-empty-function': 'error'
|
||||
'@typescript-eslint/no-var-requires': 'error'
|
||||
'@typescript-eslint/explicit-function-return-type': 'off'
|
||||
'@typescript-eslint/no-object-literal-type-assertion': 'off'
|
||||
'@typescript-eslint/no-explicit-any': 'error'
|
||||
'@typescript-eslint/ban-ts-ignore': 'off'
|
||||
|
||||
- files:
|
||||
- core/**/*.ts
|
||||
@@ -121,9 +113,9 @@ rules:
|
||||
# Allow unused parameters. In callbacks, removing them seems to obscure
|
||||
# what the functions are doing.
|
||||
'@typescript-eslint/no-unused-vars': ['error', { 'args': 'none' }]
|
||||
no-unused-vars: 'off'
|
||||
no-unused-vars: off
|
||||
|
||||
'@typescript-eslint/no-var-requires': 'off'
|
||||
'@typescript-eslint/no-var-requires': error
|
||||
|
||||
# These should be disabled by eslint-config-prettier, but are not.
|
||||
no-extra-semi: 'off'
|
||||
@@ -152,7 +144,7 @@ rules:
|
||||
# allow Joi as an undefined type
|
||||
jsdoc/no-undefined-types: ['error', { definedTypes: ['Joi'] }]
|
||||
|
||||
# all the other recommended rules as errors (not warnings)
|
||||
# all the other reccomended rules as errors (not warnings)
|
||||
jsdoc/check-alignment: 'error'
|
||||
jsdoc/check-param-names: 'error'
|
||||
jsdoc/check-tag-names: 'error'
|
||||
@@ -171,8 +163,6 @@ rules:
|
||||
|
||||
# Disable some from TypeScript.
|
||||
'@typescript-eslint/camelcase': off
|
||||
'@typescript-eslint/explicit-function-return-type': 'off'
|
||||
'@typescript-eslint/no-empty-function': 'off'
|
||||
|
||||
react/jsx-sort-props: 'error'
|
||||
react-hooks/rules-of-hooks: 'error'
|
||||
|
||||
2
.github/ISSUE_TEMPLATE/1_Bug_report.md
vendored
2
.github/ISSUE_TEMPLATE/1_Bug_report.md
vendored
@@ -8,7 +8,7 @@ Are you experiencing an issue with...
|
||||
|
||||
- [ ] [shields.io](https://shields.io/#/)
|
||||
- [ ] My own instance
|
||||
- [ ] [badge-maker NPM package](https://www.npmjs.com/package/badge-maker)
|
||||
- [ ] [gh-badges NPM package](https://www.npmjs.com/package/gh-badges)
|
||||
|
||||
:beetle: **Description**
|
||||
|
||||
|
||||
17
.github/ISSUE_TEMPLATE/5_Support_question.md
vendored
Normal file
17
.github/ISSUE_TEMPLATE/5_Support_question.md
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: ❓ Support Question
|
||||
about: Ask a question about shields.io
|
||||
labels: 'question'
|
||||
---
|
||||
|
||||
:question: **Question**
|
||||
|
||||
<!--
|
||||
Ask your question clearly and concisely.
|
||||
|
||||
#support on our [Discord](https://discordapp.com/invite/HjJCwm5)
|
||||
is also a great place to ask questions and get help
|
||||
-->
|
||||
|
||||
<!-- Love Shields? Please consider donating $10 to sustain our activities:
|
||||
👉 https://opencollective.com/shields -->
|
||||
7
.github/ISSUE_TEMPLATE/config.yml
vendored
7
.github/ISSUE_TEMPLATE/config.yml
vendored
@@ -1,7 +0,0 @@
|
||||
contact_links:
|
||||
- name: 🎨 Simple Icons
|
||||
url: https://github.com/badges/shields/discussions/5369
|
||||
about: Please read this before posting a question about SimpleIcons
|
||||
- name: ❓ Support Question
|
||||
url: https://github.com/badges/shields/discussions
|
||||
about: Ask a question about Shields.io
|
||||
12
.github/actions/approve-bot/action.yml
vendored
12
.github/actions/approve-bot/action.yml
vendored
@@ -1,12 +0,0 @@
|
||||
name: 'Auto Approve'
|
||||
description: 'Automatically approve/close selected pull requests for shields.io'
|
||||
branding:
|
||||
icon: 'check-circle'
|
||||
color: 'green'
|
||||
inputs:
|
||||
github-token:
|
||||
description: 'The GITHUB_TOKEN secret'
|
||||
required: true
|
||||
runs:
|
||||
using: 'node12'
|
||||
main: 'index.js'
|
||||
65
.github/actions/approve-bot/helpers.js
vendored
65
.github/actions/approve-bot/helpers.js
vendored
@@ -1,65 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
function findChangelogStart(lines) {
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
if (
|
||||
line === '<summary>Changelog</summary>' &&
|
||||
lines[i + 2] === '<blockquote>'
|
||||
) {
|
||||
return i + 3
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function findChangelogEnd(lines, start) {
|
||||
for (let i = start; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
if (line === '</blockquote>') {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function allChangelogLinesAreVersionBump(changelogLines) {
|
||||
return (
|
||||
changelogLines.length > 0 &&
|
||||
changelogLines.length ===
|
||||
changelogLines.filter(line =>
|
||||
line.includes('Version bump only for package')
|
||||
).length
|
||||
)
|
||||
}
|
||||
|
||||
function isPointlessGatsbyBump(body) {
|
||||
const lines = body.split(/\r?\n/)
|
||||
if (
|
||||
!lines[0].includes('https://github.com/gatsbyjs/gatsby') // lgtm [js/incomplete-url-substring-sanitization]
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const start = findChangelogStart(lines)
|
||||
const end = findChangelogEnd(lines, start)
|
||||
if (!start || !end) {
|
||||
return false
|
||||
}
|
||||
const changelogLines = lines
|
||||
.slice(start, end)
|
||||
.filter(line => !line.startsWith('<h'))
|
||||
.filter(line => !line.startsWith('<p>All notable changes'))
|
||||
.filter(
|
||||
line => !line.startsWith('See <a href="https://conventionalcommits.org">')
|
||||
)
|
||||
.filter(line => !line.startsWith('<!--'))
|
||||
return allChangelogLinesAreVersionBump(changelogLines)
|
||||
}
|
||||
|
||||
function shouldAutoMerge(body) {
|
||||
return body.includes(
|
||||
'If all status checks pass Dependabot will automatically merge this pull request'
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = { isPointlessGatsbyBump, shouldAutoMerge }
|
||||
56
.github/actions/approve-bot/index.js
vendored
56
.github/actions/approve-bot/index.js
vendored
@@ -1,56 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const core = require('@actions/core')
|
||||
const github = require('@actions/github')
|
||||
const { isPointlessGatsbyBump, shouldAutoMerge } = require('./helpers')
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
const token = core.getInput('github-token', { required: true })
|
||||
|
||||
const { pull_request: pr } = github.context.payload
|
||||
if (!pr) {
|
||||
throw new Error('Event payload missing `pull_request`')
|
||||
}
|
||||
|
||||
const client = github.getOctokit(token)
|
||||
|
||||
if (
|
||||
['dependabot[bot]', 'dependabot-preview[bot]'].includes(pr.user.login)
|
||||
) {
|
||||
if (isPointlessGatsbyBump(pr.body)) {
|
||||
core.debug(`Closing pull request #${pr.number}`)
|
||||
await client.pulls.update({
|
||||
owner: github.context.repo.owner,
|
||||
repo: github.context.repo.repo,
|
||||
pull_number: pr.number,
|
||||
state: 'closed',
|
||||
})
|
||||
|
||||
core.debug(`Done.`)
|
||||
} else if (shouldAutoMerge(pr.body)) {
|
||||
core.debug(`Adding label to pull request #${pr.number}`)
|
||||
await client.issues.addLabels({
|
||||
owner: github.context.repo.owner,
|
||||
repo: github.context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: ['squash when passing'],
|
||||
})
|
||||
|
||||
core.debug(`Creating approving review for pull request #${pr.number}`)
|
||||
await client.pulls.createReview({
|
||||
owner: github.context.repo.owner,
|
||||
repo: github.context.repo.repo,
|
||||
pull_number: pr.number,
|
||||
event: 'APPROVE',
|
||||
})
|
||||
|
||||
core.debug(`Done.`)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
core.setFailed(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
run()
|
||||
177
.github/actions/approve-bot/package-lock.json
generated
vendored
177
.github/actions/approve-bot/package-lock.json
generated
vendored
@@ -1,177 +0,0 @@
|
||||
{
|
||||
"name": "approve-bot",
|
||||
"version": "0.0.0",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
"@actions/core": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz",
|
||||
"integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA=="
|
||||
},
|
||||
"@actions/github": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@actions/github/-/github-4.0.0.tgz",
|
||||
"integrity": "sha512-Ej/Y2E+VV6sR9X7pWL5F3VgEWrABaT292DRqRU6R4hnQjPtC/zD3nagxVdXWiRQvYDh8kHXo7IDmG42eJ/dOMA==",
|
||||
"requires": {
|
||||
"@actions/http-client": "^1.0.8",
|
||||
"@octokit/core": "^3.0.0",
|
||||
"@octokit/plugin-paginate-rest": "^2.2.3",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"@actions/http-client": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.9.tgz",
|
||||
"integrity": "sha512-0O4SsJ7q+MK0ycvXPl2e6bMXV7dxAXOGjrXS1eTF9s2S401Tp6c/P3c3Joz04QefC1J6Gt942Wl2jbm3f4mLcg==",
|
||||
"requires": {
|
||||
"tunnel": "0.0.6"
|
||||
}
|
||||
},
|
||||
"@octokit/auth-token": {
|
||||
"version": "2.4.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz",
|
||||
"integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==",
|
||||
"requires": {
|
||||
"@octokit/types": "^6.0.3"
|
||||
}
|
||||
},
|
||||
"@octokit/core": {
|
||||
"version": "3.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.2.5.tgz",
|
||||
"integrity": "sha512-+DCtPykGnvXKWWQI0E1XD+CCeWSBhB6kwItXqfFmNBlIlhczuDPbg+P6BtLnVBaRJDAjv+1mrUJuRsFSjktopg==",
|
||||
"requires": {
|
||||
"@octokit/auth-token": "^2.4.4",
|
||||
"@octokit/graphql": "^4.5.8",
|
||||
"@octokit/request": "^5.4.12",
|
||||
"@octokit/types": "^6.0.3",
|
||||
"before-after-hook": "^2.1.0",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"@octokit/endpoint": {
|
||||
"version": "6.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.11.tgz",
|
||||
"integrity": "sha512-fUIPpx+pZyoLW4GCs3yMnlj2LfoXTWDUVPTC4V3MUEKZm48W+XYpeWSZCv+vYF1ZABUm2CqnDVf1sFtIYrj7KQ==",
|
||||
"requires": {
|
||||
"@octokit/types": "^6.0.3",
|
||||
"is-plain-object": "^5.0.0",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"@octokit/graphql": {
|
||||
"version": "4.5.9",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.9.tgz",
|
||||
"integrity": "sha512-c+0yofIugUNqo+ktrLaBlWSbjSq/UF8ChAyxQzbD3X74k1vAuyLKdDJmPwVExUFSp6+U1FzWe+3OkeRsIqV0vg==",
|
||||
"requires": {
|
||||
"@octokit/request": "^5.3.0",
|
||||
"@octokit/types": "^6.0.3",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"@octokit/openapi-types": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-3.3.0.tgz",
|
||||
"integrity": "sha512-s3dd32gagPmKaSLNJ9aPNok7U+tl69YLESf6DgQz5Ml/iipPZtif3GLvWpNXoA6qspFm1LFUZX+C3SqWX/Y/TQ=="
|
||||
},
|
||||
"@octokit/plugin-paginate-rest": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.9.0.tgz",
|
||||
"integrity": "sha512-XxbOg45r2n/2QpU6hnGDxQNDRrJ7gjYpMXeDbUCigWTHECmjoyFLizkFO2jMEtidMkfiELn7AF8GBAJ/cbPTnA==",
|
||||
"requires": {
|
||||
"@octokit/types": "^6.6.0"
|
||||
}
|
||||
},
|
||||
"@octokit/plugin-rest-endpoint-methods": {
|
||||
"version": "4.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.9.0.tgz",
|
||||
"integrity": "sha512-EAr2epvY8JfXSi/cdMsyyfBctdKkolDH7xSgu3MKBqPRm0WfQ2QvI050jz61XZXoVK3ZgrhdMCyd1GgOFz7CSw==",
|
||||
"requires": {
|
||||
"@octokit/types": "^6.6.0",
|
||||
"deprecation": "^2.3.1"
|
||||
}
|
||||
},
|
||||
"@octokit/request": {
|
||||
"version": "5.4.13",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.13.tgz",
|
||||
"integrity": "sha512-WcNRH5XPPtg7i1g9Da5U9dvZ6YbTffw9BN2rVezYiE7couoSyaRsw0e+Tl8uk1fArHE7Dn14U7YqUDy59WaqEw==",
|
||||
"requires": {
|
||||
"@octokit/endpoint": "^6.0.1",
|
||||
"@octokit/request-error": "^2.0.0",
|
||||
"@octokit/types": "^6.0.3",
|
||||
"deprecation": "^2.0.0",
|
||||
"is-plain-object": "^5.0.0",
|
||||
"node-fetch": "^2.6.1",
|
||||
"once": "^1.4.0",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"@octokit/request-error": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.5.tgz",
|
||||
"integrity": "sha512-T/2wcCFyM7SkXzNoyVNWjyVlUwBvW3igM3Btr/eKYiPmucXTtkxt2RBsf6gn3LTzaLSLTQtNmvg+dGsOxQrjZg==",
|
||||
"requires": {
|
||||
"@octokit/types": "^6.0.3",
|
||||
"deprecation": "^2.0.0",
|
||||
"once": "^1.4.0"
|
||||
}
|
||||
},
|
||||
"@octokit/types": {
|
||||
"version": "6.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.6.0.tgz",
|
||||
"integrity": "sha512-nmFoU3HCbw1AmnZU/eto2VvzV06+N7oAqXwMmAHGlNDF+KFykksh/VlAl85xc1P5T7Mw8fKYvXNaImNHCCH/rg==",
|
||||
"requires": {
|
||||
"@octokit/openapi-types": "^3.3.0",
|
||||
"@types/node": ">= 8"
|
||||
}
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "14.14.22",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.22.tgz",
|
||||
"integrity": "sha512-g+f/qj/cNcqKkc3tFqlXOYjrmZA+jNBiDzbP3kH+B+otKFqAdPgVTGP1IeKRdMml/aE69as5S4FqtxAbl+LaMw=="
|
||||
},
|
||||
"before-after-hook": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz",
|
||||
"integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A=="
|
||||
},
|
||||
"deprecation": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
|
||||
"integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
|
||||
},
|
||||
"is-plain-object": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
|
||||
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q=="
|
||||
},
|
||||
"node-fetch": {
|
||||
"version": "2.6.1",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
|
||||
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw=="
|
||||
},
|
||||
"once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
|
||||
"requires": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"tunnel": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz",
|
||||
"integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg=="
|
||||
},
|
||||
"universal-user-agent": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz",
|
||||
"integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w=="
|
||||
},
|
||||
"wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
|
||||
}
|
||||
}
|
||||
}
|
||||
16
.github/actions/approve-bot/package.json
vendored
16
.github/actions/approve-bot/package.json
vendored
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"name": "approve-bot",
|
||||
"version": "0.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "chris48s",
|
||||
"license": "CC0",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.2.6",
|
||||
"@actions/github": "^4.0.0"
|
||||
}
|
||||
}
|
||||
8
.github/actions/draft-release/Dockerfile
vendored
8
.github/actions/draft-release/Dockerfile
vendored
@@ -1,8 +0,0 @@
|
||||
FROM node:12-buster
|
||||
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y jq
|
||||
RUN apt-get install -y uuid-runtime
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
5
.github/actions/draft-release/action.yml
vendored
5
.github/actions/draft-release/action.yml
vendored
@@ -1,5 +0,0 @@
|
||||
name: 'draft-release'
|
||||
description: 'Generate a changelog and propose a release PR'
|
||||
runs:
|
||||
using: 'docker'
|
||||
image: 'Dockerfile'
|
||||
60
.github/actions/draft-release/entrypoint.sh
vendored
60
.github/actions/draft-release/entrypoint.sh
vendored
@@ -1,60 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
# Set up a git user
|
||||
git config user.name "release[bot]"
|
||||
git config user.email "actions@users.noreply.github.com"
|
||||
|
||||
# Find last server-YYYY-MM-DD tag
|
||||
git fetch --unshallow --tags
|
||||
LAST_TAG=$(git tag | grep server | tail -n 1)
|
||||
|
||||
# Find the marker in CHANGELOG.md
|
||||
INSERT_POINT=$(grep -n "^\-\-\-$" CHANGELOG.md | cut -f1 -d:)
|
||||
INSERT_POINT=$((INSERT_POINT+1))
|
||||
|
||||
# Generate a release name
|
||||
RELEASE_NAME="server-$(date --rfc-3339=date)"
|
||||
|
||||
# Assemble changelog entry
|
||||
rm -f temp-changes.txt
|
||||
touch temp-changes.txt
|
||||
{
|
||||
echo "## $RELEASE_NAME"
|
||||
echo ""
|
||||
git log "$LAST_TAG"..HEAD --no-merges --oneline --pretty="format:- %s" --perl-regexp --author='^((?!dependabot).*)$'
|
||||
echo $'\n'
|
||||
} >> temp-changes.txt
|
||||
|
||||
# Write the changelog
|
||||
sed -i "${INSERT_POINT} r temp-changes.txt" CHANGELOG.md
|
||||
|
||||
# Cleanup
|
||||
rm temp-changes.txt
|
||||
|
||||
# Run prettier (to ensure the markdown file doesn't fail CI)
|
||||
npx prettier@$(cat package.json | jq -r .devDependencies.prettier) --write "CHANGELOG.md"
|
||||
|
||||
# Generate a unique branch name
|
||||
BRANCH_NAME="$RELEASE_NAME"-$(uuidgen | head -c 8)
|
||||
git checkout -b "$BRANCH_NAME"
|
||||
|
||||
# Commit + push changelog
|
||||
git add CHANGELOG.md
|
||||
git commit -m "Update Changelog"
|
||||
git push origin "$BRANCH_NAME"
|
||||
|
||||
# Submit a PR
|
||||
TITLE="Changelog for Release $RELEASE_NAME"
|
||||
PR_RESP=$(curl https://api.github.com/repos/"$REPO_NAME"/pulls \
|
||||
-X POST \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
--data '{"title": "'"$TITLE"'", "body": "'"$TITLE"'", "head": "'"$BRANCH_NAME"'", "base": "master"}')
|
||||
|
||||
# Add the 'release' label to the PR
|
||||
PR_API_URL=$(echo "$PR_RESP" | jq -r ._links.issue.href)
|
||||
curl "$PR_API_URL" \
|
||||
-X POST \
|
||||
-H "Authorization: token $GITHUB_TOKEN" \
|
||||
--data '{"labels":["release"]}'
|
||||
10
.github/probot.js
vendored
Normal file
10
.github/probot.js
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
on('pull_request.closed')
|
||||
.filter(context => context.payload.pull_request.merged)
|
||||
.filter(
|
||||
context =>
|
||||
context.payload.pull_request.head.ref.slice(0, 11) !== 'dependabot/'
|
||||
)
|
||||
.filter(context => context.payload.pull_request.base.ref === 'master')
|
||||
.comment(`This pull request was merged to [{{ pull_request.base.ref }}]({{ repository.html_url }}/tree/{{ pull_request.base.ref }}) branch. This change is now waiting for deployment, which will usually happen within a few days. Stay tuned by joining our \`#ops\` channel on [Discord](https://discordapp.com/invite/HjJCwm5)!
|
||||
|
||||
After deployment, changes are copied to [gh-pages]({{ repository.html_url }}/tree/gh-pages) branch: `)
|
||||
16
.github/workflows/auto-approve.yml
vendored
16
.github/workflows/auto-approve.yml
vendored
@@ -1,16 +0,0 @@
|
||||
name: Auto approve
|
||||
on: pull_request
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install action dependencies
|
||||
run: cd .github/actions/approve-bot && npm ci
|
||||
|
||||
- uses: ./.github/actions/approve-bot
|
||||
with:
|
||||
github-token: '${{ secrets.GITHUB_TOKEN }}'
|
||||
26
.github/workflows/deploy-docs.yml
vendored
26
.github/workflows/deploy-docs.yml
vendored
@@ -1,26 +0,0 @@
|
||||
name: Deploy Documentation
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
npm ci
|
||||
npm run build-docs
|
||||
|
||||
- name: Deploy
|
||||
uses: JamesIves/github-pages-deploy-action@3.7.1
|
||||
with:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
BRANCH: gh-pages
|
||||
FOLDER: api-docs
|
||||
CLEAN: true
|
||||
19
.github/workflows/draft-release.yml
vendored
19
.github/workflows/draft-release.yml
vendored
@@ -1,19 +0,0 @@
|
||||
name: Draft Release
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 1 1 * *'
|
||||
# At 01:00 on the first day of every month
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Draft Release
|
||||
uses: ./.github/actions/draft-release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO_NAME: ${{ github.repository }}
|
||||
31
.github/workflows/tag-release.yml
vendored
31
.github/workflows/tag-release.yml
vendored
@@ -1,31 +0,0 @@
|
||||
name: Tag Release
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [closed]
|
||||
|
||||
jobs:
|
||||
tag-release:
|
||||
if: |
|
||||
github.event_name == 'pull_request' &&
|
||||
github.event.action == 'closed' &&
|
||||
github.event.pull_request.merged == true &&
|
||||
contains(github.event.pull_request.labels.*.name, 'release')
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Get current date
|
||||
id: date
|
||||
run: echo "::set-output name=date::$(date --rfc-3339=date)"
|
||||
|
||||
- name: Checkout branch "master"
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
ref: 'master'
|
||||
|
||||
- name: Tag Release
|
||||
uses: tvdias/github-tagger@v0.0.2
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: server-${{ steps.date.outputs.date }}
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -7,7 +7,7 @@
|
||||
/private
|
||||
/index.html
|
||||
/shields.env
|
||||
badge-maker/package-lock.json
|
||||
gh-badges/package-lock.json
|
||||
|
||||
# Folder view configuration files
|
||||
.DS_Store
|
||||
@@ -113,6 +113,3 @@ service-definitions.yml
|
||||
|
||||
# Rendered API docs
|
||||
/api-docs/
|
||||
|
||||
# Flamebearer
|
||||
flamegraph.html
|
||||
|
||||
30
.nowignore
Normal file
30
.nowignore
Normal file
@@ -0,0 +1,30 @@
|
||||
*
|
||||
!frontend/
|
||||
!gh-badges/
|
||||
!lib/
|
||||
!core/
|
||||
!logo/
|
||||
!pages/
|
||||
!public/
|
||||
!templates/
|
||||
!services/
|
||||
!package-lock.json
|
||||
!/*.js
|
||||
!scripts/export-*.js
|
||||
!config/
|
||||
config/local*.yml
|
||||
*.spec.js
|
||||
*~
|
||||
.env
|
||||
.circleci
|
||||
.github
|
||||
.vscode
|
||||
__snapshots__
|
||||
.buildpacks
|
||||
.eslint*
|
||||
.editorconfig
|
||||
.nycrc*
|
||||
.gitpod*
|
||||
.prettier*
|
||||
CONTRIBUTING.md
|
||||
Dockerfile
|
||||
@@ -10,7 +10,6 @@
|
||||
"**/*-test-helpers.js",
|
||||
"**/*-fixtures.js",
|
||||
"**/mocha-*.js",
|
||||
"**/*.test-d.ts",
|
||||
"dangerfile.js",
|
||||
"gatsby-*.js",
|
||||
"core/service-test-runner",
|
||||
|
||||
@@ -10,5 +10,6 @@ package-lock.json
|
||||
private/*.json
|
||||
/.nyc_output
|
||||
analytics.json
|
||||
gh-badges/templates/default-template.json
|
||||
supported-features.json
|
||||
service-definitions.yml
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
semi: false
|
||||
singleQuote: true
|
||||
trailingComma: es5
|
||||
bracketSpacing: true
|
||||
endOfLine: lf
|
||||
arrowParens: avoid
|
||||
|
||||
6
.vscode/extensions.json
vendored
6
.vscode/extensions.json
vendored
@@ -1,3 +1,7 @@
|
||||
{
|
||||
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
|
||||
"recommendations": [
|
||||
"esbenp.prettier-vscode",
|
||||
"EditorConfig.EditorConfig",
|
||||
"dbaeumer.vscode-eslint"
|
||||
]
|
||||
}
|
||||
|
||||
16
CHANGELOG.md
16
CHANGELOG.md
@@ -1,16 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
Note: this changelog is for the shields.io server. The changelog for the badge-maker NPM package is at https://github.com/badges/shields/blob/master/badge-maker/CHANGELOG.md
|
||||
|
||||
---
|
||||
|
||||
## server-2021-02-01
|
||||
|
||||
- Docs.rs badge (#6098)
|
||||
- Fix feedz service in case the package page gets paginated (#6101)
|
||||
- [Bitbucket] Server Adding Auth Tokens and Resolving Pull Request api … (#6076)
|
||||
- Dependency updates
|
||||
|
||||
## server-2021-01-18
|
||||
|
||||
- Gotta start somewhere
|
||||
@@ -1,129 +0,0 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
 or directly to [@calebcartwright](https://github.com/calebcartwright)  or [@paulmelnikow](https://github.com/paulmelnikow) 
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
@@ -49,9 +49,8 @@ simple changes, like badge additions. These are usually tagged with
|
||||
|
||||
Please review [these impeccable guidelines][code review guidelines].
|
||||
|
||||
You can monitor [issues][], [discussions][] and the [chat room][], and help
|
||||
other people who have questions about contributing to Shields, or using it
|
||||
for their projects.
|
||||
You can monitor [issues][] and the [chat room][], and help other people who
|
||||
have questions about contributing to Shields, or using it for their projects.
|
||||
|
||||
Feel free to reach out to one of the [maintainers][]
|
||||
if you need help getting started.
|
||||
@@ -59,7 +58,6 @@ if you need help getting started.
|
||||
[service badge pr tag]: https://github.com/badges/shields/pulls?q=is%3Apr+is%3Aopen+label%3Aservice-badge
|
||||
[code review guidelines]: https://kickstarter.engineering/a-guide-to-mindful-communication-in-code-reviews-48aab5282e5e
|
||||
[issues]: https://github.com/badges/shields/issues
|
||||
[discussions]: https://github.com/badges/shields/discussions
|
||||
[chat room]: https://discordapp.com/invite/HjJCwm5
|
||||
[maintainers]: https://github.com/badges/shields#project-leaders
|
||||
|
||||
@@ -88,9 +86,9 @@ We're also asking for [one-time \$10 donations](https://opencollective.com/shiel
|
||||
There are three places to get help:
|
||||
|
||||
1. If you're new to the project, a good place to start is the [tutorial][].
|
||||
2. If you need help getting started or implementing a change, [start a discussion][discussions]
|
||||
2. If you need help getting started or implementing a change, [open an issue][]
|
||||
with your question. We promise it's okay to do that. If there is already an
|
||||
issue open for the feature you're working on, you can post there directly.
|
||||
issue open for the feature you're working on, you can post there.
|
||||
3. You can also join the [chat room][] and ask your question there.
|
||||
|
||||
[tutorial]: doc/TUTORIAL.md
|
||||
@@ -98,23 +96,20 @@ There are three places to get help:
|
||||
## Badge guidelines
|
||||
|
||||
- Shields.io hosts integrations for services which are primarily
|
||||
used by developers or which are widely used by developers.
|
||||
used by developers or which are widely used by developers
|
||||
- The left-hand side of a badge should not advertise. It should be a lowercase _noun_
|
||||
succinctly describing the meaning of the right-hand side.
|
||||
- Except for badges using the `social` style, logos should be _turned off by
|
||||
default_.
|
||||
- Badges should not obtain data from undocumented or reverse-engineered API endpoints.
|
||||
- Badges should not obtain data by scraping web pages - these are likely to break frequently.
|
||||
Whereas API publishers are incentivised to maintain a stable platform for their users,
|
||||
authors of web pages have no such incentive.
|
||||
- Badges may require users to specify a token in the badge URL as long it is scoped only to
|
||||
fetching information and doesn't expose any sensitive information. Generating a token with the
|
||||
correct scope must be clearly documented.
|
||||
|
||||
## Badge URLs
|
||||
|
||||
- The format of new badges should be of the form `/SERVICE/NOUN/PARAMETERS`.
|
||||
- There is further documentation on this in [badge-urls](https://github.com/badges/shields/blob/master/doc/badge-urls.md)
|
||||
- The format of new badges should be of the form
|
||||
`/SERVICE/NOUN/PARAMETERS/QUALIFIERS`. For instance,
|
||||
`/gitter/room/nwjs/nw.js`. The vendor is gitter, the
|
||||
badge is for rooms, and the parameter is nwjs/nw.js.
|
||||
- Services which require a url/hostname parameter should use a query parameter to accept that value. For instance,
|
||||
`/discourse/topics?server=https://meta.discourse.org`.
|
||||
|
||||
## Coding guidelines
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
FROM node:12-alpine
|
||||
FROM node:8-alpine
|
||||
|
||||
RUN mkdir -p /usr/src/app
|
||||
RUN mkdir /usr/src/app/private
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
COPY package.json package-lock.json /usr/src/app/
|
||||
# Without the badge-maker package.json and CLI script in place, `npm ci` will fail.
|
||||
COPY badge-maker /usr/src/app/badge-maker/
|
||||
# Without the gh-badges package.json and CLI script in place, `npm ci` will fail.
|
||||
COPY gh-badges /usr/src/app/gh-badges/
|
||||
|
||||
# We need dev deps to build the front end. We don't need Cypress, though.
|
||||
RUN NODE_ENV=development CYPRESS_INSTALL_BINARY=0 npm ci
|
||||
|
||||
70
Makefile
Normal file
70
Makefile
Normal file
@@ -0,0 +1,70 @@
|
||||
SHELL:=/bin/bash
|
||||
|
||||
SERVER_TMP=${TMPDIR}shields-server-deploy
|
||||
FRONTEND_TMP=${TMPDIR}shields-frontend-deploy
|
||||
|
||||
# This branch is reserved for the deploy process and should not be used for
|
||||
# development. The deploy script will clobber it. To avoid accidentally
|
||||
# pushing secrets to GitHub, this branch is configured to reject pushes.
|
||||
WORKING_BRANCH=server-deploy-working-branch
|
||||
|
||||
all: test
|
||||
|
||||
deploy: deploy-s0 deploy-s1 deploy-s2 clean-server-deploy deploy-gh-pages deploy-gh-pages-clean
|
||||
|
||||
deploy-s0: prepare-server-deploy push-s0
|
||||
deploy-s1: prepare-server-deploy push-s1
|
||||
deploy-s2: prepare-server-deploy push-s2
|
||||
|
||||
prepare-server-deploy:
|
||||
# Ship a copy of the front end to each server for debugging.
|
||||
# https://github.com/badges/shields/issues/1220
|
||||
INCLUDE_DEV_PAGES=false \
|
||||
npm run build
|
||||
rm -rf ${SERVER_TMP}
|
||||
git worktree prune
|
||||
git worktree add -B ${WORKING_BRANCH} ${SERVER_TMP}
|
||||
cp -r public ${SERVER_TMP}
|
||||
git -C ${SERVER_TMP} add -f public/
|
||||
git -C ${SERVER_TMP} commit --no-verify -m '[DEPLOY] Add frontend for debugging'
|
||||
cp config/local-shields-io-production.yml ${SERVER_TMP}/config/
|
||||
git -C ${SERVER_TMP} add -f config/local-shields-io-production.yml
|
||||
git -C ${SERVER_TMP} commit --no-verify -m '[DEPLOY] MUST NOT BE ON GITHUB'
|
||||
|
||||
clean-server-deploy:
|
||||
rm -rf ${SERVER_TMP}
|
||||
git worktree prune
|
||||
|
||||
push-s0:
|
||||
git push -f s0 ${WORKING_BRANCH}:master
|
||||
|
||||
push-s1:
|
||||
git push -f s1 ${WORKING_BRANCH}:master
|
||||
|
||||
push-s2:
|
||||
git push -f s2 ${WORKING_BRANCH}:master
|
||||
|
||||
deploy-gh-pages:
|
||||
rm -rf ${FRONTEND_TMP}
|
||||
git worktree prune
|
||||
GATSBY_BASE_URL=https://img.shields.io \
|
||||
INCLUDE_DEV_PAGES=false \
|
||||
npm run build
|
||||
git worktree add -B gh-pages ${FRONTEND_TMP}
|
||||
git -C ${FRONTEND_TMP} ls-files | xargs git -C ${FRONTEND_TMP} rm
|
||||
git -C ${FRONTEND_TMP} commit --no-verify -m '[DEPLOY] Completely clean the index'
|
||||
cp -r public/* ${FRONTEND_TMP}
|
||||
echo shields.io > ${FRONTEND_TMP}/CNAME
|
||||
touch ${FRONTEND_TMP}/.nojekyll
|
||||
git -C ${FRONTEND_TMP} add .
|
||||
git -C ${FRONTEND_TMP} commit --no-verify -m '[DEPLOY] Add built site'
|
||||
git push -f origin gh-pages
|
||||
|
||||
deploy-gh-pages-clean:
|
||||
rm -rf ${FRONTEND_TMP}
|
||||
git worktree prune
|
||||
|
||||
test:
|
||||
npm test
|
||||
|
||||
.PHONY: all deploy prepare-server-deploy clean-server-deploy deploy-s0 deploy-s1 deploy-s2 push-s0 push-s1 push-s2 deploy-gh-pages deploy-gh-pages-clean deploy-heroku setup redis test
|
||||
77
README.md
77
README.md
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/badges/shields/master/readme-logo.svg?sanitize=true"
|
||||
<img src="https://raw.githubusercontent.com/badges/shields/master/frontend/images/logo.svg?sanitize=true"
|
||||
height="130">
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -22,6 +22,9 @@
|
||||
<a href="https://lgtm.com/projects/g/badges/shields/alerts/">
|
||||
<img src="https://img.shields.io/lgtm/alerts/g/badges/shields"
|
||||
alt="Total alerts"/></a>
|
||||
<a href="https://github.com/badges/shields/compare/gh-pages...master">
|
||||
<img src="https://img.shields.io/github/commits-since/badges/shields/gh-pages?label=commits%20to%20be%20deployed"
|
||||
alt="commits to be deployed"></a>
|
||||
<a href="https://discord.gg/HjJCwm5">
|
||||
<img src="https://img.shields.io/discord/308323056592486420?logo=discord"
|
||||
alt="chat on Discord"></a>
|
||||
@@ -40,16 +43,16 @@ Every month it serves over 470 million images.
|
||||
This repo hosts:
|
||||
|
||||
- The [Shields.io][shields.io] frontend and server code
|
||||
- An [NPM library for generating badges][badge-maker]
|
||||
- [documentation][badge-maker-docs]
|
||||
- [changelog][badge-maker-changelog]
|
||||
- An [NPM library for generating badges][gh-badges]
|
||||
- [documentation][gh-badges-docs]
|
||||
- [changelog][gh-badges-changelog]
|
||||
- The [badge design specification][badge-spec]
|
||||
|
||||
[shields.io]: https://shields.io/
|
||||
[badge-maker]: https://www.npmjs.com/package/badge-maker
|
||||
[gh-badges]: https://www.npmjs.com/package/gh-badges
|
||||
[badge-spec]: https://github.com/badges/shields/tree/master/spec
|
||||
[badge-maker-docs]: https://github.com/badges/shields/tree/master/badge-maker/README.md
|
||||
[badge-maker-changelog]: https://github.com/badges/shields/tree/master/badge-maker/CHANGELOG.md
|
||||
[gh-badges-docs]: https://github.com/badges/shields/tree/master/gh-badges/README.md
|
||||
[gh-badges-changelog]: https://github.com/badges/shields/tree/master/gh-badges/CHANGELOG.md
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -67,14 +70,10 @@ This repo hosts:
|
||||
[Make your own badges!][custom badges]
|
||||
(Quick example: `https://img.shields.io/badge/left-right-f39f37`)
|
||||
|
||||
Browse a [complete list of badges][shields.io].
|
||||
|
||||
[custom badges]: http://shields.io/#your-badge
|
||||
|
||||
### Quickstart
|
||||
|
||||
Browse a [complete list of badges][shields.io] and locate a particular badge by using the search bar or by browsing the categories. Click on the badge to fill in required data elements for that badge type (like your username or repo) and optionally customize (label, colors etc.). And it's ready for use!
|
||||
|
||||
Use the button at the bottom to copy your badge url or snippet, which can then be added to places like your GitHub readme files or other web pages.
|
||||
|
||||
## Contributing
|
||||
|
||||
Shields is a community project. We invite your participation through issues
|
||||
@@ -83,20 +82,20 @@ and pull requests! You can peruse the [contributing guidelines][contributing].
|
||||
When adding or changing a service [please add tests][service-tests].
|
||||
|
||||
This project has quite a backlog of suggestions! If you're new to the project,
|
||||
maybe you'd like to open a pull request to address one of them.
|
||||
|
||||
You can read a [tutorial on how to add a badge][tutorial].
|
||||
maybe you'd like to open a pull request to address one of them:
|
||||
|
||||
[](https://github.com/badges/shields/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
|
||||
|
||||
You can read a [tutorial on how to add a badge][tutorial].
|
||||
|
||||
[service-tests]: https://github.com/badges/shields/blob/master/doc/service-tests.md
|
||||
[tutorial]: doc/TUTORIAL.md
|
||||
[contributing]: CONTRIBUTING.md
|
||||
|
||||
## Development
|
||||
|
||||
1. Install Node 12 or later. You can use the [package manager][] of your choice.
|
||||
Tests need to pass in Node 12 and 14.
|
||||
1. Install Node 8 or later. You can use the [package manager][] of your choice.
|
||||
Tests need to pass in Node 8 and 10.
|
||||
2. Clone this repository.
|
||||
3. Run `npm ci` to install the dependencies.
|
||||
4. Run `npm start` to start the badge server and the frontend dev server.
|
||||
@@ -125,8 +124,8 @@ Please report any Gitpod bugs, questions, or suggestions in issue
|
||||
|
||||
[Snapshot tests][] ensure we don't inadvertently make changes that affect the
|
||||
SVG or JSON output. When deliberately changing the output, run
|
||||
`SNAPSHOT_DRY=1 npm run test:package` to preview changes to the saved
|
||||
snapshots, and `SNAPSHOT_UPDATE=1 npm run test:package` to update them.
|
||||
`SNAPSHOT_DRY=1 npm run test:js:server` to preview changes to the saved
|
||||
snapshots, and `SNAPSHOT_UPDATE=1 npm run test:js:server` to update them.
|
||||
|
||||
The server can be configured to use [Sentry][] ([configuration][sentry configuration]) and [Prometheus][] ([configuration][prometheus configuration]).
|
||||
|
||||
@@ -184,6 +183,7 @@ Maintainers:
|
||||
- [calebcartwright](https://github.com/calebcartwright) (core team)
|
||||
- [chris48s](https://github.com/chris48s) (core team)
|
||||
- [Daniel15](https://github.com/Daniel15) (core team)
|
||||
- [espadrine](https://github.com/espadrine) (core team)
|
||||
- [paulmelnikow](https://github.com/paulmelnikow) (core team)
|
||||
- [platan](https://github.com/platan) (core team)
|
||||
- [PyvesB](https://github.com/PyvesB) (core team)
|
||||
@@ -191,22 +191,19 @@ Maintainers:
|
||||
|
||||
Operations:
|
||||
|
||||
- [calebcartwright](https://github.com/calebcartwright)
|
||||
- [chris48s](https://github.com/chris48s)
|
||||
- [paulmelnikow](https://github.com/paulmelnikow)
|
||||
- [PyvesB](https://github.com/PyvesB)
|
||||
- [espadrine](https://github.com/espadrine) (sysadmin)
|
||||
- [paulmelnikow](https://github.com/paulmelnikow) (limited access)
|
||||
|
||||
Alumni:
|
||||
|
||||
- [espadrine](https://github.com/espadrine)
|
||||
- [olivierlacan](https://github.com/olivierlacan)
|
||||
|
||||
## Related projects
|
||||
|
||||
- [poser PHP library][poser]
|
||||
- [badgerbadgerbadger gem][gem]
|
||||
- [pybadges python library][pybadges]
|
||||
|
||||
[poser]: https://github.com/badges/poser
|
||||
[gem]: https://github.com/badges/badgerbadgerbadger
|
||||
[pybadges]: https://github.com/google/pybadges
|
||||
|
||||
## License
|
||||
@@ -217,6 +214,28 @@ domain unless specified otherwise.
|
||||
The assets in `logo/` are trademarks of their respective companies and are
|
||||
under their terms and license.
|
||||
|
||||
## Community
|
||||
## Contributors
|
||||
|
||||
Thanks to the people and companies who donate money, services or time to keep the project running. [https://shields.io/community](https://shields.io/community)
|
||||
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
|
||||
<a href="https://github.com/badges/shields/graphs/contributors"><img src="https://opencollective.com/shields/contributors.svg?width=890" /></a>
|
||||
|
||||
## Backers
|
||||
|
||||
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/shields#backer)]
|
||||
|
||||
<a href="https://opencollective.com/shields#backers" target="_blank"><img src="https://opencollective.com/shields/backers.svg?width=890"></a>
|
||||
|
||||
## Sponsors
|
||||
|
||||
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/shields#sponsor)]
|
||||
|
||||
<a href="https://opencollective.com/shields/sponsor/0/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/0/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/1/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/1/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/2/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/2/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/3/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/3/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/4/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/4/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/5/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/5/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/6/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/6/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/7/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/7/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/8/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/8/avatar.svg"></a>
|
||||
<a href="https://opencollective.com/shields/sponsor/9/website" target="_blank"><img src="https://opencollective.com/shields/sponsor/9/avatar.svg"></a>
|
||||
|
||||
25
SECURITY.md
25
SECURITY.md
@@ -1,25 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Projects
|
||||
|
||||
Please follow this guidance when reporting security issues affecting:
|
||||
|
||||
- [Shields.io](https://shields.io)
|
||||
- [Raster.shields.io](https://raster.shields.io)
|
||||
- Self-hosted Shields instances
|
||||
- The [svg-to-image-proxy](https://www.npmjs.com/package/svg-to-image-proxy) NPM package
|
||||
- The [badge-maker](https://www.npmjs.com/package/badge-maker) NPM package
|
||||
|
||||
The [gh-badges](https://www.npmjs.com/package/gh-badges) NPM package is now deprecated and will no longer receive fixes for bugs or security issues.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you find a security vulnerability affecting any of our supported projects, please email [security@shields.io](mailto:security@shields.io), rather than opening a public issue on GitHub. After receiving the initial report, we will endeavor to keep you informed of the progress towards a fix and full announcement. We may ask you for additional information. You are also welcome to propose a patch or solution.
|
||||
|
||||
Report security bugs in third-party modules to the person or team maintaining the module.
|
||||
|
||||
## Coordinated Disclosure
|
||||
|
||||
We aim to patch confirmed vulnerabilities within 90 days or less, disclosing the details of those vulnerabilities when a patch is published. We ask that you refrain from sharing your report with others while we work on our patch.
|
||||
|
||||
We may want to coordinate an advisory with you to be published simultaneously with the patch, but you are also welcome to self-disclose after 90 days if you prefer. We will never publish information about you or our communications with you without your permission.
|
||||
File diff suppressed because it is too large
Load Diff
11
badge-maker/index.d.ts
vendored
11
badge-maker/index.d.ts
vendored
@@ -1,11 +0,0 @@
|
||||
interface Format {
|
||||
label?: string
|
||||
message: string
|
||||
labelColor?: string
|
||||
color?: string
|
||||
style?: 'plastic' | 'flat' | 'flat-square' | 'for-the-badge' | 'social'
|
||||
}
|
||||
|
||||
export declare class ValidationError extends Error {}
|
||||
|
||||
export declare function makeBadge(format: Format): string
|
||||
@@ -1,35 +0,0 @@
|
||||
import { expectType, expectError, expectAssignable } from 'tsd'
|
||||
import { makeBadge, ValidationError } from '.'
|
||||
|
||||
expectError(makeBadge('string is invalid'))
|
||||
expectError(makeBadge({}))
|
||||
expectError(
|
||||
makeBadge({
|
||||
message: 'passed',
|
||||
style: 'invalid style',
|
||||
})
|
||||
)
|
||||
|
||||
expectType<string>(
|
||||
makeBadge({
|
||||
message: 'passed',
|
||||
})
|
||||
)
|
||||
expectType<string>(
|
||||
makeBadge({
|
||||
label: 'build',
|
||||
message: 'passed',
|
||||
})
|
||||
)
|
||||
expectType<string>(
|
||||
makeBadge({
|
||||
label: 'build',
|
||||
message: 'passed',
|
||||
labelColor: 'green',
|
||||
color: 'red',
|
||||
style: 'flat',
|
||||
})
|
||||
)
|
||||
|
||||
const error = new ValidationError()
|
||||
expectAssignable<Error>(error)
|
||||
@@ -1,708 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const anafanafo = require('anafanafo')
|
||||
const { brightness } = require('./color')
|
||||
|
||||
const fontFamily = 'font-family="Verdana,Geneva,DejaVu Sans,sans-serif"'
|
||||
const socialFontFamily =
|
||||
'font-family="Helvetica Neue,Helvetica,Arial,sans-serif"'
|
||||
const brightnessThreshold = 0.69
|
||||
|
||||
function capitalize(s) {
|
||||
return `${s.charAt(0).toUpperCase()}${s.slice(1)}`
|
||||
}
|
||||
|
||||
function colorsForBackground(color) {
|
||||
if (brightness(color) <= brightnessThreshold) {
|
||||
return { textColor: '#fff', shadowColor: '#010101' }
|
||||
} else {
|
||||
return { textColor: '#333', shadowColor: '#ccc' }
|
||||
}
|
||||
}
|
||||
|
||||
function escapeXml(s) {
|
||||
if (s === undefined || typeof s !== 'string') {
|
||||
return undefined
|
||||
} else {
|
||||
return s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
}
|
||||
|
||||
function roundUpToOdd(val) {
|
||||
return val % 2 === 0 ? val + 1 : val
|
||||
}
|
||||
|
||||
function preferredWidthOf(str, options) {
|
||||
// Increase chances of pixel grid alignment.
|
||||
return roundUpToOdd(anafanafo(str, options) | 0)
|
||||
}
|
||||
|
||||
function createAccessibleText({ label, message }) {
|
||||
const labelPrefix = label ? `${label}: ` : ''
|
||||
return labelPrefix + message
|
||||
}
|
||||
|
||||
function hasLinks({ links }) {
|
||||
const [leftLink, rightLink] = links || []
|
||||
const hasLeftLink = leftLink && leftLink.length
|
||||
const hasRightLink = rightLink && rightLink.length
|
||||
const hasLink = hasLeftLink && hasRightLink
|
||||
return { hasLink, hasLeftLink, hasRightLink }
|
||||
}
|
||||
|
||||
function shouldWrapBodyWithLink({ links }) {
|
||||
const { hasLeftLink, hasRightLink } = hasLinks({ links })
|
||||
return hasLeftLink && !hasRightLink
|
||||
}
|
||||
|
||||
function renderAriaAttributes({ accessibleText, links }) {
|
||||
const { hasLink } = hasLinks({ links })
|
||||
return hasLink ? '' : `role="img" aria-label="${escapeXml(accessibleText)}"`
|
||||
}
|
||||
|
||||
function renderTitle({ accessibleText, links }) {
|
||||
const { hasLink } = hasLinks({ links })
|
||||
return hasLink ? '' : `<title>${escapeXml(accessibleText)}</title>`
|
||||
}
|
||||
|
||||
function renderLogo({
|
||||
logo,
|
||||
badgeHeight,
|
||||
horizPadding,
|
||||
logoWidth = 14,
|
||||
logoPadding = 0,
|
||||
}) {
|
||||
if (logo) {
|
||||
const logoHeight = 14
|
||||
const y = (badgeHeight - logoHeight) / 2
|
||||
const x = horizPadding
|
||||
return {
|
||||
hasLogo: true,
|
||||
totalLogoWidth: logoWidth + logoPadding,
|
||||
renderedLogo: `<image x="${x}" y="${y}" width="${logoWidth}" height="${logoHeight}" xlink:href="${escapeXml(
|
||||
logo
|
||||
)}"/>`,
|
||||
}
|
||||
} else {
|
||||
return { hasLogo: false, totalLogoWidth: 0, renderedLogo: '' }
|
||||
}
|
||||
}
|
||||
|
||||
function renderLink({
|
||||
link,
|
||||
height,
|
||||
textLength,
|
||||
horizPadding,
|
||||
leftMargin,
|
||||
renderedText,
|
||||
}) {
|
||||
const rectHeight = height
|
||||
const rectWidth = textLength + horizPadding * 2
|
||||
const rectX = leftMargin > 1 ? leftMargin + 1 : 0
|
||||
return `<a target="_blank" xlink:href="${escapeXml(link)}">
|
||||
<rect width="${rectWidth}" x="${rectX}" height="${rectHeight}" fill="rgba(0,0,0,0)" />
|
||||
${renderedText}
|
||||
</a>`
|
||||
}
|
||||
|
||||
function renderText({
|
||||
leftMargin,
|
||||
horizPadding = 0,
|
||||
content,
|
||||
link,
|
||||
height,
|
||||
verticalMargin = 0,
|
||||
shadow = false,
|
||||
color,
|
||||
}) {
|
||||
if (!content.length) {
|
||||
return { renderedText: '', width: 0 }
|
||||
}
|
||||
|
||||
const textLength = preferredWidthOf(content, { font: '11px Verdana' })
|
||||
const escapedContent = escapeXml(content)
|
||||
|
||||
const shadowMargin = 150 + verticalMargin
|
||||
const textMargin = 140 + verticalMargin
|
||||
|
||||
const outTextLength = 10 * textLength
|
||||
const x = 10 * (leftMargin + 0.5 * textLength + horizPadding)
|
||||
|
||||
let renderedText = ''
|
||||
const { textColor, shadowColor } = colorsForBackground(color)
|
||||
if (shadow) {
|
||||
renderedText = `<text aria-hidden="true" x="${x}" y="${shadowMargin}" fill="${shadowColor}" fill-opacity=".3" transform="scale(.1)" textLength="${outTextLength}">${escapedContent}</text>`
|
||||
}
|
||||
renderedText += `<text x="${x}" y="${textMargin}" transform="scale(.1)" fill="${textColor}" textLength="${outTextLength}">${escapedContent}</text>`
|
||||
|
||||
return {
|
||||
renderedText: link
|
||||
? renderLink({
|
||||
link,
|
||||
height,
|
||||
textLength,
|
||||
horizPadding,
|
||||
leftMargin,
|
||||
renderedText,
|
||||
})
|
||||
: renderedText,
|
||||
width: textLength,
|
||||
}
|
||||
}
|
||||
|
||||
function renderBadge(
|
||||
{ links, leftWidth, rightWidth, height, accessibleText },
|
||||
main
|
||||
) {
|
||||
const width = leftWidth + rightWidth
|
||||
const leftLink = escapeXml(links[0])
|
||||
|
||||
return `
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" ${renderAriaAttributes(
|
||||
{ links, accessibleText }
|
||||
)}>
|
||||
|
||||
${renderTitle({ accessibleText, links })}
|
||||
${
|
||||
shouldWrapBodyWithLink({ links })
|
||||
? `<a target="_blank" xlink:href="${leftLink}">${main}</a>`
|
||||
: main
|
||||
}
|
||||
</svg>`
|
||||
}
|
||||
|
||||
class Badge {
|
||||
static get fontFamily() {
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
|
||||
static get height() {
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
|
||||
static get verticalMargin() {
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
|
||||
static get shadow() {
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
|
||||
constructor({
|
||||
label,
|
||||
message,
|
||||
links,
|
||||
logo,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
color = '#4c1',
|
||||
labelColor,
|
||||
}) {
|
||||
const horizPadding = 5
|
||||
const { hasLogo, totalLogoWidth, renderedLogo } = renderLogo({
|
||||
logo,
|
||||
badgeHeight: this.constructor.height,
|
||||
horizPadding,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
})
|
||||
const hasLabel = label.length || labelColor
|
||||
if (labelColor == null) {
|
||||
labelColor = '#555'
|
||||
}
|
||||
|
||||
const [leftLink, rightLink] = links
|
||||
|
||||
labelColor = hasLabel || hasLogo ? labelColor : color
|
||||
labelColor = escapeXml(labelColor)
|
||||
color = escapeXml(color)
|
||||
|
||||
const labelMargin = totalLogoWidth + 1
|
||||
|
||||
const { renderedText: renderedLabel, width: labelWidth } = renderText({
|
||||
leftMargin: labelMargin,
|
||||
horizPadding,
|
||||
content: label,
|
||||
link: !shouldWrapBodyWithLink({ links }) && leftLink,
|
||||
height: this.constructor.height,
|
||||
verticalMargin: this.constructor.verticalMargin,
|
||||
shadow: this.constructor.shadow,
|
||||
color: labelColor,
|
||||
})
|
||||
|
||||
const leftWidth = hasLabel
|
||||
? labelWidth + 2 * horizPadding + totalLogoWidth
|
||||
: 0
|
||||
|
||||
let messageMargin = leftWidth - (message.length ? 1 : 0)
|
||||
if (!hasLabel) {
|
||||
if (hasLogo) {
|
||||
messageMargin = messageMargin + totalLogoWidth + horizPadding
|
||||
} else {
|
||||
messageMargin = messageMargin + 1
|
||||
}
|
||||
}
|
||||
|
||||
const { renderedText: renderedMessage, width: messageWidth } = renderText({
|
||||
leftMargin: messageMargin,
|
||||
horizPadding,
|
||||
content: message,
|
||||
link: rightLink,
|
||||
height: this.constructor.height,
|
||||
verticalMargin: this.constructor.verticalMargin,
|
||||
shadow: this.constructor.shadow,
|
||||
color,
|
||||
})
|
||||
|
||||
let rightWidth = messageWidth + 2 * horizPadding
|
||||
if (hasLogo && !hasLabel) {
|
||||
rightWidth += totalLogoWidth + horizPadding - 1
|
||||
}
|
||||
|
||||
const width = leftWidth + rightWidth
|
||||
|
||||
const accessibleText = createAccessibleText({ label, message })
|
||||
|
||||
this.links = links
|
||||
this.leftWidth = leftWidth
|
||||
this.rightWidth = rightWidth
|
||||
this.width = width
|
||||
this.labelColor = labelColor
|
||||
this.color = color
|
||||
this.label = label
|
||||
this.message = message
|
||||
this.accessibleText = accessibleText
|
||||
this.renderedLogo = renderedLogo
|
||||
this.renderedLabel = renderedLabel
|
||||
this.renderedMessage = renderedMessage
|
||||
}
|
||||
|
||||
static render(params) {
|
||||
return new this(params).render()
|
||||
}
|
||||
|
||||
render() {
|
||||
throw new Error('Not implemented')
|
||||
}
|
||||
}
|
||||
|
||||
class Plastic extends Badge {
|
||||
static get fontFamily() {
|
||||
return fontFamily
|
||||
}
|
||||
|
||||
static get height() {
|
||||
return 18
|
||||
}
|
||||
|
||||
static get verticalMargin() {
|
||||
return -10
|
||||
}
|
||||
|
||||
static get shadow() {
|
||||
return true
|
||||
}
|
||||
|
||||
render() {
|
||||
return renderBadge(
|
||||
{
|
||||
links: this.links,
|
||||
leftWidth: this.leftWidth,
|
||||
rightWidth: this.rightWidth,
|
||||
accessibleText: this.accessibleText,
|
||||
height: this.constructor.height,
|
||||
},
|
||||
`
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
|
||||
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
|
||||
<stop offset=".9" stop-color="#000" stop-opacity=".3"/>
|
||||
<stop offset="1" stop-color="#000" stop-opacity=".5"/>
|
||||
</linearGradient>
|
||||
|
||||
<clipPath id="r">
|
||||
<rect width="${this.width}" height="${this.constructor.height}" rx="4" fill="#fff"/>
|
||||
</clipPath>
|
||||
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="${this.leftWidth}" height="${this.constructor.height}" fill="${this.labelColor}"/>
|
||||
<rect x="${this.leftWidth}" width="${this.rightWidth}" height="${this.constructor.height}" fill="${this.color}"/>
|
||||
<rect width="${this.width}" height="${this.constructor.height}" fill="url(#s)"/>
|
||||
</g>
|
||||
|
||||
<g fill="#fff" text-anchor="middle" ${this.constructor.fontFamily} text-rendering="geometricPrecision" font-size="110">
|
||||
${this.renderedLogo}
|
||||
${this.renderedLabel}
|
||||
${this.renderedMessage}
|
||||
</g>`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class Flat extends Badge {
|
||||
static get fontFamily() {
|
||||
return fontFamily
|
||||
}
|
||||
|
||||
static get height() {
|
||||
return 20
|
||||
}
|
||||
|
||||
static get verticalMargin() {
|
||||
return 0
|
||||
}
|
||||
|
||||
static get shadow() {
|
||||
return true
|
||||
}
|
||||
|
||||
render() {
|
||||
return renderBadge(
|
||||
{
|
||||
links: this.links,
|
||||
leftWidth: this.leftWidth,
|
||||
rightWidth: this.rightWidth,
|
||||
accessibleText: this.accessibleText,
|
||||
height: this.constructor.height,
|
||||
},
|
||||
`
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
|
||||
<clipPath id="r">
|
||||
<rect width="${this.width}" height="${this.constructor.height}" rx="3" fill="#fff"/>
|
||||
</clipPath>
|
||||
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="${this.leftWidth}" height="${this.constructor.height}" fill="${this.labelColor}"/>
|
||||
<rect x="${this.leftWidth}" width="${this.rightWidth}" height="${this.constructor.height}" fill="${this.color}"/>
|
||||
<rect width="${this.width}" height="${this.constructor.height}" fill="url(#s)"/>
|
||||
</g>
|
||||
|
||||
<g fill="#fff" text-anchor="middle" ${this.constructor.fontFamily} text-rendering="geometricPrecision" font-size="110">
|
||||
${this.renderedLogo}
|
||||
${this.renderedLabel}
|
||||
${this.renderedMessage}
|
||||
</g>`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class FlatSquare extends Badge {
|
||||
static get fontFamily() {
|
||||
return fontFamily
|
||||
}
|
||||
|
||||
static get height() {
|
||||
return 20
|
||||
}
|
||||
|
||||
static get verticalMargin() {
|
||||
return 0
|
||||
}
|
||||
|
||||
static get shadow() {
|
||||
return false
|
||||
}
|
||||
|
||||
render() {
|
||||
return renderBadge(
|
||||
{
|
||||
links: this.links,
|
||||
leftWidth: this.leftWidth,
|
||||
rightWidth: this.rightWidth,
|
||||
accessibleText: this.accessibleText,
|
||||
height: this.constructor.height,
|
||||
},
|
||||
`
|
||||
<g shape-rendering="crispEdges">
|
||||
<rect width="${this.leftWidth}" height="${this.constructor.height}" fill="${this.labelColor}"/>
|
||||
<rect x="${this.leftWidth}" width="${this.rightWidth}" height="${this.constructor.height}" fill="${this.color}"/>
|
||||
</g>
|
||||
|
||||
<g fill="#fff" text-anchor="middle" ${this.constructor.fontFamily} text-rendering="geometricPrecision" font-size="110">
|
||||
${this.renderedLogo}
|
||||
${this.renderedLabel}
|
||||
${this.renderedMessage}
|
||||
</g>`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function social({
|
||||
label,
|
||||
message,
|
||||
links = [],
|
||||
logo,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
color = '#4c1',
|
||||
labelColor = '#555',
|
||||
}) {
|
||||
// Social label is styled with a leading capital. Convert to caps here so
|
||||
// width can be measured using the correct characters.
|
||||
label = capitalize(label)
|
||||
|
||||
const externalHeight = 20
|
||||
const internalHeight = 19
|
||||
const labelHorizPadding = 5
|
||||
const messageHorizPadding = 4
|
||||
const horizGutter = 6
|
||||
const { totalLogoWidth, renderedLogo } = renderLogo({
|
||||
logo,
|
||||
badgeHeight: externalHeight,
|
||||
horizPadding: labelHorizPadding,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
})
|
||||
const hasMessage = message.length
|
||||
|
||||
const font = 'bold 11px Helvetica'
|
||||
const labelTextWidth = preferredWidthOf(label, { font })
|
||||
const messageTextWidth = preferredWidthOf(message, { font })
|
||||
const labelRectWidth = labelTextWidth + totalLogoWidth + 2 * labelHorizPadding
|
||||
const messageRectWidth = messageTextWidth + 2 * messageHorizPadding
|
||||
|
||||
let [leftLink, rightLink] = links
|
||||
leftLink = escapeXml(leftLink)
|
||||
rightLink = escapeXml(rightLink)
|
||||
const { hasLeftLink, hasRightLink, hasLink } = hasLinks({ links })
|
||||
|
||||
const accessibleText = createAccessibleText({ label, message })
|
||||
|
||||
function renderMessageBubble() {
|
||||
const messageBubbleMainX = labelRectWidth + horizGutter + 0.5
|
||||
const messageBubbleNotchX = labelRectWidth + horizGutter
|
||||
return `
|
||||
<rect x="${messageBubbleMainX}" y="0.5" width="${messageRectWidth}" height="${internalHeight}" rx="2" fill="#fafafa"/>
|
||||
<rect x="${messageBubbleNotchX}" y="7.5" width="0.5" height="5" stroke="#fafafa"/>
|
||||
<path d="M${messageBubbleMainX} 6.5 l-3 3v1 l3 3" stroke="d5d5d5" fill="#fafafa"/>
|
||||
`
|
||||
}
|
||||
|
||||
function renderLabelText() {
|
||||
const labelTextX =
|
||||
10 * (totalLogoWidth + labelTextWidth / 2 + labelHorizPadding)
|
||||
const labelTextLength = 10 * labelTextWidth
|
||||
const escapedLabel = escapeXml(label)
|
||||
const shouldWrapWithLink = hasLeftLink && !shouldWrapBodyWithLink({ links })
|
||||
|
||||
const rect = `<rect id="llink" stroke="#d5d5d5" fill="url(#a)" x=".5" y=".5" width="${labelRectWidth}" height="${internalHeight}" rx="2" />`
|
||||
const shadow = `<text aria-hidden="true" x="${labelTextX}" y="150" fill="#fff" transform="scale(.1)" textLength="${labelTextLength}">${escapedLabel}</text>`
|
||||
const text = `<text x="${labelTextX}" y="140" transform="scale(.1)" textLength="${labelTextLength}">${escapedLabel}</text>`
|
||||
|
||||
return shouldWrapWithLink
|
||||
? `
|
||||
<a target="_blank" xlink:href="${leftLink}">
|
||||
${shadow}
|
||||
${text}
|
||||
${rect}
|
||||
</a>
|
||||
`
|
||||
: `
|
||||
${rect}
|
||||
${shadow}
|
||||
${text}
|
||||
`
|
||||
}
|
||||
|
||||
function renderMessageText() {
|
||||
const messageTextX =
|
||||
10 * (labelRectWidth + horizGutter + messageRectWidth / 2)
|
||||
const messageTextLength = 10 * messageTextWidth
|
||||
const escapedMessage = escapeXml(message)
|
||||
|
||||
const rect = `<rect width="${messageRectWidth + 1}" x="${
|
||||
labelRectWidth + horizGutter
|
||||
}" height="${internalHeight + 1}" fill="rgba(0,0,0,0)" />`
|
||||
const shadow = `<text aria-hidden="true" x="${messageTextX}" y="150" fill="#fff" transform="scale(.1)" textLength="${messageTextLength}">${escapedMessage}</text>`
|
||||
const text = `<text id="rlink" x="${messageTextX}" y="140" transform="scale(.1)" textLength="${messageTextLength}">${escapedMessage}</text>`
|
||||
|
||||
return hasRightLink
|
||||
? `
|
||||
<a target="_blank" xlink:href="${rightLink}">
|
||||
${rect}
|
||||
${shadow}
|
||||
${text}
|
||||
</a>
|
||||
`
|
||||
: `
|
||||
${shadow}
|
||||
${text}
|
||||
`
|
||||
}
|
||||
|
||||
return renderBadge(
|
||||
{
|
||||
links,
|
||||
leftWidth: labelRectWidth + 1,
|
||||
rightWidth: hasMessage ? horizGutter + messageRectWidth : 0,
|
||||
accessibleText,
|
||||
height: externalHeight,
|
||||
},
|
||||
`
|
||||
<style>a:hover #llink{fill:url(#b);stroke:#ccc}a:hover #rlink{fill:#4183c4}</style>
|
||||
<linearGradient id="a" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fcfcfc" stop-opacity="0"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="b" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#ccc" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<g stroke="#d5d5d5">
|
||||
<rect stroke="none" fill="#fcfcfc" x="0.5" y="0.5" width="${labelRectWidth}" height="${internalHeight}" rx="2"/>
|
||||
${hasMessage ? renderMessageBubble() : ''}
|
||||
</g>
|
||||
${renderedLogo}
|
||||
<g aria-hidden="${!hasLink}" fill="#333" text-anchor="middle" ${socialFontFamily} text-rendering="geometricPrecision" font-weight="700" font-size="110px" line-height="14px">
|
||||
${renderLabelText()}
|
||||
${hasMessage ? renderMessageText() : ''}
|
||||
</g>
|
||||
`
|
||||
)
|
||||
}
|
||||
|
||||
function forTheBadge({
|
||||
label,
|
||||
message,
|
||||
links,
|
||||
logo,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
color = '#4c1',
|
||||
labelColor,
|
||||
}) {
|
||||
// For the Badge is styled in all caps. Convert to caps here so widths can
|
||||
// be measured using the correct characters.
|
||||
label = label.toUpperCase()
|
||||
message = message.toUpperCase()
|
||||
|
||||
let labelWidth = preferredWidthOf(label, { font: '10px Verdana' }) || 0
|
||||
let messageWidth =
|
||||
preferredWidthOf(message, { font: 'bold 10px Verdana' }) || 0
|
||||
const height = 28
|
||||
const hasLabel = label.length || labelColor
|
||||
if (labelColor == null) {
|
||||
labelColor = '#555'
|
||||
}
|
||||
const horizPadding = 9
|
||||
const { hasLogo, totalLogoWidth, renderedLogo } = renderLogo({
|
||||
logo,
|
||||
badgeHeight: height,
|
||||
horizPadding,
|
||||
logoWidth,
|
||||
logoPadding,
|
||||
})
|
||||
|
||||
labelWidth += 10 + totalLogoWidth
|
||||
if (label.length) {
|
||||
// Add 10 px of padding, plus approximately 1 px of letter spacing per
|
||||
// character.
|
||||
labelWidth += 10 + 2 * label.length
|
||||
} else if (hasLogo) {
|
||||
if (hasLabel) {
|
||||
labelWidth += 7
|
||||
} else {
|
||||
labelWidth -= 7
|
||||
}
|
||||
} else {
|
||||
labelWidth -= 11
|
||||
}
|
||||
|
||||
// Add 20 px of padding, plus approximately 1.5 px of letter spacing per
|
||||
// character.
|
||||
messageWidth += 20 + 1.5 * message.length
|
||||
const leftWidth = hasLogo && !hasLabel ? 0 : labelWidth
|
||||
const rightWidth =
|
||||
hasLogo && !hasLabel ? messageWidth + labelWidth : messageWidth
|
||||
|
||||
labelColor = hasLabel || hasLogo ? labelColor : color
|
||||
|
||||
color = escapeXml(color)
|
||||
labelColor = escapeXml(labelColor)
|
||||
|
||||
let [leftLink, rightLink] = links
|
||||
leftLink = escapeXml(leftLink)
|
||||
rightLink = escapeXml(rightLink)
|
||||
const { hasLeftLink, hasRightLink } = hasLinks({ links })
|
||||
|
||||
const accessibleText = createAccessibleText({ label, message })
|
||||
|
||||
function renderLabelText() {
|
||||
const { textColor } = colorsForBackground(labelColor)
|
||||
const labelTextX = ((labelWidth + totalLogoWidth) / 2) * 10
|
||||
const labelTextLength = (labelWidth - (24 + totalLogoWidth)) * 10
|
||||
const escapedLabel = escapeXml(label)
|
||||
|
||||
const text = `<text fill="${textColor}" x="${labelTextX}" y="175" transform="scale(.1)" textLength="${labelTextLength}">${escapedLabel}</text>`
|
||||
|
||||
if (hasLeftLink && !shouldWrapBodyWithLink({ links })) {
|
||||
return `
|
||||
<a target="_blank" xlink:href="${leftLink}">
|
||||
<rect width="${leftWidth}" height="${height}" fill="rgba(0,0,0,0)"/>
|
||||
${text}
|
||||
</a>
|
||||
`
|
||||
} else {
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
function renderMessageText() {
|
||||
const { textColor } = colorsForBackground(color)
|
||||
|
||||
const text = `<text fill="${textColor}" x="${
|
||||
(labelWidth + messageWidth / 2) * 10
|
||||
}" y="175" font-weight="bold" transform="scale(.1)" textLength="${
|
||||
(messageWidth - 24) * 10
|
||||
}">
|
||||
${escapeXml(message)}</text>`
|
||||
|
||||
if (hasRightLink) {
|
||||
return `
|
||||
<a target="_blank" xlink:href="${rightLink}">
|
||||
<rect width="${rightWidth}" height="${height}" x="${labelWidth}" fill="rgba(0,0,0,0)"/>
|
||||
${text}
|
||||
</a>
|
||||
`
|
||||
} else {
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
return renderBadge(
|
||||
{
|
||||
links,
|
||||
leftWidth,
|
||||
rightWidth,
|
||||
accessibleText,
|
||||
height,
|
||||
},
|
||||
`
|
||||
<g shape-rendering="crispEdges">
|
||||
<rect width="${leftWidth}" height="${height}" fill="${labelColor}"/>
|
||||
<rect x="${leftWidth}" width="${rightWidth}" height="${height}" fill="${color}"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" ${fontFamily} text-rendering="geometricPrecision" font-size="100">
|
||||
${renderedLogo}
|
||||
${hasLabel ? renderLabelText() : ''}
|
||||
${renderMessageText()}
|
||||
</g>`
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
plastic: params => Plastic.render(params),
|
||||
flat: params => Flat.render(params),
|
||||
'flat-square': params => FlatSquare.render(params),
|
||||
social,
|
||||
'for-the-badge': forTheBadge,
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
'use strict'
|
||||
/**
|
||||
* @module badge-maker
|
||||
*/
|
||||
|
||||
const _makeBadge = require('./make-badge')
|
||||
|
||||
class ValidationError extends Error {}
|
||||
|
||||
function _validate(format) {
|
||||
if (format !== Object(format)) {
|
||||
throw new ValidationError('makeBadge takes an argument of type object')
|
||||
}
|
||||
|
||||
if (!('message' in format)) {
|
||||
throw new ValidationError('Field `message` is required')
|
||||
}
|
||||
|
||||
const stringFields = ['labelColor', 'color', 'message', 'label']
|
||||
stringFields.forEach(function (field) {
|
||||
if (field in format && typeof format[field] !== 'string') {
|
||||
throw new ValidationError(`Field \`${field}\` must be of type string`)
|
||||
}
|
||||
})
|
||||
|
||||
const styleValues = [
|
||||
'plastic',
|
||||
'flat',
|
||||
'flat-square',
|
||||
'for-the-badge',
|
||||
'social',
|
||||
]
|
||||
if ('style' in format && !styleValues.includes(format.style)) {
|
||||
throw new ValidationError(
|
||||
`Field \`style\` must be one of (${styleValues.toString()})`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function _clean(format) {
|
||||
const expectedKeys = ['label', 'message', 'labelColor', 'color', 'style']
|
||||
|
||||
const cleaned = {}
|
||||
Object.keys(format).forEach(key => {
|
||||
if (format[key] != null && expectedKeys.includes(key)) {
|
||||
cleaned[key] = format[key]
|
||||
} else {
|
||||
throw new ValidationError(
|
||||
`Unexpected field '${key}'. Allowed values are (${expectedKeys.toString()})`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
// Legacy.
|
||||
cleaned.label = cleaned.label || ''
|
||||
|
||||
return cleaned
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a badge
|
||||
*
|
||||
* @param {object} format Object specifying badge data
|
||||
* @param {string} format.label (Optional) Badge label (e.g: 'build')
|
||||
* @param {string} format.message (Required) Badge message (e.g: 'passing')
|
||||
* @param {string} format.labelColor (Optional) Label color
|
||||
* @param {string} format.color (Optional) Message color
|
||||
* @param {string} format.style (Optional) Visual style e.g: 'flat'
|
||||
* @returns {string} Badge in SVG format
|
||||
* @see https://github.com/badges/shields/tree/master/badge-maker/README.md
|
||||
*/
|
||||
function makeBadge(format) {
|
||||
_validate(format)
|
||||
const cleanedFormat = _clean(format)
|
||||
return _makeBadge(cleanedFormat)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeBadge,
|
||||
ValidationError,
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const { expect } = require('chai')
|
||||
const isSvg = require('is-svg')
|
||||
const { makeBadge, ValidationError } = require('.')
|
||||
|
||||
describe('makeBadge function', function () {
|
||||
it('should produce badge with valid input', function () {
|
||||
expect(
|
||||
makeBadge({
|
||||
label: 'build',
|
||||
message: 'passed',
|
||||
})
|
||||
).to.satisfy(isSvg)
|
||||
expect(
|
||||
makeBadge({
|
||||
message: 'passed',
|
||||
})
|
||||
).to.satisfy(isSvg)
|
||||
expect(
|
||||
makeBadge({
|
||||
label: 'build',
|
||||
message: 'passed',
|
||||
color: 'green',
|
||||
style: 'flat',
|
||||
})
|
||||
).to.satisfy(isSvg)
|
||||
})
|
||||
|
||||
it('should throw a ValidationError with invalid inputs', function () {
|
||||
;[null, undefined, 7, 'foo', 4.25].forEach(x => {
|
||||
console.log(x)
|
||||
expect(() => makeBadge(x)).to.throw(
|
||||
ValidationError,
|
||||
'makeBadge takes an argument of type object'
|
||||
)
|
||||
})
|
||||
expect(() => makeBadge({})).to.throw(
|
||||
ValidationError,
|
||||
'Field `message` is required'
|
||||
)
|
||||
expect(() => makeBadge({ label: 'build' })).to.throw(
|
||||
ValidationError,
|
||||
'Field `message` is required'
|
||||
)
|
||||
expect(() =>
|
||||
makeBadge({ label: 'build', message: 'passed', labelColor: 7 })
|
||||
).to.throw(ValidationError, 'Field `labelColor` must be of type string')
|
||||
expect(() =>
|
||||
makeBadge({ label: 'build', message: 'passed', format: 'png' })
|
||||
).to.throw(ValidationError, "Unexpected field 'format'")
|
||||
expect(() =>
|
||||
makeBadge({ label: 'build', message: 'passed', template: 'flat' })
|
||||
).to.throw(ValidationError, "Unexpected field 'template'")
|
||||
expect(() =>
|
||||
makeBadge({ label: 'build', message: 'passed', foo: 'bar' })
|
||||
).to.throw(ValidationError, "Unexpected field 'foo'")
|
||||
expect(() =>
|
||||
makeBadge({
|
||||
label: 'build',
|
||||
message: 'passed',
|
||||
style: 'something else',
|
||||
})
|
||||
).to.throw(
|
||||
ValidationError,
|
||||
'Field `style` must be one of (plastic,flat,flat-square,for-the-badge,social)'
|
||||
)
|
||||
expect(() =>
|
||||
makeBadge({ label: 'build', message: 'passed', style: 'popout' })
|
||||
).to.throw(
|
||||
ValidationError,
|
||||
'Field `style` must be one of (plastic,flat,flat-square,for-the-badge,social)'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,66 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const { normalizeColor, toSvgColor } = require('./color')
|
||||
const badgeRenderers = require('./badge-renderers')
|
||||
|
||||
function stripXmlWhitespace(xml) {
|
||||
return xml.replace(/>\s+/g, '>').replace(/<\s+/g, '<').trim()
|
||||
}
|
||||
|
||||
/*
|
||||
note: makeBadge() is fairly thinly wrapped so if we are making changes here
|
||||
it is likely this will impact on the package's public interface in index.js
|
||||
*/
|
||||
module.exports = function makeBadge({
|
||||
format,
|
||||
style = 'flat',
|
||||
label,
|
||||
message,
|
||||
color,
|
||||
labelColor,
|
||||
logo,
|
||||
logoPosition,
|
||||
logoWidth,
|
||||
links = ['', ''],
|
||||
}) {
|
||||
// String coercion and whitespace removal.
|
||||
label = `${label}`.trim()
|
||||
message = `${message}`.trim()
|
||||
|
||||
// This ought to be the responsibility of the server, not `makeBadge`.
|
||||
if (format === 'json') {
|
||||
return JSON.stringify({
|
||||
label,
|
||||
message,
|
||||
logoWidth,
|
||||
// Only call normalizeColor for the JSON case: this is handled
|
||||
// internally by toSvgColor in the SVG case.
|
||||
color: normalizeColor(color),
|
||||
labelColor: normalizeColor(labelColor),
|
||||
link: links,
|
||||
name: label,
|
||||
value: message,
|
||||
})
|
||||
}
|
||||
|
||||
const render = badgeRenderers[style]
|
||||
if (!render) {
|
||||
throw new Error(`Unknown badge style: '${style}'`)
|
||||
}
|
||||
|
||||
logoWidth = +logoWidth || (logo ? 14 : 0)
|
||||
|
||||
return stripXmlWhitespace(
|
||||
render({
|
||||
label,
|
||||
message,
|
||||
links,
|
||||
logo,
|
||||
logoPosition,
|
||||
logoWidth,
|
||||
logoPadding: logo && label.length ? 3 : 0,
|
||||
color: toSvgColor(color),
|
||||
labelColor: toSvgColor(labelColor),
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -1,583 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const { test, given, forCases } = require('sazerac')
|
||||
const { expect } = require('chai')
|
||||
const snapshot = require('snap-shot-it')
|
||||
const isSvg = require('is-svg')
|
||||
const prettier = require('prettier')
|
||||
const makeBadge = require('./make-badge')
|
||||
|
||||
function expectBadgeToMatchSnapshot(format) {
|
||||
snapshot(prettier.format(makeBadge(format), { parser: 'html' }))
|
||||
}
|
||||
|
||||
function testColor(color = '', colorAttr = 'color') {
|
||||
return JSON.parse(
|
||||
makeBadge({
|
||||
label: 'name',
|
||||
message: 'Bob',
|
||||
[colorAttr]: color,
|
||||
format: 'json',
|
||||
})
|
||||
).color
|
||||
}
|
||||
|
||||
describe('The badge generator', function () {
|
||||
describe('color test', function () {
|
||||
test(testColor, () => {
|
||||
// valid hex
|
||||
forCases([
|
||||
given('#4c1'),
|
||||
given('#4C1'),
|
||||
given('4C1'),
|
||||
given('4c1'),
|
||||
]).expect('#4c1')
|
||||
forCases([
|
||||
given('#abc123'),
|
||||
given('#ABC123'),
|
||||
given('abc123'),
|
||||
given('ABC123'),
|
||||
]).expect('#abc123')
|
||||
// valid rgb(a)
|
||||
given('rgb(0,128,255)').expect('rgb(0,128,255)')
|
||||
given('rgb(220,128,255,0.5)').expect('rgb(220,128,255,0.5)')
|
||||
given('rgba(0,0,255)').expect('rgba(0,0,255)')
|
||||
given('rgba(0,128,255,0)').expect('rgba(0,128,255,0)')
|
||||
// valid hsl(a)
|
||||
given('hsl(100, 56%, 10%)').expect('hsl(100, 56%, 10%)')
|
||||
given('hsl(360,50%,50%,0.5)').expect('hsl(360,50%,50%,0.5)')
|
||||
given('hsla(25,20%,0%,0.1)').expect('hsla(25,20%,0%,0.1)')
|
||||
given('hsla(0,50%,101%)').expect('hsla(0,50%,101%)')
|
||||
// CSS named color.
|
||||
given('papayawhip').expect('papayawhip')
|
||||
// Shields named color.
|
||||
given('red').expect('red')
|
||||
given('green').expect('green')
|
||||
given('blue').expect('blue')
|
||||
given('yellow').expect('yellow')
|
||||
// Semantic color alias
|
||||
given('success').expect('brightgreen')
|
||||
given('informational').expect('blue')
|
||||
|
||||
forCases(
|
||||
// invalid hex
|
||||
given('#123red'), // contains letter above F
|
||||
given('#red'), // contains letter above F
|
||||
// neither a css named color nor colorscheme
|
||||
given('notacolor'),
|
||||
given('bluish'),
|
||||
given('almostred'),
|
||||
given('brightmaroon'),
|
||||
given('cactus')
|
||||
).expect(undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('color aliases', function () {
|
||||
test(testColor, () => {
|
||||
forCases([given('#4c1', 'color')]).expect('#4c1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SVG', function () {
|
||||
it('should produce SVG', function () {
|
||||
expect(makeBadge({ label: 'cactus', message: 'grown', format: 'svg' }))
|
||||
.to.satisfy(isSvg)
|
||||
.and.to.include('cactus')
|
||||
.and.to.include('grown')
|
||||
})
|
||||
|
||||
it('should match snapshot', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('JSON', function () {
|
||||
it('should produce the expected JSON', function () {
|
||||
const json = makeBadge({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'json',
|
||||
links: ['https://example.com/', 'https://other.example.com/'],
|
||||
})
|
||||
expect(JSON.parse(json)).to.deep.equal({
|
||||
name: 'cactus',
|
||||
label: 'cactus',
|
||||
value: 'grown',
|
||||
message: 'grown',
|
||||
link: ['https://example.com/', 'https://other.example.com/'],
|
||||
})
|
||||
})
|
||||
|
||||
it('should replace undefined svg badge style with "flat"', function () {
|
||||
const jsonBadgeWithUnknownStyle = makeBadge({
|
||||
label: 'name',
|
||||
message: 'Bob',
|
||||
format: 'svg',
|
||||
})
|
||||
const jsonBadgeWithDefaultStyle = makeBadge({
|
||||
label: 'name',
|
||||
message: 'Bob',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
})
|
||||
expect(jsonBadgeWithUnknownStyle)
|
||||
.to.equal(jsonBadgeWithDefaultStyle)
|
||||
.and.to.satisfy(isSvg)
|
||||
})
|
||||
|
||||
it('should fail with unknown svg badge style', function () {
|
||||
expect(() =>
|
||||
makeBadge({
|
||||
label: 'name',
|
||||
message: 'Bob',
|
||||
format: 'svg',
|
||||
style: 'unknown_style',
|
||||
})
|
||||
).to.throw(Error, "Unknown badge style: 'unknown_style'")
|
||||
})
|
||||
})
|
||||
|
||||
describe('"flat" template badge generation', function () {
|
||||
it('should match snapshots: message/label, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo and labelColor', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with links', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
links: ['https://shields.io/', 'https://www.google.co.uk/'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('"flat-square" template badge generation', function () {
|
||||
it('should match snapshots: message/label, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo and labelColor', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with links', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat-square',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
links: ['https://shields.io/', 'https://www.google.co.uk/'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('"plastic" template badge generation', function () {
|
||||
it('should match snapshots: message/label, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo and labelColor', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with links', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'plastic',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
links: ['https://shields.io/', 'https://www.google.co.uk/'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('"for-the-badge" template badge generation', function () {
|
||||
// https://github.com/badges/shields/issues/1280
|
||||
it('numbers should produce a string', function () {
|
||||
expect(
|
||||
makeBadge({
|
||||
label: 1998,
|
||||
message: 1999,
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
})
|
||||
)
|
||||
.to.include('1998')
|
||||
.and.to.include('1999')
|
||||
})
|
||||
|
||||
it('lowercase/mixedcase string should produce uppercase string', function () {
|
||||
expect(
|
||||
makeBadge({
|
||||
label: 'Label',
|
||||
message: '1 string',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
})
|
||||
)
|
||||
.to.include('LABEL')
|
||||
.and.to.include('1 STRING')
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo and labelColor', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with links', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
links: ['https://shields.io/', 'https://www.google.co.uk/'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('"social" template badge generation', function () {
|
||||
it('should produce capitalized string for badge key', function () {
|
||||
expect(
|
||||
makeBadge({
|
||||
label: 'some-key',
|
||||
message: 'some-value',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
})
|
||||
)
|
||||
.to.include('Some-key')
|
||||
.and.to.include('some-value')
|
||||
})
|
||||
|
||||
// https://github.com/badges/shields/issues/1606
|
||||
it('should handle empty strings used as badge keys', function () {
|
||||
expect(
|
||||
makeBadge({
|
||||
label: '',
|
||||
message: 'some-value',
|
||||
format: 'json',
|
||||
style: 'social',
|
||||
})
|
||||
)
|
||||
.to.include('""')
|
||||
.and.to.include('some-value')
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, no logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message only, with logo and labelColor', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: '',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
|
||||
it('should match snapshots: message/label, with links', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'social',
|
||||
color: '#b3e',
|
||||
labelColor: '#0f0',
|
||||
links: ['https://shields.io/', 'https://www.google.co.uk/'],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('badges with logos should always produce the same badge', function () {
|
||||
it('badge with logo', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'label',
|
||||
message: 'message',
|
||||
format: 'svg',
|
||||
logo: 'data:image/svg+xml;base64,PHN2ZyB4bWxu',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('text colors', function () {
|
||||
it('should use black text when the label color is light', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'flat',
|
||||
color: '#000',
|
||||
labelColor: '#f3f3f3',
|
||||
})
|
||||
})
|
||||
|
||||
it('should use black text when the message color is light', function () {
|
||||
expectBadgeToMatchSnapshot({
|
||||
label: 'cactus',
|
||||
message: 'grown',
|
||||
format: 'svg',
|
||||
style: 'for-the-badge',
|
||||
color: '#e2ffe1',
|
||||
labelColor: '#000',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -6,22 +6,13 @@ public:
|
||||
metrics:
|
||||
prometheus:
|
||||
enabled: 'METRICS_PROMETHEUS_ENABLED'
|
||||
endpointEnabled: 'METRICS_PROMETHEUS_ENDPOINT_ENABLED'
|
||||
influx:
|
||||
enabled: 'METRICS_INFLUX_ENABLED'
|
||||
url: 'METRICS_INFLUX_URL'
|
||||
timeoutMilliseconds: 'METRICS_INFLUX_TIMEOUT_MILLISECONDS'
|
||||
intervalSeconds: 'METRICS_INFLUX_INTERVAL_SECONDS'
|
||||
instanceIdFrom: 'METRICS_INFLUX_INSTANCE_ID_FROM'
|
||||
instanceIdEnvVarName: 'METRICS_INFLUX_INSTANCE_ID_ENV_VAR_NAME'
|
||||
envLabel: 'METRICS_INFLUX_ENV_LABEL'
|
||||
|
||||
ssl:
|
||||
isSecure: 'HTTPS'
|
||||
key: 'HTTPS_KEY'
|
||||
cert: 'HTTPS_CRT'
|
||||
|
||||
redirectUrl: 'REDIRECT_URI'
|
||||
redirectUri: 'REDIRECT_URI'
|
||||
|
||||
rasterUrl: 'RASTER_URL'
|
||||
|
||||
@@ -30,30 +21,20 @@ public:
|
||||
__name: 'ALLOWED_ORIGIN'
|
||||
__format: 'json'
|
||||
|
||||
persistence:
|
||||
dir: 'PERSISTENCE_DIR'
|
||||
|
||||
services:
|
||||
bitbucketServer:
|
||||
authorizedOrigins: 'BITBUCKET_SERVER_ORIGINS'
|
||||
drone:
|
||||
authorizedOrigins: 'DRONE_ORIGINS'
|
||||
github:
|
||||
baseUri: 'GITHUB_URL'
|
||||
debug:
|
||||
enabled: 'GITHUB_DEBUG_ENABLED'
|
||||
intervalSeconds: 'GITHUB_DEBUG_INTERVAL_SECONDS'
|
||||
jenkins:
|
||||
authorizedOrigins: 'JENKINS_ORIGINS'
|
||||
jira:
|
||||
authorizedOrigins: 'JIRA_ORIGINS'
|
||||
nexus:
|
||||
authorizedOrigins: 'NEXUS_ORIGINS'
|
||||
npm:
|
||||
authorizedOrigins: 'NPM_ORIGINS'
|
||||
sonar:
|
||||
authorizedOrigins: 'SONAR_ORIGINS'
|
||||
teamcity:
|
||||
authorizedOrigins: 'TEAMCITY_ORIGINS'
|
||||
trace: 'TRACE_SERVICES'
|
||||
|
||||
profiling:
|
||||
makeBadge: 'PROFILE_MAKE_BADGE'
|
||||
|
||||
cacheHeaders:
|
||||
defaultCacheLengthSeconds: 'BADGE_MAX_AGE_SECONDS'
|
||||
|
||||
@@ -61,17 +42,10 @@ public:
|
||||
|
||||
fetchLimit: 'FETCH_LIMIT'
|
||||
|
||||
requireCloudflare: 'REQUIRE_CLOUDFLARE'
|
||||
|
||||
private:
|
||||
azure_devops_token: 'AZURE_DEVOPS_TOKEN'
|
||||
bintray_user: 'BINTRAY_USER'
|
||||
bintray_apikey: 'BINTRAY_API_KEY'
|
||||
bitbucket_username: 'BITBUCKET_USER'
|
||||
bitbucket_password: 'BITBUCKET_PASS'
|
||||
bitbucket_server_username: 'BITBUCKET_SERVER_USER'
|
||||
bitbucket_server_password: 'BITBUCKET_SERVER_PASS'
|
||||
discord_bot_token: 'DISCORD_BOT_TOKEN'
|
||||
drone_token: 'DRONE_TOKEN'
|
||||
gh_client_id: 'GH_CLIENT_ID'
|
||||
gh_client_secret: 'GH_CLIENT_SECRET'
|
||||
@@ -89,11 +63,6 @@ private:
|
||||
sl_insight_userUuid: 'SL_INSIGHT_USER_UUID'
|
||||
sl_insight_apiToken: 'SL_INSIGHT_API_TOKEN'
|
||||
sonarqube_token: 'SONARQUBE_TOKEN'
|
||||
teamcity_user: 'TEAMCITY_USER'
|
||||
teamcity_pass: 'TEAMCITY_PASS'
|
||||
twitch_client_id: 'TWITCH_CLIENT_ID'
|
||||
twitch_client_secret: 'TWITCH_CLIENT_SECRET'
|
||||
wheelmap_token: 'WHEELMAP_TOKEN'
|
||||
influx_username: 'INFLUX_USERNAME'
|
||||
influx_password: 'INFLUX_PASSWORD'
|
||||
youtube_api_key: 'YOUTUBE_API_KEY'
|
||||
|
||||
@@ -5,17 +5,16 @@ public:
|
||||
metrics:
|
||||
prometheus:
|
||||
enabled: false
|
||||
endpointEnabled: false
|
||||
influx:
|
||||
enabled: false
|
||||
timeoutMilliseconds: 1000
|
||||
intervalSeconds: 15
|
||||
|
||||
ssl:
|
||||
isSecure: false
|
||||
|
||||
cors:
|
||||
allowedOrigin: []
|
||||
|
||||
persistence:
|
||||
dir: './private'
|
||||
|
||||
services:
|
||||
github:
|
||||
baseUri: 'https://api.github.com/'
|
||||
@@ -24,6 +23,9 @@ public:
|
||||
intervalSeconds: 200
|
||||
trace: false
|
||||
|
||||
profiling:
|
||||
makeBadge: false
|
||||
|
||||
cacheHeaders:
|
||||
defaultCacheLengthSeconds: 120
|
||||
|
||||
@@ -33,6 +35,4 @@ public:
|
||||
|
||||
fetchLimit: '10MB'
|
||||
|
||||
requireCloudflare: false
|
||||
|
||||
private: {}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
private:
|
||||
# These are the keys which are set on the production servers.
|
||||
discord_bot_token: ...
|
||||
bintray_user: ...
|
||||
bintray_apikey: ...
|
||||
gh_client_id: ...
|
||||
gh_client_secret: ...
|
||||
redis_url: ...
|
||||
sentry_dsn: ...
|
||||
shields_secret: ...
|
||||
sl_insight_userUuid: ...
|
||||
@@ -11,4 +10,3 @@ private:
|
||||
twitch_client_id: ...
|
||||
twitch_client_secret: ...
|
||||
wheelmap_token: ...
|
||||
youtube_api_key: ...
|
||||
|
||||
@@ -8,4 +8,3 @@ private:
|
||||
twitch_client_id: '...'
|
||||
twitch_client_secret: '...'
|
||||
wheelmap_token: '...'
|
||||
youtube_api_key: '...'
|
||||
|
||||
@@ -2,12 +2,6 @@ public:
|
||||
metrics:
|
||||
prometheus:
|
||||
enabled: true
|
||||
influx:
|
||||
enabled: true
|
||||
url: https://metrics.shields.io/telegraf
|
||||
instanceIdFrom: env-var
|
||||
instanceIdEnvVarName: HEROKU_DYNO_ID
|
||||
envLabel: shields-production
|
||||
|
||||
ssl:
|
||||
isSecure: true
|
||||
@@ -15,4 +9,10 @@ public:
|
||||
cors:
|
||||
allowedOrigin: ['http://shields.io', 'https://shields.io']
|
||||
|
||||
redirectUrl: 'https://shields.io/'
|
||||
|
||||
rasterUrl: 'https://raster.shields.io'
|
||||
|
||||
private:
|
||||
# These are not really private; they should be moved to `public`.
|
||||
shields_ips: ['192.99.59.72', '51.254.114.150', '149.56.96.133']
|
||||
|
||||
4
core/badge-urls/make-badge-url.d.ts
vendored
4
core/badge-urls/make-badge-url.d.ts
vendored
@@ -38,22 +38,18 @@ export function staticBadgeUrl({
|
||||
baseUrl,
|
||||
label,
|
||||
message,
|
||||
labelColor,
|
||||
color,
|
||||
style,
|
||||
namedLogo,
|
||||
format,
|
||||
links,
|
||||
}: {
|
||||
baseUrl?: string
|
||||
label: string
|
||||
message: string
|
||||
labelColor?: string
|
||||
color?: string
|
||||
style?: string
|
||||
namedLogo?: string
|
||||
format?: string
|
||||
links?: string[]
|
||||
}): string
|
||||
|
||||
export function queryStringStaticBadgeUrl({
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
const { URL } = require('url')
|
||||
const queryString = require('query-string')
|
||||
const { compile } = require('path-to-regexp')
|
||||
const pathToRegexp = require('path-to-regexp')
|
||||
|
||||
function badgeUrlFromPath({
|
||||
baseUrl = '',
|
||||
@@ -33,10 +33,9 @@ function badgeUrlFromPattern({
|
||||
format = '',
|
||||
longCache = false,
|
||||
}) {
|
||||
const toPath = compile(pattern, {
|
||||
const toPath = pathToRegexp.compile(pattern, {
|
||||
strict: true,
|
||||
sensitive: true,
|
||||
encode: encodeURIComponent,
|
||||
})
|
||||
|
||||
const path = toPath(namedParams)
|
||||
@@ -59,19 +58,15 @@ function staticBadgeUrl({
|
||||
baseUrl = '',
|
||||
label,
|
||||
message,
|
||||
labelColor,
|
||||
color = 'lightgray',
|
||||
style,
|
||||
namedLogo,
|
||||
format = '',
|
||||
links = [],
|
||||
}) {
|
||||
const path = [label, message, color].map(encodeField).join('-')
|
||||
const outQueryString = queryString.stringify({
|
||||
labelColor,
|
||||
style,
|
||||
logo: namedLogo,
|
||||
link: links,
|
||||
})
|
||||
const outExt = format.length ? `.${format}` : ''
|
||||
const suffix = outQueryString ? `?${outQueryString}` : ''
|
||||
|
||||
@@ -10,7 +10,7 @@ const {
|
||||
dynamicBadgeUrl,
|
||||
} = require('./make-badge-url')
|
||||
|
||||
describe('Badge URL generation functions', function () {
|
||||
describe('Badge URL generation functions', function() {
|
||||
test(badgeUrlFromPath, () => {
|
||||
given({
|
||||
baseUrl: 'http://example.com',
|
||||
|
||||
@@ -5,8 +5,11 @@
|
||||
function escapeFormat(t) {
|
||||
return (
|
||||
t
|
||||
// Single underscore.
|
||||
.replace(/(^|[^_])((?:__)*)_(?!_)/g, '$1$2 ')
|
||||
// Inline single underscore.
|
||||
.replace(/([^_])_([^_])/g, '$1 $2')
|
||||
// Leading or trailing underscore.
|
||||
.replace(/([^_])_$/, '$1 ')
|
||||
.replace(/^_([^_])/, ' $1')
|
||||
// Double underscore and double dash.
|
||||
.replace(/__/g, '_')
|
||||
.replace(/--/g, '-')
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
const { test, given } = require('sazerac')
|
||||
const { escapeFormat } = require('./path-helpers')
|
||||
|
||||
describe('Badge URL helper functions', function () {
|
||||
test(escapeFormat, () => {
|
||||
given('_single leading underscore').expect(' single leading underscore')
|
||||
given('single trailing underscore_').expect('single trailing underscore ')
|
||||
given('__double leading underscores').expect('_double leading underscores')
|
||||
given('double trailing underscores__').expect(
|
||||
'double trailing underscores_'
|
||||
)
|
||||
given('treble___underscores').expect('treble_ underscores')
|
||||
given('fourfold____underscores').expect('fourfold__underscores')
|
||||
given('double--dashes').expect('double-dashes')
|
||||
given('treble---dashes').expect('treble--dashes')
|
||||
given('fourfold----dashes').expect('fourfold--dashes')
|
||||
given('once_in_a_blue--moon').expect('once in a blue-moon')
|
||||
})
|
||||
})
|
||||
@@ -1,68 +1,34 @@
|
||||
'use strict'
|
||||
|
||||
const { URL } = require('url')
|
||||
const { InvalidParameter } = require('./errors')
|
||||
|
||||
class AuthHelper {
|
||||
constructor(
|
||||
{
|
||||
userKey,
|
||||
passKey,
|
||||
authorizedOrigins,
|
||||
serviceKey,
|
||||
isRequired = false,
|
||||
defaultToEmptyStringForUser = false,
|
||||
},
|
||||
config
|
||||
privateConfig
|
||||
) {
|
||||
if (!userKey && !passKey) {
|
||||
throw Error('Expected userKey or passKey to be set')
|
||||
}
|
||||
|
||||
if (!authorizedOrigins && !serviceKey) {
|
||||
throw Error('Expected authorizedOrigins or serviceKey to be set')
|
||||
}
|
||||
|
||||
this._userKey = userKey
|
||||
this._passKey = passKey
|
||||
if (userKey) {
|
||||
this._user = config.private[userKey]
|
||||
this.user = privateConfig[userKey]
|
||||
} else {
|
||||
this._user = defaultToEmptyStringForUser ? '' : undefined
|
||||
this.user = defaultToEmptyStringForUser ? '' : undefined
|
||||
}
|
||||
this._pass = passKey ? config.private[passKey] : undefined
|
||||
this.pass = passKey ? privateConfig[passKey] : undefined
|
||||
this.isRequired = isRequired
|
||||
|
||||
if (serviceKey !== undefined && !(serviceKey in config.public.services)) {
|
||||
// Keep this as its own error, as it's useful to the programmer as they're
|
||||
// getting auth set up.
|
||||
throw Error(`Service key ${serviceKey} was missing from config schema`)
|
||||
}
|
||||
|
||||
let requireStrictSsl, requireStrictSslToAuthenticate
|
||||
if (serviceKey === undefined) {
|
||||
requireStrictSsl = true
|
||||
requireStrictSslToAuthenticate = true
|
||||
} else {
|
||||
;({
|
||||
authorizedOrigins,
|
||||
requireStrictSsl = true,
|
||||
requireStrictSslToAuthenticate = true,
|
||||
} = config.public.services[serviceKey])
|
||||
}
|
||||
if (!Array.isArray(authorizedOrigins)) {
|
||||
throw Error('Expected authorizedOrigins to be an array of origins')
|
||||
}
|
||||
this._authorizedOrigins = authorizedOrigins
|
||||
this._requireStrictSsl = requireStrictSsl
|
||||
this._requireStrictSslToAuthenticate = requireStrictSslToAuthenticate
|
||||
}
|
||||
|
||||
get isConfigured() {
|
||||
return (
|
||||
this._authorizedOrigins.length > 0 &&
|
||||
(this._userKey ? Boolean(this._user) : true) &&
|
||||
(this._passKey ? Boolean(this._pass) : true)
|
||||
(this._userKey ? Boolean(this.user) : true) &&
|
||||
(this._passKey ? Boolean(this.pass) : true)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -70,142 +36,19 @@ class AuthHelper {
|
||||
if (this.isRequired) {
|
||||
return this.isConfigured
|
||||
} else {
|
||||
const configIsEmpty = !this._user && !this._pass
|
||||
const configIsEmpty = !this.user && !this.pass
|
||||
return this.isConfigured || configIsEmpty
|
||||
}
|
||||
}
|
||||
|
||||
static _isInsecureSslRequest({ options = {} }) {
|
||||
const { strictSSL = true } = options
|
||||
return strictSSL !== true
|
||||
}
|
||||
|
||||
enforceStrictSsl({ options = {} }) {
|
||||
if (
|
||||
this._requireStrictSsl &&
|
||||
this.constructor._isInsecureSslRequest({ options })
|
||||
) {
|
||||
throw new InvalidParameter({ prettyMessage: 'strict ssl is required' })
|
||||
}
|
||||
}
|
||||
|
||||
shouldAuthenticateRequest({ url, options = {} }) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = new URL(url)
|
||||
} catch (e) {
|
||||
throw new InvalidParameter({ prettyMessage: 'invalid url parameter' })
|
||||
}
|
||||
|
||||
const { protocol, host } = parsed
|
||||
const origin = `${protocol}//${host}`
|
||||
const originViolation = !this._authorizedOrigins.includes(origin)
|
||||
|
||||
const strictSslCheckViolation =
|
||||
this._requireStrictSslToAuthenticate &&
|
||||
this.constructor._isInsecureSslRequest({ options })
|
||||
|
||||
return this.isConfigured && !originViolation && !strictSslCheckViolation
|
||||
}
|
||||
|
||||
get _basicAuth() {
|
||||
const { _user: user, _pass: pass } = this
|
||||
get basicAuth() {
|
||||
const { user, pass } = this
|
||||
return this.isConfigured ? { user, pass } : undefined
|
||||
}
|
||||
|
||||
/*
|
||||
* Helper function for `withBasicAuth()` and friends.
|
||||
*/
|
||||
_withAnyAuth(requestParams, mergeAuthFn) {
|
||||
this.enforceStrictSsl(requestParams)
|
||||
|
||||
const shouldAuthenticate = this.shouldAuthenticateRequest(requestParams)
|
||||
if (this.isRequired && !shouldAuthenticate) {
|
||||
throw new InvalidParameter({
|
||||
prettyMessage: 'requested origin not authorized',
|
||||
})
|
||||
}
|
||||
|
||||
return shouldAuthenticate ? mergeAuthFn(requestParams) : requestParams
|
||||
}
|
||||
|
||||
static _mergeAuth(requestParams, auth) {
|
||||
const { options, ...rest } = requestParams
|
||||
return {
|
||||
options: {
|
||||
auth,
|
||||
...options,
|
||||
},
|
||||
...rest,
|
||||
}
|
||||
}
|
||||
|
||||
withBasicAuth(requestParams) {
|
||||
return this._withAnyAuth(requestParams, requestParams =>
|
||||
this.constructor._mergeAuth(requestParams, this._basicAuth)
|
||||
)
|
||||
}
|
||||
|
||||
_bearerAuthHeader(bearerKey) {
|
||||
const { _pass: pass } = this
|
||||
return this.isConfigured
|
||||
? { Authorization: `${bearerKey} ${pass}` }
|
||||
: undefined
|
||||
}
|
||||
|
||||
static _mergeHeaders(requestParams, headers) {
|
||||
const {
|
||||
options: { headers: existingHeaders, ...restOptions } = {},
|
||||
...rest
|
||||
} = requestParams
|
||||
return {
|
||||
options: {
|
||||
headers: {
|
||||
...existingHeaders,
|
||||
...headers,
|
||||
},
|
||||
...restOptions,
|
||||
},
|
||||
...rest,
|
||||
}
|
||||
}
|
||||
|
||||
withBearerAuthHeader(
|
||||
requestParams,
|
||||
bearerKey = 'Bearer' // lgtm [js/hardcoded-credentials]
|
||||
) {
|
||||
return this._withAnyAuth(requestParams, requestParams =>
|
||||
this.constructor._mergeHeaders(
|
||||
requestParams,
|
||||
this._bearerAuthHeader(bearerKey)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
static _mergeQueryParams(requestParams, query) {
|
||||
const {
|
||||
options: { qs: existingQuery, ...restOptions } = {},
|
||||
...rest
|
||||
} = requestParams
|
||||
return {
|
||||
options: {
|
||||
qs: {
|
||||
...existingQuery,
|
||||
...query,
|
||||
},
|
||||
...restOptions,
|
||||
},
|
||||
...rest,
|
||||
}
|
||||
}
|
||||
|
||||
withQueryStringAuth({ userKey, passKey }, requestParams) {
|
||||
return this._withAnyAuth(requestParams, requestParams =>
|
||||
this.constructor._mergeQueryParams(requestParams, {
|
||||
...(userKey ? { [userKey]: this._user } : undefined),
|
||||
...(passKey ? { [passKey]: this._pass } : undefined),
|
||||
})
|
||||
)
|
||||
get bearerAuthHeader() {
|
||||
const { pass } = this
|
||||
return this.isConfigured ? { Authorization: `Bearer ${pass}` } : undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,42 +3,18 @@
|
||||
const { expect } = require('chai')
|
||||
const { test, given, forCases } = require('sazerac')
|
||||
const { AuthHelper } = require('./auth-helper')
|
||||
const { InvalidParameter } = require('./errors')
|
||||
|
||||
describe('AuthHelper', function () {
|
||||
describe('constructor checks', function () {
|
||||
it('throws without userKey or passKey', function () {
|
||||
expect(() => new AuthHelper({}, {})).to.throw(
|
||||
Error,
|
||||
'Expected userKey or passKey to be set'
|
||||
)
|
||||
})
|
||||
it('throws without serviceKey or authorizedOrigins', function () {
|
||||
expect(
|
||||
() => new AuthHelper({ userKey: 'myci_user', passKey: 'myci_pass' }, {})
|
||||
).to.throw(Error, 'Expected authorizedOrigins or serviceKey to be set')
|
||||
})
|
||||
it('throws when authorizedOrigins is not an array', function () {
|
||||
expect(
|
||||
() =>
|
||||
new AuthHelper(
|
||||
{
|
||||
userKey: 'myci_user',
|
||||
passKey: 'myci_pass',
|
||||
authorizedOrigins: true,
|
||||
},
|
||||
{ private: {} }
|
||||
)
|
||||
).to.throw(Error, 'Expected authorizedOrigins to be an array of origins')
|
||||
})
|
||||
describe('AuthHelper', function() {
|
||||
it('throws without userKey or passKey', function() {
|
||||
expect(() => new AuthHelper({}, {})).to.throw(
|
||||
Error,
|
||||
'Expected userKey or passKey to be set'
|
||||
)
|
||||
})
|
||||
|
||||
describe('isValid', function () {
|
||||
describe('isValid', function() {
|
||||
function validate(config, privateConfig) {
|
||||
return new AuthHelper(
|
||||
{ authorizedOrigins: ['https://example.test'], ...config },
|
||||
{ private: privateConfig }
|
||||
).isValid
|
||||
return new AuthHelper(config, privateConfig).isValid
|
||||
}
|
||||
test(validate, () => {
|
||||
forCases([
|
||||
@@ -89,12 +65,9 @@ describe('AuthHelper', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('_basicAuth', function () {
|
||||
describe('basicAuth', function() {
|
||||
function validate(config, privateConfig) {
|
||||
return new AuthHelper(
|
||||
{ authorizedOrigins: ['https://example.test'], ...config },
|
||||
{ private: privateConfig }
|
||||
)._basicAuth
|
||||
return new AuthHelper(config, privateConfig).basicAuth
|
||||
}
|
||||
test(validate, () => {
|
||||
forCases([
|
||||
@@ -127,250 +100,4 @@ describe('AuthHelper', function () {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('_isInsecureSslRequest', function () {
|
||||
test(AuthHelper._isInsecureSslRequest, () => {
|
||||
forCases([
|
||||
given({ url: 'http://example.test' }),
|
||||
given({ url: 'http://example.test', options: {} }),
|
||||
given({ url: 'http://example.test', options: { strictSSL: true } }),
|
||||
given({
|
||||
url: 'http://example.test',
|
||||
options: { strictSSL: undefined },
|
||||
}),
|
||||
]).expect(false)
|
||||
given({
|
||||
url: 'http://example.test',
|
||||
options: { strictSSL: false },
|
||||
}).expect(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('enforceStrictSsl', function () {
|
||||
const authConfig = {
|
||||
userKey: 'myci_user',
|
||||
passKey: 'myci_pass',
|
||||
serviceKey: 'myci',
|
||||
}
|
||||
|
||||
context('by default', function () {
|
||||
const authHelper = new AuthHelper(authConfig, {
|
||||
public: {
|
||||
services: { myci: { authorizedOrigins: ['http://myci.test'] } },
|
||||
},
|
||||
private: { myci_user: 'admin', myci_pass: 'abc123' },
|
||||
})
|
||||
it('does not throw for secure requests', function () {
|
||||
expect(() => authHelper.enforceStrictSsl({})).not.to.throw()
|
||||
})
|
||||
it('throws for insecure requests', function () {
|
||||
expect(() =>
|
||||
authHelper.enforceStrictSsl({ options: { strictSSL: false } })
|
||||
).to.throw(InvalidParameter)
|
||||
})
|
||||
})
|
||||
|
||||
context("when strict SSL isn't required", function () {
|
||||
const authHelper = new AuthHelper(authConfig, {
|
||||
public: {
|
||||
services: {
|
||||
myci: {
|
||||
authorizedOrigins: ['http://myci.test'],
|
||||
requireStrictSsl: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
private: { myci_user: 'admin', myci_pass: 'abc123' },
|
||||
})
|
||||
it('does not throw for secure requests', function () {
|
||||
expect(() => authHelper.enforceStrictSsl({})).not.to.throw()
|
||||
})
|
||||
it('does not throw for insecure requests', function () {
|
||||
expect(() =>
|
||||
authHelper.enforceStrictSsl({ options: { strictSSL: false } })
|
||||
).not.to.throw()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldAuthenticateRequest', function () {
|
||||
const authConfig = {
|
||||
userKey: 'myci_user',
|
||||
passKey: 'myci_pass',
|
||||
serviceKey: 'myci',
|
||||
}
|
||||
|
||||
context('by default', function () {
|
||||
const authHelper = new AuthHelper(authConfig, {
|
||||
public: {
|
||||
services: {
|
||||
myci: {
|
||||
authorizedOrigins: ['https://myci.test'],
|
||||
},
|
||||
},
|
||||
},
|
||||
private: { myci_user: 'admin', myci_pass: 'abc123' },
|
||||
})
|
||||
const shouldAuthenticateRequest = requestOptions =>
|
||||
authHelper.shouldAuthenticateRequest(requestOptions)
|
||||
describe('a secure request to an authorized origin', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
given({ url: 'https://myci.test/api' }).expect(true)
|
||||
})
|
||||
})
|
||||
describe('an insecure request', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
given({
|
||||
url: 'https://myci.test/api',
|
||||
options: { strictSSL: false },
|
||||
}).expect(false)
|
||||
})
|
||||
})
|
||||
describe('a request to an unauthorized origin', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
forCases([
|
||||
given({ url: 'http://myci.test/api' }),
|
||||
given({ url: 'https://myci.test:12345/api' }),
|
||||
given({ url: 'https://other.test/api' }),
|
||||
]).expect(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
context('when auth over insecure SSL is allowed', function () {
|
||||
const authHelper = new AuthHelper(authConfig, {
|
||||
public: {
|
||||
services: {
|
||||
myci: {
|
||||
authorizedOrigins: ['https://myci.test'],
|
||||
requireStrictSslToAuthenticate: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
private: { myci_user: 'admin', myci_pass: 'abc123' },
|
||||
})
|
||||
const shouldAuthenticateRequest = requestOptions =>
|
||||
authHelper.shouldAuthenticateRequest(requestOptions)
|
||||
describe('a secure request to an authorized origin', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
given({ url: 'https://myci.test' }).expect(true)
|
||||
})
|
||||
})
|
||||
describe('an insecure request', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
given({
|
||||
url: 'https://myci.test',
|
||||
options: { strictSSL: false },
|
||||
}).expect(true)
|
||||
})
|
||||
})
|
||||
describe('a request to an unauthorized origin', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
forCases([
|
||||
given({ url: 'http://myci.test' }),
|
||||
given({ url: 'https://myci.test:12345/' }),
|
||||
given({ url: 'https://other.test' }),
|
||||
]).expect(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
context('when the service is partly configured', function () {
|
||||
const authHelper = new AuthHelper(authConfig, {
|
||||
public: {
|
||||
services: {
|
||||
myci: {
|
||||
authorizedOrigins: ['https://myci.test'],
|
||||
requireStrictSslToAuthenticate: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
private: { myci_user: 'admin' },
|
||||
})
|
||||
const shouldAuthenticateRequest = requestOptions =>
|
||||
authHelper.shouldAuthenticateRequest(requestOptions)
|
||||
describe('a secure request to an authorized origin', function () {
|
||||
test(shouldAuthenticateRequest, () => {
|
||||
given({ url: 'https://myci.test' }).expect(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('withBasicAuth', function () {
|
||||
const authHelper = new AuthHelper(
|
||||
{
|
||||
userKey: 'myci_user',
|
||||
passKey: 'myci_pass',
|
||||
serviceKey: 'myci',
|
||||
},
|
||||
{
|
||||
public: {
|
||||
services: {
|
||||
myci: {
|
||||
authorizedOrigins: ['https://myci.test'],
|
||||
},
|
||||
},
|
||||
},
|
||||
private: { myci_user: 'admin', myci_pass: 'abc123' },
|
||||
}
|
||||
)
|
||||
const withBasicAuth = requestOptions =>
|
||||
authHelper.withBasicAuth(requestOptions)
|
||||
|
||||
describe('authenticates a secure request to an authorized origin', function () {
|
||||
test(withBasicAuth, () => {
|
||||
given({
|
||||
url: 'https://myci.test/api',
|
||||
}).expect({
|
||||
url: 'https://myci.test/api',
|
||||
options: {
|
||||
auth: { user: 'admin', pass: 'abc123' },
|
||||
},
|
||||
})
|
||||
given({
|
||||
url: 'https://myci.test/api',
|
||||
options: {
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
}).expect({
|
||||
url: 'https://myci.test/api',
|
||||
options: {
|
||||
headers: { Accept: 'application/json' },
|
||||
auth: { user: 'admin', pass: 'abc123' },
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('does not authenticate a request to an unauthorized origin', function () {
|
||||
test(withBasicAuth, () => {
|
||||
given({
|
||||
url: 'https://other.test/api',
|
||||
}).expect({
|
||||
url: 'https://other.test/api',
|
||||
})
|
||||
given({
|
||||
url: 'https://other.test/api',
|
||||
options: {
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
}).expect({
|
||||
url: 'https://other.test/api',
|
||||
options: {
|
||||
headers: { Accept: 'application/json' },
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('throws on an insecure SSL request', function () {
|
||||
expect(() =>
|
||||
withBasicAuth({
|
||||
url: 'https://myci.test/api',
|
||||
options: { strictSSL: false },
|
||||
})
|
||||
).to.throw(InvalidParameter)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -46,9 +46,6 @@ class BaseGraphqlService extends BaseService {
|
||||
* and custom error messages e.g: `{ 404: 'package not found' }`.
|
||||
* This can be used to extend or override the
|
||||
* [default](https://github.com/badges/shields/blob/master/core/base-service/check-error-response.js#L5)
|
||||
* @param {Function} [attrs.transformJson=data => data] Function which takes the raw json and transforms it before
|
||||
* further procesing. In case of multiple query in a single graphql call and few of them
|
||||
* throw error, partial data might be used ignoring the error.
|
||||
* @param {Function} [attrs.transformErrors=defaultTransformErrors]
|
||||
* Function which takes an errors object from a GraphQL
|
||||
* response and returns an instance of ShieldsRuntimeError.
|
||||
@@ -64,7 +61,6 @@ class BaseGraphqlService extends BaseService {
|
||||
variables = {},
|
||||
options = {},
|
||||
httpErrorMessages = {},
|
||||
transformJson = data => data,
|
||||
transformErrors = defaultTransformErrors,
|
||||
}) {
|
||||
const mergedOptions = {
|
||||
@@ -78,7 +74,7 @@ class BaseGraphqlService extends BaseService {
|
||||
options: mergedOptions,
|
||||
errorMessages: httpErrorMessages,
|
||||
})
|
||||
const json = transformJson(this._parseJson(buffer))
|
||||
const json = this._parseJson(buffer)
|
||||
if (json.errors) {
|
||||
const exception = transformErrors(json.errors)
|
||||
if (exception instanceof ShieldsRuntimeError) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const gql = require('graphql-tag')
|
||||
const sinon = require('sinon')
|
||||
@@ -12,8 +12,15 @@ const dummySchema = Joi.object({
|
||||
}).required()
|
||||
|
||||
class DummyGraphqlService extends BaseGraphqlService {
|
||||
static category = 'cat'
|
||||
static route = { base: 'foo' }
|
||||
static get category() {
|
||||
return 'cat'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestGraphql({
|
||||
@@ -29,10 +36,10 @@ class DummyGraphqlService extends BaseGraphqlService {
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseGraphqlService', function () {
|
||||
describe('Making requests', function () {
|
||||
describe('BaseGraphqlService', function() {
|
||||
describe('Making requests', function() {
|
||||
let sendAndCacheRequest
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sendAndCacheRequest = sinon.stub().returns(
|
||||
Promise.resolve({
|
||||
buffer: '{"some": "json"}',
|
||||
@@ -41,7 +48,7 @@ describe('BaseGraphqlService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('invokes _sendAndCacheRequest', async function () {
|
||||
it('invokes _sendAndCacheRequest', async function() {
|
||||
await DummyGraphqlService.invoke(
|
||||
{ sendAndCacheRequest },
|
||||
{ handleInternalErrors: false }
|
||||
@@ -57,7 +64,7 @@ describe('BaseGraphqlService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards options to _sendAndCacheRequest', async function () {
|
||||
it('forwards options to _sendAndCacheRequest', async function() {
|
||||
class WithOptions extends DummyGraphqlService {
|
||||
async handle() {
|
||||
const { value } = await this._requestGraphql({
|
||||
@@ -91,8 +98,8 @@ describe('BaseGraphqlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making badges', function () {
|
||||
it('handles valid json responses', async function () {
|
||||
describe('Making badges', function() {
|
||||
it('handles valid json responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '{"requiredString": "some-string"}',
|
||||
res: { statusCode: 200 },
|
||||
@@ -107,7 +114,7 @@ describe('BaseGraphqlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles json responses which do not match the schema', async function () {
|
||||
it('handles json responses which do not match the schema', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '{"unexpectedKey": "some-string"}',
|
||||
res: { statusCode: 200 },
|
||||
@@ -124,7 +131,7 @@ describe('BaseGraphqlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unparseable json responses', async function () {
|
||||
it('handles unparseable json responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'not json',
|
||||
res: { statusCode: 200 },
|
||||
@@ -142,8 +149,8 @@ describe('BaseGraphqlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Error handling', function () {
|
||||
it('handles generic error', async function () {
|
||||
describe('Error handling', function() {
|
||||
it('handles generic error', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '{ "errors": [ { "message": "oh noes!!" } ] }',
|
||||
res: { statusCode: 200 },
|
||||
@@ -160,7 +167,7 @@ describe('BaseGraphqlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles custom error', async function () {
|
||||
it('handles custom error', async function() {
|
||||
class WithErrorHandler extends DummyGraphqlService {
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestGraphql({
|
||||
@@ -171,7 +178,7 @@ describe('BaseGraphqlService', function () {
|
||||
requiredString
|
||||
}
|
||||
`,
|
||||
transformErrors: function (errors) {
|
||||
transformErrors: function(errors) {
|
||||
if (errors[0].message === 'oh noes!!') {
|
||||
return new InvalidResponse({
|
||||
prettyMessage: 'a terrible thing has happened',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const BaseJsonService = require('./base-json')
|
||||
@@ -10,8 +10,15 @@ const dummySchema = Joi.object({
|
||||
}).required()
|
||||
|
||||
class DummyJsonService extends BaseJsonService {
|
||||
static category = 'cat'
|
||||
static route = { base: 'foo' }
|
||||
static get category() {
|
||||
return 'cat'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestJson({
|
||||
@@ -22,10 +29,10 @@ class DummyJsonService extends BaseJsonService {
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseJsonService', function () {
|
||||
describe('Making requests', function () {
|
||||
describe('BaseJsonService', function() {
|
||||
describe('Making requests', function() {
|
||||
let sendAndCacheRequest
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sendAndCacheRequest = sinon.stub().returns(
|
||||
Promise.resolve({
|
||||
buffer: '{"some": "json"}',
|
||||
@@ -34,7 +41,7 @@ describe('BaseJsonService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('invokes _sendAndCacheRequest', async function () {
|
||||
it('invokes _sendAndCacheRequest', async function() {
|
||||
await DummyJsonService.invoke(
|
||||
{ sendAndCacheRequest },
|
||||
{ handleInternalErrors: false }
|
||||
@@ -42,13 +49,11 @@ describe('BaseJsonService', function () {
|
||||
|
||||
expect(sendAndCacheRequest).to.have.been.calledOnceWith(
|
||||
'http://example.com/foo.json',
|
||||
{
|
||||
headers: { Accept: 'application/json' },
|
||||
}
|
||||
{ headers: { Accept: 'application/json' } }
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards options to _sendAndCacheRequest', async function () {
|
||||
it('forwards options to _sendAndCacheRequest', async function() {
|
||||
class WithOptions extends DummyJsonService {
|
||||
async handle() {
|
||||
const { value } = await this._requestJson({
|
||||
@@ -76,8 +81,8 @@ describe('BaseJsonService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making badges', function () {
|
||||
it('handles valid json responses', async function () {
|
||||
describe('Making badges', function() {
|
||||
it('handles valid json responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '{"requiredString": "some-string"}',
|
||||
res: { statusCode: 200 },
|
||||
@@ -92,7 +97,7 @@ describe('BaseJsonService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles json responses which do not match the schema', async function () {
|
||||
it('handles json responses which do not match the schema', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '{"unexpectedKey": "some-string"}',
|
||||
res: { statusCode: 200 },
|
||||
@@ -109,7 +114,7 @@ describe('BaseJsonService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unparseable json responses', async function () {
|
||||
it('handles unparseable json responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'not json',
|
||||
res: { statusCode: 200 },
|
||||
|
||||
74
core/base-service/base-non-memory-caching.js
Normal file
74
core/base-service/base-non-memory-caching.js
Normal file
@@ -0,0 +1,74 @@
|
||||
'use strict'
|
||||
|
||||
const makeBadge = require('../../gh-badges/lib/make-badge')
|
||||
const BaseService = require('./base')
|
||||
const { MetricHelper } = require('./metric-helper')
|
||||
const { setCacheHeaders } = require('./cache-headers')
|
||||
const { makeSend } = require('./legacy-result-sender')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
const { prepareRoute, namedParamsForMatch } = require('./route')
|
||||
|
||||
// Badges are subject to two independent types of caching: in-memory and
|
||||
// downstream.
|
||||
//
|
||||
// Services deriving from `NonMemoryCachingBaseService` are not cached in
|
||||
// memory on the server. This means that each request that hits the server
|
||||
// triggers another call to the handler. When using badges for server
|
||||
// diagnostics, that's useful!
|
||||
//
|
||||
// In contrast, The `handle()` function of most other `BaseService`
|
||||
// subclasses is wrapped in onboard, in-memory caching. See `lib /request-
|
||||
// handler.js` and `BaseService.prototype.register()`.
|
||||
//
|
||||
// All services, including those extending NonMemoryCachingBaseServices, may
|
||||
// be cached _downstream_. This is governed by cache headers, which are
|
||||
// configured by the service, the user's request, and the server's default
|
||||
// cache length.
|
||||
module.exports = class NonMemoryCachingBaseService extends BaseService {
|
||||
static register({ camp, metricInstance }, serviceConfig) {
|
||||
const { cacheHeaders: cacheHeaderConfig } = serviceConfig
|
||||
const { _cacheLength: serviceDefaultCacheLengthSeconds } = this
|
||||
const { regex, captureNames } = prepareRoute(this.route)
|
||||
|
||||
const metricHelper = MetricHelper.create({
|
||||
metricInstance,
|
||||
ServiceClass: this,
|
||||
})
|
||||
|
||||
camp.route(regex, async (queryParams, match, end, ask) => {
|
||||
const metricHandle = metricHelper.startRequest()
|
||||
|
||||
const namedParams = namedParamsForMatch(captureNames, match, this)
|
||||
const serviceData = await this.invoke(
|
||||
{},
|
||||
serviceConfig,
|
||||
namedParams,
|
||||
queryParams
|
||||
)
|
||||
|
||||
const badgeData = coalesceBadge(
|
||||
queryParams,
|
||||
serviceData,
|
||||
this.defaultBadgeData,
|
||||
this
|
||||
)
|
||||
|
||||
// The final capture group is the extension.
|
||||
const format = (match.slice(-1)[0] || '.svg').replace(/^\./, '')
|
||||
badgeData.format = format
|
||||
|
||||
const svg = makeBadge(badgeData)
|
||||
|
||||
setCacheHeaders({
|
||||
cacheHeaderConfig,
|
||||
serviceDefaultCacheLengthSeconds,
|
||||
queryParams,
|
||||
res: ask.res,
|
||||
})
|
||||
|
||||
makeSend(format, ask.res, end)(svg)
|
||||
|
||||
metricHandle.noteResponseSent()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const makeBadge = require('../../badge-maker/lib/make-badge')
|
||||
const makeBadge = require('../../gh-badges/lib/make-badge')
|
||||
const BaseService = require('./base')
|
||||
const {
|
||||
serverHasBeenUpSinceResourceCached,
|
||||
@@ -13,6 +13,9 @@ const { prepareRoute, namedParamsForMatch } = require('./route')
|
||||
|
||||
module.exports = class BaseStaticService extends BaseService {
|
||||
static register({ camp, metricInstance }, serviceConfig) {
|
||||
const {
|
||||
profiling: { makeBadge: shouldProfileMakeBadge },
|
||||
} = serviceConfig
|
||||
const { regex, captureNames } = prepareRoute(this.route)
|
||||
|
||||
const metricHelper = MetricHelper.create({
|
||||
@@ -49,9 +52,16 @@ module.exports = class BaseStaticService extends BaseService {
|
||||
const format = (match.slice(-1)[0] || '.svg').replace(/^\./, '')
|
||||
badgeData.format = format
|
||||
|
||||
if (shouldProfileMakeBadge) {
|
||||
console.time('makeBadge total')
|
||||
}
|
||||
const svg = makeBadge(badgeData)
|
||||
if (shouldProfileMakeBadge) {
|
||||
console.timeEnd('makeBadge total')
|
||||
}
|
||||
|
||||
setCacheHeadersForStaticResource(ask.res)
|
||||
|
||||
const svg = makeBadge(badgeData)
|
||||
makeSend(format, ask.res, end)(svg)
|
||||
|
||||
metricHandle.noteResponseSent()
|
||||
|
||||
@@ -2,17 +2,28 @@
|
||||
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const Joi = require('joi')
|
||||
const makeBadge = require('../../badge-maker/lib/make-badge')
|
||||
const Joi = require('@hapi/joi')
|
||||
const makeBadge = require('../../gh-badges/lib/make-badge')
|
||||
const BaseSvgScrapingService = require('./base-svg-scraping')
|
||||
|
||||
function makeExampleSvg({ label, message }) {
|
||||
return makeBadge({ text: ['this is the label', 'this is the result!'] })
|
||||
}
|
||||
|
||||
const schema = Joi.object({
|
||||
message: Joi.string().required(),
|
||||
}).required()
|
||||
|
||||
class DummySvgScrapingService extends BaseSvgScrapingService {
|
||||
static category = 'cat'
|
||||
static route = { base: 'foo' }
|
||||
static get category() {
|
||||
return 'cat'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
return this._requestSvg({
|
||||
@@ -22,22 +33,25 @@ class DummySvgScrapingService extends BaseSvgScrapingService {
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseSvgScrapingService', function () {
|
||||
describe('BaseSvgScrapingService', function() {
|
||||
const exampleLabel = 'this is the label'
|
||||
const exampleMessage = 'this is the result!'
|
||||
const exampleSvg = makeBadge({ label: exampleLabel, message: exampleMessage })
|
||||
const exampleSvg = makeExampleSvg({
|
||||
label: exampleLabel,
|
||||
message: exampleMessage,
|
||||
})
|
||||
|
||||
describe('valueFromSvgBadge', function () {
|
||||
it('should find the correct value', function () {
|
||||
describe('valueFromSvgBadge', function() {
|
||||
it('should find the correct value', function() {
|
||||
expect(BaseSvgScrapingService.valueFromSvgBadge(exampleSvg)).to.equal(
|
||||
exampleMessage
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making requests', function () {
|
||||
describe('Making requests', function() {
|
||||
let sendAndCacheRequest
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sendAndCacheRequest = sinon.stub().returns(
|
||||
Promise.resolve({
|
||||
buffer: exampleSvg,
|
||||
@@ -46,7 +60,7 @@ describe('BaseSvgScrapingService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('invokes _sendAndCacheRequest with the expected header', async function () {
|
||||
it('invokes _sendAndCacheRequest with the expected header', async function() {
|
||||
await DummySvgScrapingService.invoke(
|
||||
{ sendAndCacheRequest },
|
||||
{ handleInternalErrors: false }
|
||||
@@ -54,13 +68,11 @@ describe('BaseSvgScrapingService', function () {
|
||||
|
||||
expect(sendAndCacheRequest).to.have.been.calledOnceWith(
|
||||
'http://example.com/foo.svg',
|
||||
{
|
||||
headers: { Accept: 'image/svg+xml' },
|
||||
}
|
||||
{ headers: { Accept: 'image/svg+xml' } }
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards options to _sendAndCacheRequest', async function () {
|
||||
it('forwards options to _sendAndCacheRequest', async function() {
|
||||
class WithCustomOptions extends DummySvgScrapingService {
|
||||
async handle() {
|
||||
const { message } = await this._requestSvg({
|
||||
@@ -91,8 +103,8 @@ describe('BaseSvgScrapingService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making badges', function () {
|
||||
it('handles valid svg responses', async function () {
|
||||
describe('Making badges', function() {
|
||||
it('handles valid svg responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: exampleSvg,
|
||||
res: { statusCode: 200 },
|
||||
@@ -107,9 +119,11 @@ describe('BaseSvgScrapingService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('allows overriding the valueMatcher', async function () {
|
||||
it('allows overriding the valueMatcher', async function() {
|
||||
class WithValueMatcher extends BaseSvgScrapingService {
|
||||
static route = {}
|
||||
static get route() {
|
||||
return {}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
return this._requestSvg({
|
||||
@@ -133,7 +147,7 @@ describe('BaseSvgScrapingService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unparseable svg responses', async function () {
|
||||
it('handles unparseable svg responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'not svg yo',
|
||||
res: { statusCode: 200 },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const BaseXmlService = require('./base-xml')
|
||||
@@ -10,8 +10,15 @@ const dummySchema = Joi.object({
|
||||
}).required()
|
||||
|
||||
class DummyXmlService extends BaseXmlService {
|
||||
static category = 'cat'
|
||||
static route = { base: 'foo' }
|
||||
static get category() {
|
||||
return 'cat'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestXml({
|
||||
@@ -22,10 +29,10 @@ class DummyXmlService extends BaseXmlService {
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseXmlService', function () {
|
||||
describe('Making requests', function () {
|
||||
describe('BaseXmlService', function() {
|
||||
describe('Making requests', function() {
|
||||
let sendAndCacheRequest
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sendAndCacheRequest = sinon.stub().returns(
|
||||
Promise.resolve({
|
||||
buffer: '<requiredString>some-string</requiredString>',
|
||||
@@ -34,7 +41,7 @@ describe('BaseXmlService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('invokes _sendAndCacheRequest', async function () {
|
||||
it('invokes _sendAndCacheRequest', async function() {
|
||||
await DummyXmlService.invoke(
|
||||
{ sendAndCacheRequest },
|
||||
{ handleInternalErrors: false }
|
||||
@@ -42,15 +49,15 @@ describe('BaseXmlService', function () {
|
||||
|
||||
expect(sendAndCacheRequest).to.have.been.calledOnceWith(
|
||||
'http://example.com/foo.xml',
|
||||
{
|
||||
headers: { Accept: 'application/xml, text/xml' },
|
||||
}
|
||||
{ headers: { Accept: 'application/xml, text/xml' } }
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards options to _sendAndCacheRequest', async function () {
|
||||
it('forwards options to _sendAndCacheRequest', async function() {
|
||||
class WithCustomOptions extends BaseXmlService {
|
||||
static route = {}
|
||||
static get route() {
|
||||
return {}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestXml({
|
||||
@@ -78,8 +85,8 @@ describe('BaseXmlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making badges', function () {
|
||||
it('handles valid xml responses', async function () {
|
||||
describe('Making badges', function() {
|
||||
it('handles valid xml responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '<requiredString>some-string</requiredString>',
|
||||
res: { statusCode: 200 },
|
||||
@@ -94,7 +101,7 @@ describe('BaseXmlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('parses XML response with custom parser options', async function () {
|
||||
it('parses XML response with custom parser options', async function() {
|
||||
const customParserOption = { trimValues: false }
|
||||
class DummyXmlServiceWithParserOption extends DummyXmlService {
|
||||
async handle() {
|
||||
@@ -121,7 +128,7 @@ describe('BaseXmlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles xml responses which do not match the schema', async function () {
|
||||
it('handles xml responses which do not match the schema', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '<unexpectedAttribute>some-string</unexpectedAttribute>',
|
||||
res: { statusCode: 200 },
|
||||
@@ -138,7 +145,7 @@ describe('BaseXmlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unparseable xml responses', async function () {
|
||||
it('handles unparseable xml responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'not xml',
|
||||
res: { statusCode: 200 },
|
||||
|
||||
@@ -57,7 +57,7 @@ class BaseYamlService extends BaseService {
|
||||
})
|
||||
let parsed
|
||||
try {
|
||||
parsed = yaml.load(buffer.toString(), encoding)
|
||||
parsed = yaml.safeLoad(buffer.toString(), encoding)
|
||||
} catch (err) {
|
||||
logTrace(emojic.dart, 'Response YAML (unparseable)', buffer)
|
||||
throw new InvalidResponse({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const BaseYamlService = require('./base-yaml')
|
||||
@@ -10,8 +10,15 @@ const dummySchema = Joi.object({
|
||||
}).required()
|
||||
|
||||
class DummyYamlService extends BaseYamlService {
|
||||
static category = 'cat'
|
||||
static route = { base: 'foo' }
|
||||
static get category() {
|
||||
return 'cat'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestYaml({
|
||||
@@ -38,10 +45,10 @@ foo: bar
|
||||
foo: baz
|
||||
`
|
||||
|
||||
describe('BaseYamlService', function () {
|
||||
describe('Making requests', function () {
|
||||
describe('BaseYamlService', function() {
|
||||
describe('Making requests', function() {
|
||||
let sendAndCacheRequest
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sendAndCacheRequest = sinon.stub().returns(
|
||||
Promise.resolve({
|
||||
buffer: expectedYaml,
|
||||
@@ -50,7 +57,7 @@ describe('BaseYamlService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('invokes _sendAndCacheRequest', async function () {
|
||||
it('invokes _sendAndCacheRequest', async function() {
|
||||
await DummyYamlService.invoke(
|
||||
{ sendAndCacheRequest },
|
||||
{ handleInternalErrors: false }
|
||||
@@ -67,7 +74,7 @@ describe('BaseYamlService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards options to _sendAndCacheRequest', async function () {
|
||||
it('forwards options to _sendAndCacheRequest', async function() {
|
||||
class WithOptions extends DummyYamlService {
|
||||
async handle() {
|
||||
const { requiredString } = await this._requestYaml({
|
||||
@@ -98,8 +105,8 @@ describe('BaseYamlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Making badges', function () {
|
||||
it('handles valid yaml responses', async function () {
|
||||
describe('Making badges', function() {
|
||||
it('handles valid yaml responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: expectedYaml,
|
||||
res: { statusCode: 200 },
|
||||
@@ -114,7 +121,7 @@ describe('BaseYamlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles yaml responses which do not match the schema', async function () {
|
||||
it('handles yaml responses which do not match the schema', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: unexpectedYaml,
|
||||
res: { statusCode: 200 },
|
||||
@@ -131,7 +138,7 @@ describe('BaseYamlService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unparseable yaml responses', async function () {
|
||||
it('handles unparseable yaml responses', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: invalidYaml,
|
||||
res: { statusCode: 200 },
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
// See available emoji at http://emoji.muan.co/
|
||||
const emojic = require('emojic')
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const log = require('../server/log')
|
||||
const { AuthHelper } = require('./auth-helper')
|
||||
const { MetricHelper, MetricNames } = require('./metric-helper')
|
||||
const { MetricHelper } = require('./metric-helper')
|
||||
const { assertValidCategory } = require('./categories')
|
||||
const checkErrorResponse = require('./check-error-response')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
@@ -58,7 +58,10 @@ const serviceDataSchema = Joi.object({
|
||||
// `render()` to always return a string.
|
||||
message: Joi.alternatives(Joi.string().allow(''), Joi.number()).required(),
|
||||
color: Joi.string(),
|
||||
link: Joi.array().items(Joi.string().uri()).single().max(2),
|
||||
link: Joi.array()
|
||||
.items(Joi.string().uri())
|
||||
.single()
|
||||
.max(2),
|
||||
// Generally services should not use these options, which are provided to
|
||||
// support the Endpoint badge.
|
||||
labelColor: Joi.string(),
|
||||
@@ -67,7 +70,9 @@ const serviceDataSchema = Joi.object({
|
||||
logoColor: optionalStringWhenNamedLogoPresent,
|
||||
logoWidth: optionalNumberWhenAnyLogoPresent,
|
||||
logoPosition: optionalNumberWhenAnyLogoPresent,
|
||||
cacheSeconds: Joi.number().integer().min(0),
|
||||
cacheSeconds: Joi.number()
|
||||
.integer()
|
||||
.min(0),
|
||||
style: Joi.string(),
|
||||
})
|
||||
.oxor('namedLogo', 'logoSvg')
|
||||
@@ -90,7 +95,9 @@ class BaseService {
|
||||
throw new Error(`Category not set for ${this.name}`)
|
||||
}
|
||||
|
||||
static isDeprecated = false
|
||||
static get isDeprecated() {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Route to mount this service on
|
||||
@@ -112,12 +119,14 @@ class BaseService {
|
||||
* credentials to the request. For example:
|
||||
* - `{ options: { auth: this.authHelper.basicAuth } }`
|
||||
* - `{ options: { headers: this.authHelper.bearerAuthHeader } }`
|
||||
* - `{ options: { qs: { token: this.authHelper._pass } } }`
|
||||
* - `{ options: { qs: { token: this.authHelper.pass } } }`
|
||||
*
|
||||
* @abstract
|
||||
* @type {module:core/base-service/base~Auth}
|
||||
*/
|
||||
static auth = undefined
|
||||
static get auth() {
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Array of Example objects describing example URLs for this service.
|
||||
@@ -135,7 +144,9 @@ class BaseService {
|
||||
* @abstract
|
||||
* @type {module:core/base-service/base~Example[]}
|
||||
*/
|
||||
static examples = []
|
||||
static get examples() {
|
||||
return []
|
||||
}
|
||||
|
||||
static get _cacheLength() {
|
||||
const cacheLengths = {
|
||||
@@ -154,7 +165,9 @@ class BaseService {
|
||||
*
|
||||
* @type {module:core/base-service/base~DefaultBadgeData}
|
||||
*/
|
||||
static defaultBadgeData = {}
|
||||
static get defaultBadgeData() {
|
||||
return {}
|
||||
}
|
||||
|
||||
static render(props) {
|
||||
throw new Error(`render() function not implemented for ${this.name}`)
|
||||
@@ -201,52 +214,20 @@ class BaseService {
|
||||
return result
|
||||
}
|
||||
|
||||
constructor(
|
||||
{ sendAndCacheRequest, authHelper, metricHelper },
|
||||
{ handleInternalErrors }
|
||||
) {
|
||||
constructor({ sendAndCacheRequest, authHelper }, { handleInternalErrors }) {
|
||||
this._requestFetcher = sendAndCacheRequest
|
||||
this.authHelper = authHelper
|
||||
this._handleInternalErrors = handleInternalErrors
|
||||
this._metricHelper = metricHelper
|
||||
}
|
||||
|
||||
async _request({ url, options = {}, errorMessages = {} }) {
|
||||
const logTrace = (...args) => trace.logTrace('fetch', ...args)
|
||||
let logUrl = url
|
||||
const logOptions = Object.assign({}, options)
|
||||
if ('qs' in options) {
|
||||
const params = new URLSearchParams(options.qs)
|
||||
logUrl = `${url}?${params.toString()}`
|
||||
delete logOptions.qs
|
||||
}
|
||||
logTrace(
|
||||
emojic.bowAndArrow,
|
||||
'Request',
|
||||
`${logUrl}\n${JSON.stringify(logOptions, null, 2)}`
|
||||
)
|
||||
logTrace(emojic.bowAndArrow, 'Request', url, '\n', options)
|
||||
const { res, buffer } = await this._requestFetcher(url, options)
|
||||
await this._meterResponse(res, buffer)
|
||||
logTrace(emojic.dart, 'Response status code', res.statusCode)
|
||||
return checkErrorResponse(errorMessages)({ buffer, res })
|
||||
}
|
||||
|
||||
static enabledMetrics = []
|
||||
|
||||
static isMetricEnabled(metricName) {
|
||||
return this.enabledMetrics.includes(metricName)
|
||||
}
|
||||
|
||||
async _meterResponse(res, buffer) {
|
||||
if (
|
||||
this._metricHelper &&
|
||||
this.constructor.isMetricEnabled(MetricNames.SERVICE_RESPONSE_SIZE) &&
|
||||
res.statusCode === 200
|
||||
) {
|
||||
this._metricHelper.noteServiceResponseSize(buffer.length)
|
||||
}
|
||||
}
|
||||
|
||||
static _validate(
|
||||
data,
|
||||
schema,
|
||||
@@ -355,7 +336,9 @@ class BaseService {
|
||||
// Like the service instance, the auth helper could be reused for each request.
|
||||
// However, moving its instantiation to `register()` makes `invoke()` harder
|
||||
// to test.
|
||||
const authHelper = this.auth ? new AuthHelper(this.auth, config) : undefined
|
||||
const authHelper = this.auth
|
||||
? new AuthHelper(this.auth, config.private)
|
||||
: undefined
|
||||
|
||||
const serviceInstance = new this({ ...context, authHelper }, config)
|
||||
|
||||
@@ -443,7 +426,6 @@ class BaseService {
|
||||
sendAndCacheRequest: request.asPromise,
|
||||
sendAndCacheRequestWithCallbacks: request,
|
||||
githubApiProvider,
|
||||
metricHelper,
|
||||
},
|
||||
serviceConfig,
|
||||
namedParams,
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const prometheus = require('prom-client')
|
||||
const PrometheusMetrics = require('../server/prometheus-metrics')
|
||||
const trace = require('./trace')
|
||||
const {
|
||||
NotFound,
|
||||
@@ -15,9 +12,8 @@ const {
|
||||
Deprecated,
|
||||
} = require('./errors')
|
||||
const BaseService = require('./base')
|
||||
const { MetricHelper, MetricNames } = require('./metric-helper')
|
||||
|
||||
require('../register-chai-plugins.spec')
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
const queryParamSchema = Joi.object({
|
||||
queryParamA: Joi.string(),
|
||||
@@ -29,19 +25,32 @@ const queryParamSchema = Joi.object({
|
||||
.required()
|
||||
|
||||
class DummyService extends BaseService {
|
||||
static category = 'other'
|
||||
static route = { base: 'foo', pattern: ':namedParamA', queryParamSchema }
|
||||
static get category() {
|
||||
return 'other'
|
||||
}
|
||||
|
||||
static examples = [
|
||||
{
|
||||
pattern: ':world',
|
||||
namedParams: { world: 'World' },
|
||||
staticPreview: this.render({ namedParamA: 'foo', queryParamA: 'bar' }),
|
||||
keywords: ['hello'],
|
||||
},
|
||||
]
|
||||
static get route() {
|
||||
return {
|
||||
base: 'foo',
|
||||
pattern: ':namedParamA',
|
||||
queryParamSchema,
|
||||
}
|
||||
}
|
||||
|
||||
static defaultBadgeData = { label: 'cat', namedLogo: 'appveyor' }
|
||||
static get examples() {
|
||||
return [
|
||||
{
|
||||
pattern: ':world',
|
||||
namedParams: { world: 'World' },
|
||||
staticPreview: this.render({ namedParamA: 'foo', queryParamA: 'bar' }),
|
||||
keywords: ['hello'],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
static get defaultBadgeData() {
|
||||
return { label: 'cat', namedLogo: 'appveyor' }
|
||||
}
|
||||
|
||||
static render({ namedParamA, queryParamA }) {
|
||||
return {
|
||||
@@ -54,20 +63,10 @@ class DummyService extends BaseService {
|
||||
}
|
||||
}
|
||||
|
||||
class DummyServiceWithServiceResponseSizeMetricEnabled extends DummyService {
|
||||
static enabledMetrics = [MetricNames.SERVICE_RESPONSE_SIZE]
|
||||
}
|
||||
describe('BaseService', function() {
|
||||
const defaultConfig = { handleInternalErrors: false, private: {} }
|
||||
|
||||
describe('BaseService', function () {
|
||||
const defaultConfig = {
|
||||
public: {
|
||||
handleInternalErrors: false,
|
||||
services: {},
|
||||
},
|
||||
private: {},
|
||||
}
|
||||
|
||||
it('Invokes the handler as expected', async function () {
|
||||
it('Invokes the handler as expected', async function() {
|
||||
expect(
|
||||
await DummyService.invoke(
|
||||
{},
|
||||
@@ -80,7 +79,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('Validates query params', async function () {
|
||||
it('Validates query params', async function() {
|
||||
expect(
|
||||
await DummyService.invoke(
|
||||
{},
|
||||
@@ -95,47 +94,55 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Required overrides', function () {
|
||||
it('Should throw if render() is not overridden', function () {
|
||||
describe('Required overrides', function() {
|
||||
it('Should throw if render() is not overridden', function() {
|
||||
expect(() => BaseService.render()).to.throw(
|
||||
/^render\(\) function not implemented for BaseService$/
|
||||
'render() function not implemented for BaseService'
|
||||
)
|
||||
})
|
||||
|
||||
it('Should throw if route is not overridden', function () {
|
||||
return expect(BaseService.invoke({}, {}, {})).to.be.rejectedWith(
|
||||
/^Route not defined for BaseService$/
|
||||
)
|
||||
it('Should throw if route is not overridden', async function() {
|
||||
try {
|
||||
await BaseService.invoke({}, {}, {})
|
||||
expect.fail('Expected to throw')
|
||||
} catch (e) {
|
||||
expect(e.message).to.equal('Route not defined for BaseService')
|
||||
}
|
||||
})
|
||||
|
||||
class WithRoute extends BaseService {
|
||||
static route = {}
|
||||
static get route() {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
it('Should throw if handle() is not overridden', function () {
|
||||
return expect(WithRoute.invoke({}, {}, {})).to.be.rejectedWith(
|
||||
/^Handler not implemented for WithRoute$/
|
||||
)
|
||||
it('Should throw if handle() is not overridden', async function() {
|
||||
try {
|
||||
await WithRoute.invoke({}, {}, {})
|
||||
expect.fail('Expected to throw')
|
||||
} catch (e) {
|
||||
expect(e.message).to.equal('Handler not implemented for WithRoute')
|
||||
}
|
||||
})
|
||||
|
||||
it('Should throw if category is not overridden', function () {
|
||||
it('Should throw if category is not overridden', function() {
|
||||
expect(() => BaseService.category).to.throw(
|
||||
/^Category not set for BaseService$/
|
||||
'Category not set for BaseService'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Logging', function () {
|
||||
describe('Logging', function() {
|
||||
let sandbox
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox = sinon.createSandbox()
|
||||
})
|
||||
afterEach(function () {
|
||||
afterEach(function() {
|
||||
sandbox.restore()
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox.stub(trace, 'logTrace')
|
||||
})
|
||||
it('Invokes the logger as expected', async function () {
|
||||
it('Invokes the logger as expected', async function() {
|
||||
await DummyService.invoke(
|
||||
{},
|
||||
defaultConfig,
|
||||
@@ -163,8 +170,8 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Service data validation', function () {
|
||||
it('Allows a link array', async function () {
|
||||
describe('Service data validation', function() {
|
||||
it('Allows a link array', async function() {
|
||||
const message = 'hello'
|
||||
const link = ['https://example.com/', 'https://other.example.com/']
|
||||
class LinkService extends DummyService {
|
||||
@@ -185,7 +192,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('On invalid data', function () {
|
||||
context('On invalid data', function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
return {
|
||||
@@ -194,7 +201,7 @@ describe('BaseService', function () {
|
||||
}
|
||||
}
|
||||
|
||||
it('Throws a validation error on invalid data', async function () {
|
||||
it('Throws a validation error on invalid data', async function() {
|
||||
try {
|
||||
await ThrowingService.invoke(
|
||||
{},
|
||||
@@ -212,7 +219,7 @@ describe('BaseService', function () {
|
||||
|
||||
// Ensure debuggabillity.
|
||||
// https://github.com/badges/shields/issues/3784
|
||||
it('Includes the service class in the stack trace', async function () {
|
||||
it('Includes the service class in the stack trace', async function() {
|
||||
try {
|
||||
await ThrowingService.invoke(
|
||||
{},
|
||||
@@ -227,8 +234,8 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Error handling', function () {
|
||||
it('Handles internal errors', async function () {
|
||||
describe('Error handling', function() {
|
||||
it('Handles internal errors', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw Error("I've made a huge mistake")
|
||||
@@ -248,8 +255,8 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Handles known subtypes of ShieldsInternalError', function () {
|
||||
it('handles NotFound errors', async function () {
|
||||
describe('Handles known subtypes of ShieldsInternalError', function() {
|
||||
it('handles NotFound errors', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw new NotFound()
|
||||
@@ -264,7 +271,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles Inaccessible errors', async function () {
|
||||
it('handles Inaccessible errors', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw new Inaccessible()
|
||||
@@ -279,7 +286,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles InvalidResponse errors', async function () {
|
||||
it('handles InvalidResponse errors', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw new InvalidResponse()
|
||||
@@ -294,7 +301,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles Deprecated', async function () {
|
||||
it('handles Deprecated', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw new Deprecated()
|
||||
@@ -309,7 +316,7 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles InvalidParameter errors', async function () {
|
||||
it('handles InvalidParameter errors', async function() {
|
||||
class ThrowingService extends DummyService {
|
||||
async handle() {
|
||||
throw new InvalidParameter()
|
||||
@@ -326,15 +333,15 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ScoutCamp integration', function () {
|
||||
describe('ScoutCamp integration', function() {
|
||||
// TODO Strangly, without the useless escape the regexes do not match in Node 12.
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
const expectedRouteRegex = /^\/foo(?:\/([^\/#\?]+?))(|\.svg|\.json)$/
|
||||
const expectedRouteRegex = /^\/foo\/([^\/]+?)(|\.svg|\.json)$/
|
||||
|
||||
let mockCamp
|
||||
let mockHandleRequest
|
||||
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
mockCamp = {
|
||||
route: sinon.spy(),
|
||||
}
|
||||
@@ -345,12 +352,12 @@ describe('BaseService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('registers the service', function () {
|
||||
it('registers the service', function() {
|
||||
expect(mockCamp.route).to.have.been.calledOnce
|
||||
expect(mockCamp.route).to.have.been.calledWith(expectedRouteRegex)
|
||||
})
|
||||
|
||||
it('handles the request', async function () {
|
||||
it('handles the request', async function() {
|
||||
expect(mockHandleRequest).to.have.been.calledOnce
|
||||
|
||||
const {
|
||||
@@ -373,10 +380,9 @@ describe('BaseService', function () {
|
||||
const expectedFormat = 'svg'
|
||||
expect(mockSendBadge).to.have.been.calledOnce
|
||||
expect(mockSendBadge).to.have.been.calledWith(expectedFormat, {
|
||||
label: 'cat',
|
||||
message: 'Hello namedParamA: bar with queryParamA: ?',
|
||||
text: ['cat', 'Hello namedParamA: bar with queryParamA: ?'],
|
||||
color: 'lightgrey',
|
||||
style: 'flat',
|
||||
template: undefined,
|
||||
namedLogo: undefined,
|
||||
logo: undefined,
|
||||
logoWidth: undefined,
|
||||
@@ -388,8 +394,8 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDefinition', function () {
|
||||
it('returns the expected result', function () {
|
||||
describe('getDefinition', function() {
|
||||
it('returns the expected result', function() {
|
||||
const {
|
||||
category,
|
||||
name,
|
||||
@@ -416,36 +422,37 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('validate', function () {
|
||||
describe('validate', function() {
|
||||
const dummySchema = Joi.object({
|
||||
requiredString: Joi.string().required(),
|
||||
}).required()
|
||||
|
||||
it('throws error for invalid responses', function () {
|
||||
expect(() =>
|
||||
it('throws error for invalid responses', async function() {
|
||||
try {
|
||||
DummyService._validate(
|
||||
{ requiredString: ['this', "shouldn't", 'work'] },
|
||||
dummySchema
|
||||
)
|
||||
)
|
||||
.to.throw()
|
||||
.instanceof(InvalidResponse)
|
||||
expect.fail('Expected to throw')
|
||||
} catch (e) {
|
||||
expect(e).to.be.an.instanceof(InvalidResponse)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('request', function () {
|
||||
describe('request', function() {
|
||||
let sandbox
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox = sinon.createSandbox()
|
||||
})
|
||||
afterEach(function () {
|
||||
afterEach(function() {
|
||||
sandbox.restore()
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox.stub(trace, 'logTrace')
|
||||
})
|
||||
|
||||
it('logs appropriate information', async function () {
|
||||
it('logs appropriate information', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '',
|
||||
res: { statusCode: 200 },
|
||||
@@ -463,7 +470,9 @@ describe('BaseService', function () {
|
||||
'fetch',
|
||||
sinon.match.string,
|
||||
'Request',
|
||||
`${url}\n${JSON.stringify(options, null, 2)}`
|
||||
url,
|
||||
'\n',
|
||||
options
|
||||
)
|
||||
expect(trace.logTrace).to.be.calledWithMatch(
|
||||
'fetch',
|
||||
@@ -473,7 +482,7 @@ describe('BaseService', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('handles errors', async function () {
|
||||
it('handles errors', async function() {
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: '',
|
||||
res: { statusCode: 404 },
|
||||
@@ -494,105 +503,37 @@ describe('BaseService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Metrics', function () {
|
||||
let register
|
||||
beforeEach(function () {
|
||||
register = new prometheus.Registry()
|
||||
})
|
||||
const url = 'some-url'
|
||||
|
||||
it('service response size metric is optional', async function () {
|
||||
const metricHelper = MetricHelper.create({
|
||||
metricInstance: new PrometheusMetrics({ register }),
|
||||
ServiceClass: DummyServiceWithServiceResponseSizeMetricEnabled,
|
||||
})
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'x'.repeat(65536 + 1),
|
||||
res: { statusCode: 200 },
|
||||
})
|
||||
const serviceInstance = new DummyServiceWithServiceResponseSizeMetricEnabled(
|
||||
{ sendAndCacheRequest, metricHelper },
|
||||
defaultConfig
|
||||
)
|
||||
|
||||
await serviceInstance._request({ url })
|
||||
|
||||
expect(await register.getSingleMetricAsString('service_response_bytes'))
|
||||
.to.contain(
|
||||
'service_response_bytes_bucket{le="65536",category="other",family="undefined",service="dummy_service_with_service_response_size_metric_enabled"} 0\n'
|
||||
)
|
||||
.and.to.contain(
|
||||
'service_response_bytes_bucket{le="131072",category="other",family="undefined",service="dummy_service_with_service_response_size_metric_enabled"} 1\n'
|
||||
)
|
||||
})
|
||||
|
||||
it('service response size metric is disabled by default', async function () {
|
||||
const metricHelper = MetricHelper.create({
|
||||
metricInstance: new PrometheusMetrics({ register }),
|
||||
ServiceClass: DummyService,
|
||||
})
|
||||
const sendAndCacheRequest = async () => ({
|
||||
buffer: 'x',
|
||||
res: { statusCode: 200 },
|
||||
})
|
||||
const serviceInstance = new DummyService(
|
||||
{ sendAndCacheRequest, metricHelper },
|
||||
defaultConfig
|
||||
)
|
||||
|
||||
await serviceInstance._request({ url })
|
||||
|
||||
expect(
|
||||
await register.getSingleMetricAsString('service_response_bytes')
|
||||
).to.not.contain('service_response_bytes_bucket')
|
||||
})
|
||||
})
|
||||
describe('auth', function () {
|
||||
describe('auth', function() {
|
||||
class AuthService extends DummyService {
|
||||
static auth = {
|
||||
passKey: 'myci_pass',
|
||||
serviceKey: 'myci',
|
||||
isRequired: true,
|
||||
static get auth() {
|
||||
return {
|
||||
passKey: 'myci_pass',
|
||||
isRequired: true,
|
||||
}
|
||||
}
|
||||
|
||||
async handle() {
|
||||
return {
|
||||
message: `The CI password is ${this.authHelper._pass}`,
|
||||
message: `The CI password is ${this.authHelper.pass}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('when auth is configured properly, invoke() sets authHelper', async function () {
|
||||
it('when auth is configured properly, invoke() sets authHelper', async function() {
|
||||
expect(
|
||||
await AuthService.invoke(
|
||||
{},
|
||||
{
|
||||
public: {
|
||||
...defaultConfig.public,
|
||||
services: { myci: { authorizedOrigins: ['https://myci.test'] } },
|
||||
},
|
||||
private: { myci_pass: 'abc123' },
|
||||
},
|
||||
{ defaultConfig, private: { myci_pass: 'abc123' } },
|
||||
{ namedParamA: 'bar.bar.bar' }
|
||||
)
|
||||
).to.deep.equal({ message: 'The CI password is abc123' })
|
||||
})
|
||||
|
||||
it('when auth is not configured properly, invoke() returns inacessible', async function () {
|
||||
it('when auth is not configured properly, invoke() returns inacessible', async function() {
|
||||
expect(
|
||||
await AuthService.invoke(
|
||||
{},
|
||||
{
|
||||
public: {
|
||||
...defaultConfig.public,
|
||||
services: { myci: { authorizedOrigins: ['https://myci.test'] } },
|
||||
},
|
||||
private: {},
|
||||
},
|
||||
{
|
||||
namedParamA: 'bar.bar.bar',
|
||||
}
|
||||
)
|
||||
await AuthService.invoke({}, defaultConfig, {
|
||||
namedParamA: 'bar.bar.bar',
|
||||
})
|
||||
).to.deep.equal({
|
||||
color: 'lightgray',
|
||||
isError: true,
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
'use strict'
|
||||
|
||||
const assert = require('assert')
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const coalesce = require('./coalesce')
|
||||
|
||||
const serverStartTimeGMTString = new Date().toGMTString()
|
||||
const serverStartTimestamp = Date.now()
|
||||
|
||||
const isOptionalNonNegativeInteger = Joi.number().integer().min(0)
|
||||
const isOptionalNonNegativeInteger = Joi.number()
|
||||
.integer()
|
||||
.min(0)
|
||||
|
||||
const queryParamSchema = Joi.object({
|
||||
cacheSeconds: isOptionalNonNegativeInteger,
|
||||
@@ -67,7 +69,7 @@ function setHeadersForCacheLength(res, cacheLengthSeconds) {
|
||||
cacheControl = 'no-cache, no-store, must-revalidate'
|
||||
expires = nowGMTString
|
||||
} else {
|
||||
cacheControl = `max-age=${cacheLengthSeconds}, s-maxage=${cacheLengthSeconds}`
|
||||
cacheControl = `max-age=${cacheLengthSeconds}`
|
||||
expires = new Date(now.getTime() + cacheLengthSeconds * 1000).toGMTString()
|
||||
}
|
||||
|
||||
@@ -92,7 +94,7 @@ function setCacheHeaders({
|
||||
setHeadersForCacheLength(res, cacheLengthSeconds)
|
||||
}
|
||||
|
||||
const staticCacheControlHeader = `max-age=${24 * 3600}, s-maxage=${24 * 3600}` // 1 day.
|
||||
const staticCacheControlHeader = `max-age=${24 * 3600}` // 1 day.
|
||||
function setCacheHeadersForStaticResource(res) {
|
||||
res.setHeader('Cache-Control', staticCacheControlHeader)
|
||||
res.setHeader('Last-Modified', serverStartTimeGMTString)
|
||||
|
||||
@@ -15,13 +15,13 @@ const {
|
||||
|
||||
chai.use(require('chai-datetime'))
|
||||
|
||||
describe('Cache header functions', function () {
|
||||
describe('Cache header functions', function() {
|
||||
let res
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
res = httpMocks.createResponse()
|
||||
})
|
||||
|
||||
describe('coalesceCacheLength', function () {
|
||||
describe('coalesceCacheLength', function() {
|
||||
const cacheHeaderConfig = { defaultCacheLengthSeconds: 777 }
|
||||
test(coalesceCacheLength, () => {
|
||||
given({ cacheHeaderConfig, queryParams: {} }).expect(777)
|
||||
@@ -101,18 +101,18 @@ describe('Cache header functions', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('setHeadersForCacheLength', function () {
|
||||
describe('setHeadersForCacheLength', function() {
|
||||
let sandbox
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox = sinon.createSandbox()
|
||||
sandbox.useFakeTimers()
|
||||
})
|
||||
afterEach(function () {
|
||||
afterEach(function() {
|
||||
sandbox.restore()
|
||||
sandbox = undefined
|
||||
})
|
||||
|
||||
it('should set the correct Date header', function () {
|
||||
it('should set the correct Date header', function() {
|
||||
// Confidence check.
|
||||
expect(res._headers.date).to.equal(undefined)
|
||||
|
||||
@@ -124,42 +124,40 @@ describe('Cache header functions', function () {
|
||||
expect(res._headers.date).to.equal(now)
|
||||
})
|
||||
|
||||
context('cacheLengthSeconds is zero', function () {
|
||||
beforeEach(function () {
|
||||
context('cacheLengthSeconds is zero', function() {
|
||||
beforeEach(function() {
|
||||
setHeadersForCacheLength(res, 0)
|
||||
})
|
||||
|
||||
it('should set the expected Cache-Control header', function () {
|
||||
it('should set the expected Cache-Control header', function() {
|
||||
expect(res._headers['cache-control']).to.equal(
|
||||
'no-cache, no-store, must-revalidate'
|
||||
)
|
||||
})
|
||||
|
||||
it('should set the expected Expires header', function () {
|
||||
it('should set the expected Expires header', function() {
|
||||
expect(res._headers.expires).to.equal(new Date().toGMTString())
|
||||
})
|
||||
})
|
||||
|
||||
context('cacheLengthSeconds is nonzero', function () {
|
||||
beforeEach(function () {
|
||||
context('cacheLengthSeconds is nonzero', function() {
|
||||
beforeEach(function() {
|
||||
setHeadersForCacheLength(res, 123)
|
||||
})
|
||||
|
||||
it('should set the expected Cache-Control header', function () {
|
||||
expect(res._headers['cache-control']).to.equal(
|
||||
'max-age=123, s-maxage=123'
|
||||
)
|
||||
it('should set the expected Cache-Control header', function() {
|
||||
expect(res._headers['cache-control']).to.equal('max-age=123')
|
||||
})
|
||||
|
||||
it('should set the expected Expires header', function () {
|
||||
it('should set the expected Expires header', function() {
|
||||
const expires = new Date(Date.now() + 123 * 1000).toGMTString()
|
||||
expect(res._headers.expires).to.equal(expires)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('setCacheHeaders', function () {
|
||||
it('sets the expected fields', function () {
|
||||
describe('setCacheHeaders', function() {
|
||||
it('sets the expected fields', function() {
|
||||
const expectedFields = ['date', 'cache-control', 'expires']
|
||||
expectedFields.forEach(field =>
|
||||
expect(res._headers[field]).to.equal(undefined)
|
||||
@@ -180,18 +178,16 @@ describe('Cache header functions', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('setCacheHeadersForStaticResource', function () {
|
||||
beforeEach(function () {
|
||||
describe('setCacheHeadersForStaticResource', function() {
|
||||
beforeEach(function() {
|
||||
setCacheHeadersForStaticResource(res)
|
||||
})
|
||||
|
||||
it('should set the expected Cache-Control header', function () {
|
||||
expect(res._headers['cache-control']).to.equal(
|
||||
`max-age=${24 * 3600}, s-maxage=${24 * 3600}`
|
||||
)
|
||||
it('should set the expected Cache-Control header', function() {
|
||||
expect(res._headers['cache-control']).to.equal(`max-age=${24 * 3600}`)
|
||||
})
|
||||
|
||||
it('should set the expected Last-Modified header', function () {
|
||||
it('should set the expected Last-Modified header', function() {
|
||||
const lastModified = res._headers['last-modified']
|
||||
expect(new Date(lastModified)).to.be.withinTime(
|
||||
// Within the last 60 seconds.
|
||||
@@ -201,17 +197,17 @@ describe('Cache header functions', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('serverHasBeenUpSinceResourceCached', function () {
|
||||
describe('serverHasBeenUpSinceResourceCached', function() {
|
||||
// The stringified req's are hard to understand. I thought Sazerac
|
||||
// provided a way to override the describe message, though I can't find it.
|
||||
context('when there is no If-Modified-Since header', function () {
|
||||
it('returns false', function () {
|
||||
context('when there is no If-Modified-Since header', function() {
|
||||
it('returns false', function() {
|
||||
const req = httpMocks.createRequest()
|
||||
expect(serverHasBeenUpSinceResourceCached(req)).to.equal(false)
|
||||
})
|
||||
})
|
||||
context('when the If-Modified-Since header is invalid', function () {
|
||||
it('returns false', function () {
|
||||
context('when the If-Modified-Since header is invalid', function() {
|
||||
it('returns false', function() {
|
||||
const req = httpMocks.createRequest({
|
||||
headers: { 'If-Modified-Since': 'this-is-not-a-date' },
|
||||
})
|
||||
@@ -220,8 +216,8 @@ describe('Cache header functions', function () {
|
||||
})
|
||||
context(
|
||||
'when the If-Modified-Since header is before the process started',
|
||||
function () {
|
||||
it('returns false', function () {
|
||||
function() {
|
||||
it('returns false', function() {
|
||||
const req = httpMocks.createRequest({
|
||||
headers: { 'If-Modified-Since': '2018-02-01T05:00:00.000Z' },
|
||||
})
|
||||
@@ -231,8 +227,8 @@ describe('Cache header functions', function () {
|
||||
)
|
||||
context(
|
||||
'when the If-Modified-Since header is after the process started',
|
||||
function () {
|
||||
it('returns true', function () {
|
||||
function() {
|
||||
it('returns true', function() {
|
||||
const modifiedTimeStamp = new Date(Date.now() + 1800000)
|
||||
const req = httpMocks.createRequest({
|
||||
headers: { 'If-Modified-Since': modifiedTimeStamp.toISOString() },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const categories = require('../../services/categories')
|
||||
|
||||
const isRealCategory = Joi.equal(...categories.map(({ id }) => id)).required()
|
||||
|
||||
@@ -7,7 +7,7 @@ const defaultErrorMessages = {
|
||||
}
|
||||
|
||||
module.exports = function checkErrorResponse(errorMessages = {}) {
|
||||
return async function ({ buffer, res }) {
|
||||
return async function({ buffer, res }) {
|
||||
let error
|
||||
errorMessages = { ...defaultErrorMessages, ...errorMessages }
|
||||
if (res.statusCode === 404) {
|
||||
|
||||
@@ -4,11 +4,11 @@ const { expect } = require('chai')
|
||||
const { NotFound, InvalidResponse, Inaccessible } = require('./errors')
|
||||
const checkErrorResponse = require('./check-error-response')
|
||||
|
||||
describe('async error handler', function () {
|
||||
describe('async error handler', function() {
|
||||
const buffer = Buffer.from('some stuff')
|
||||
|
||||
context('when status is 200', function () {
|
||||
it('passes through the inputs', async function () {
|
||||
context('when status is 200', function() {
|
||||
it('passes through the inputs', async function() {
|
||||
const res = { statusCode: 200 }
|
||||
expect(await checkErrorResponse()({ res, buffer })).to.deep.equal({
|
||||
res,
|
||||
@@ -17,11 +17,11 @@ describe('async error handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('when status is 404', function () {
|
||||
context('when status is 404', function() {
|
||||
const buffer = Buffer.from('some stuff')
|
||||
const res = { statusCode: 404 }
|
||||
|
||||
it('throws NotFound', async function () {
|
||||
it('throws NotFound', async function() {
|
||||
try {
|
||||
await checkErrorResponse()({ res, buffer })
|
||||
expect.fail('Expected to throw')
|
||||
@@ -34,7 +34,7 @@ describe('async error handler', function () {
|
||||
}
|
||||
})
|
||||
|
||||
it('displays the custom not found message', async function () {
|
||||
it('displays the custom not found message', async function() {
|
||||
const notFoundMessage = 'no goblins found'
|
||||
try {
|
||||
await checkErrorResponse({ 404: notFoundMessage })({ res, buffer })
|
||||
@@ -47,8 +47,8 @@ describe('async error handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('when status is 4xx', function () {
|
||||
it('throws InvalidResponse', async function () {
|
||||
context('when status is 4xx', function() {
|
||||
it('throws InvalidResponse', async function() {
|
||||
const res = { statusCode: 499 }
|
||||
try {
|
||||
await checkErrorResponse()({ res, buffer })
|
||||
@@ -64,7 +64,7 @@ describe('async error handler', function () {
|
||||
}
|
||||
})
|
||||
|
||||
it('displays the custom error message', async function () {
|
||||
it('displays the custom error message', async function() {
|
||||
const res = { statusCode: 403 }
|
||||
try {
|
||||
await checkErrorResponse({ 403: 'access denied' })({ res })
|
||||
@@ -79,8 +79,8 @@ describe('async error handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('when status is 5xx', function () {
|
||||
it('throws Inaccessible', async function () {
|
||||
context('when status is 5xx', function() {
|
||||
it('throws Inaccessible', async function() {
|
||||
const res = { statusCode: 503 }
|
||||
try {
|
||||
await checkErrorResponse()({ res, buffer })
|
||||
@@ -96,7 +96,7 @@ describe('async error handler', function () {
|
||||
}
|
||||
})
|
||||
|
||||
it('displays the custom error message', async function () {
|
||||
it('displays the custom error message', async function() {
|
||||
const res = { statusCode: 500 }
|
||||
try {
|
||||
await checkErrorResponse({ 500: 'server overloaded' })({ res, buffer })
|
||||
|
||||
@@ -104,23 +104,7 @@ module.exports = function coalesceBadge(
|
||||
labelColor: defaultLabelColor,
|
||||
} = defaultBadgeData
|
||||
|
||||
let style = coalesce(overrideStyle, serviceStyle)
|
||||
if (typeof style !== 'string') {
|
||||
style = 'flat'
|
||||
}
|
||||
if (style.startsWith('popout')) {
|
||||
style = style.replace('popout', 'flat')
|
||||
}
|
||||
const styleValues = [
|
||||
'plastic',
|
||||
'flat',
|
||||
'flat-square',
|
||||
'for-the-badge',
|
||||
'social',
|
||||
]
|
||||
if (!styleValues.includes(style)) {
|
||||
style = 'flat'
|
||||
}
|
||||
const style = coalesce(overrideStyle, serviceStyle)
|
||||
|
||||
let namedLogo, namedLogoColor, logoWidth, logoPosition, logoSvgBase64
|
||||
if (overrideLogo) {
|
||||
@@ -160,10 +144,12 @@ module.exports = function coalesceBadge(
|
||||
}
|
||||
|
||||
return {
|
||||
// Use `coalesce()` to support empty labels and messages, as in the static
|
||||
// badge.
|
||||
label: coalesce(overrideLabel, serviceLabel, defaultLabel, category),
|
||||
message: coalesce(serviceMessage, 'n/a'),
|
||||
text: [
|
||||
// Use `coalesce()` to support empty labels and messages, as in the
|
||||
// static badge.
|
||||
coalesce(overrideLabel, serviceLabel, defaultLabel, category),
|
||||
coalesce(serviceMessage, 'n/a'),
|
||||
],
|
||||
color: coalesce(
|
||||
// In case of an error, disregard user's color override.
|
||||
isError ? undefined : overrideColor,
|
||||
@@ -177,7 +163,7 @@ module.exports = function coalesceBadge(
|
||||
serviceLabelColor,
|
||||
defaultLabelColor
|
||||
),
|
||||
style,
|
||||
template: style,
|
||||
namedLogo,
|
||||
logo: logoSvgBase64,
|
||||
logoWidth,
|
||||
|
||||
@@ -4,123 +4,124 @@ const { expect } = require('chai')
|
||||
const { getShieldsIcon, getSimpleIcon } = require('../../lib/logos')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
|
||||
describe('coalesceBadge', function () {
|
||||
describe('Label', function () {
|
||||
it('uses the default label', function () {
|
||||
expect(coalesceBadge({}, {}, { label: 'heyo' })).to.include({
|
||||
label: 'heyo',
|
||||
})
|
||||
describe('coalesceBadge', function() {
|
||||
describe('Label', function() {
|
||||
it('uses the default label', function() {
|
||||
expect(coalesceBadge({}, {}, { label: 'heyo' }).text).to.deep.equal([
|
||||
'heyo',
|
||||
'n/a',
|
||||
])
|
||||
})
|
||||
|
||||
// This behavior isn't great and we might want to remove it.
|
||||
it('uses the category as a default label', function () {
|
||||
expect(coalesceBadge({}, {}, {}, { category: 'cat' })).to.include({
|
||||
label: 'cat',
|
||||
})
|
||||
it('uses the category as a default label', function() {
|
||||
expect(coalesceBadge({}, {}, {}, { category: 'cat' }).text).to.deep.equal(
|
||||
['cat', 'n/a']
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves an empty label', function () {
|
||||
expect(coalesceBadge({}, { label: '', message: '10k' }, {})).to.include({
|
||||
label: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('overrides the label', function () {
|
||||
it('preserves an empty label', function() {
|
||||
expect(
|
||||
coalesceBadge({ label: 'purr count' }, { label: 'purrs' }, {})
|
||||
).to.include({ label: 'purr count' })
|
||||
coalesceBadge({}, { label: '', message: '10k' }, {}).text
|
||||
).to.deep.equal(['', '10k'])
|
||||
})
|
||||
|
||||
it('overrides the label', function() {
|
||||
expect(
|
||||
coalesceBadge({ label: 'purr count' }, { label: 'purrs' }, {}).text
|
||||
).to.deep.equal(['purr count', 'n/a'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Message', function () {
|
||||
it('applies the service message', function () {
|
||||
expect(coalesceBadge({}, { message: '10k' }, {})).to.include({
|
||||
message: '10k',
|
||||
})
|
||||
describe('Message', function() {
|
||||
it('applies the service message', function() {
|
||||
expect(coalesceBadge({}, { message: '10k' }, {}).text).to.deep.equal([
|
||||
undefined,
|
||||
'10k',
|
||||
])
|
||||
})
|
||||
|
||||
// https://github.com/badges/shields/issues/1280
|
||||
it('converts a number to a string', function () {
|
||||
it('applies a numeric service message', function() {
|
||||
// While a number of badges use this, in the long run we may want
|
||||
// `render()` to always return a string.
|
||||
expect(coalesceBadge({}, { message: 10 }, {})).to.include({
|
||||
message: 10,
|
||||
})
|
||||
expect(coalesceBadge({}, { message: 10 }, {}).text).to.deep.equal([
|
||||
undefined,
|
||||
10,
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Right color', function () {
|
||||
it('uses the default color', function () {
|
||||
expect(coalesceBadge({}, {}, {})).to.include({ color: 'lightgrey' })
|
||||
describe('Right color', function() {
|
||||
it('uses the default color', function() {
|
||||
expect(coalesceBadge({}, {}, {}).color).to.equal('lightgrey')
|
||||
})
|
||||
|
||||
it('overrides the color', function () {
|
||||
it('overrides the color', function() {
|
||||
expect(
|
||||
coalesceBadge({ color: '10ADED' }, { color: 'red' }, {})
|
||||
).to.include({ color: '10ADED' })
|
||||
coalesceBadge({ color: '10ADED' }, { color: 'red' }, {}).color
|
||||
).to.equal('10ADED')
|
||||
// also expected for legacy name
|
||||
expect(
|
||||
coalesceBadge({ colorB: 'B0ADED' }, { color: 'red' }, {})
|
||||
).to.include({ color: 'B0ADED' })
|
||||
coalesceBadge({ colorB: 'B0ADED' }, { color: 'red' }, {}).color
|
||||
).to.equal('B0ADED')
|
||||
})
|
||||
|
||||
context('In case of an error', function () {
|
||||
it('does not override the color', function () {
|
||||
context('In case of an error', function() {
|
||||
it('does not override the color', function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ color: '10ADED' },
|
||||
{ isError: true, color: 'lightgray' },
|
||||
{}
|
||||
)
|
||||
).to.include({ color: 'lightgray' })
|
||||
).color
|
||||
).to.equal('lightgray')
|
||||
// also expected for legacy name
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ colorB: 'B0ADED' },
|
||||
{ isError: true, color: 'lightgray' },
|
||||
{}
|
||||
)
|
||||
).to.include({ color: 'lightgray' })
|
||||
).color
|
||||
).to.equal('lightgray')
|
||||
})
|
||||
})
|
||||
|
||||
it('applies the service color', function () {
|
||||
expect(coalesceBadge({}, { color: 'red' }, {})).to.include({
|
||||
color: 'red',
|
||||
})
|
||||
it('applies the service color', function() {
|
||||
expect(coalesceBadge({}, { color: 'red' }, {}).color).to.equal('red')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Left color', function () {
|
||||
it('provides no default label color', function () {
|
||||
describe('Left color', function() {
|
||||
it('provides no default label color', function() {
|
||||
expect(coalesceBadge({}, {}, {}).labelColor).to.be.undefined
|
||||
})
|
||||
|
||||
it('applies the service label color', function () {
|
||||
expect(coalesceBadge({}, { labelColor: 'red' }, {})).to.include({
|
||||
labelColor: 'red',
|
||||
})
|
||||
it('applies the service label color', function() {
|
||||
expect(coalesceBadge({}, { labelColor: 'red' }, {}).labelColor).to.equal(
|
||||
'red'
|
||||
)
|
||||
})
|
||||
|
||||
it('overrides the label color', function () {
|
||||
it('overrides the label color', function() {
|
||||
expect(
|
||||
coalesceBadge({ labelColor: '42f483' }, { color: 'green' }, {})
|
||||
).to.include({ labelColor: '42f483' })
|
||||
.labelColor
|
||||
).to.equal('42f483')
|
||||
// also expected for legacy name
|
||||
expect(
|
||||
coalesceBadge({ colorA: 'B2f483' }, { color: 'green' }, {})
|
||||
).to.include({ labelColor: 'B2f483' })
|
||||
coalesceBadge({ colorA: 'B2f483' }, { color: 'green' }, {}).labelColor
|
||||
).to.equal('B2f483')
|
||||
})
|
||||
|
||||
it('converts a query-string numeric color to a string', function () {
|
||||
it('converts a query-string numeric color to a string', function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
// Scoutcamp converts numeric query params to numbers.
|
||||
{ color: 123 },
|
||||
{ color: 'green' },
|
||||
{}
|
||||
)
|
||||
).to.include({ color: '123' })
|
||||
).color
|
||||
).to.equal('123')
|
||||
// also expected for legacy name
|
||||
expect(
|
||||
coalesceBadge(
|
||||
@@ -128,47 +129,47 @@ describe('coalesceBadge', function () {
|
||||
{ colorB: 123 },
|
||||
{ color: 'green' },
|
||||
{}
|
||||
)
|
||||
).to.include({ color: '123' })
|
||||
).color
|
||||
).to.equal('123')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Named logos', function () {
|
||||
it('when not a social badge, ignores the default named logo', function () {
|
||||
describe('Named logos', function() {
|
||||
it('when not a social badge, ignores the default named logo', function() {
|
||||
expect(coalesceBadge({}, {}, { namedLogo: 'appveyor' }).logo).to.be
|
||||
.undefined
|
||||
})
|
||||
|
||||
it('when a social badge, uses the default named logo', function () {
|
||||
it('when a social badge, uses the default named logo', function() {
|
||||
// .not.be.empty for confidence that nothing has changed with `getShieldsIcon()`.
|
||||
expect(
|
||||
coalesceBadge({ style: 'social' }, {}, { namedLogo: 'appveyor' }).logo
|
||||
).to.equal(getSimpleIcon({ name: 'appveyor' })).and.not.be.empty
|
||||
})
|
||||
|
||||
it('applies the named logo', function () {
|
||||
expect(coalesceBadge({}, { namedLogo: 'npm' }, {})).to.include({
|
||||
namedLogo: 'npm',
|
||||
})
|
||||
it('applies the named logo', function() {
|
||||
expect(coalesceBadge({}, { namedLogo: 'npm' }, {}).namedLogo).to.equal(
|
||||
'npm'
|
||||
)
|
||||
expect(coalesceBadge({}, { namedLogo: 'npm' }, {}).logo).to.equal(
|
||||
getShieldsIcon({ name: 'npm' })
|
||||
).and.not.to.be.empty
|
||||
})
|
||||
|
||||
it('applies the named logo with color', function () {
|
||||
it('applies the named logo with color', function() {
|
||||
expect(
|
||||
coalesceBadge({}, { namedLogo: 'npm', logoColor: 'blue' }, {}).logo
|
||||
).to.equal(getShieldsIcon({ name: 'npm', color: 'blue' })).and.not.to.be
|
||||
.empty
|
||||
})
|
||||
|
||||
it('overrides the logo', function () {
|
||||
it('overrides the logo', function() {
|
||||
expect(
|
||||
coalesceBadge({ logo: 'npm' }, { namedLogo: 'appveyor' }, {}).logo
|
||||
).to.equal(getShieldsIcon({ name: 'npm' })).and.not.be.empty
|
||||
})
|
||||
|
||||
it('overrides the logo with a color', function () {
|
||||
it('overrides the logo with a color', function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ logo: 'npm', logoColor: 'blue' },
|
||||
@@ -179,7 +180,7 @@ describe('coalesceBadge', function () {
|
||||
.empty
|
||||
})
|
||||
|
||||
it("when the logo is overridden, it ignores the service's logo color, position, and width", function () {
|
||||
it("when the logo is overridden, it ignores the service's logo color, position, and width", function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ logo: 'npm' },
|
||||
@@ -194,7 +195,7 @@ describe('coalesceBadge', function () {
|
||||
).to.equal(getShieldsIcon({ name: 'npm' })).and.not.be.empty
|
||||
})
|
||||
|
||||
it("overrides the service logo's color", function () {
|
||||
it("overrides the service logo's color", function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ logoColor: 'blue' },
|
||||
@@ -206,7 +207,7 @@ describe('coalesceBadge', function () {
|
||||
})
|
||||
|
||||
// https://github.com/badges/shields/issues/2998
|
||||
it('overrides logoSvg', function () {
|
||||
it('overrides logoSvg', function() {
|
||||
const logoSvg = 'data:image/svg+xml;base64,PHN2ZyB4bWxu'
|
||||
expect(coalesceBadge({ logo: 'npm' }, { logoSvg }, {}).logo).to.equal(
|
||||
getShieldsIcon({ name: 'npm' })
|
||||
@@ -214,56 +215,55 @@ describe('coalesceBadge', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Custom logos', function () {
|
||||
it('overrides the logo with custom svg', function () {
|
||||
describe('Custom logos', function() {
|
||||
it('overrides the logo with custom svg', function() {
|
||||
const logoSvg = 'data:image/svg+xml;base64,PHN2ZyB4bWxu'
|
||||
expect(
|
||||
coalesceBadge({ logo: logoSvg }, { namedLogo: 'appveyor' }, {})
|
||||
).to.include({ logo: logoSvg })
|
||||
coalesceBadge({ logo: logoSvg }, { namedLogo: 'appveyor' }, {}).logo
|
||||
).to.equal(logoSvg)
|
||||
})
|
||||
|
||||
it('ignores the color when custom svg is provided', function () {
|
||||
it('ignores the color when custom svg is provided', function() {
|
||||
const logoSvg = 'data:image/svg+xml;base64,PHN2ZyB4bWxu'
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ logo: logoSvg, logoColor: 'brightgreen' },
|
||||
{ namedLogo: 'appveyor' },
|
||||
{}
|
||||
)
|
||||
).to.include({ logo: logoSvg })
|
||||
).logo
|
||||
).to.equal(logoSvg)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Logo width', function () {
|
||||
it('overrides the logoWidth', function () {
|
||||
expect(coalesceBadge({ logoWidth: 20 }, {}, {})).to.include({
|
||||
logoWidth: 20,
|
||||
})
|
||||
describe('Logo width', function() {
|
||||
it('overrides the logoWidth', function() {
|
||||
expect(coalesceBadge({ logoWidth: 20 }, {}, {}).logoWidth).to.equal(20)
|
||||
})
|
||||
|
||||
it('applies the logo width', function () {
|
||||
it('applies the logo width', function() {
|
||||
expect(
|
||||
coalesceBadge({}, { namedLogo: 'npm', logoWidth: 275 }, {})
|
||||
).to.include({ logoWidth: 275 })
|
||||
coalesceBadge({}, { namedLogo: 'npm', logoWidth: 275 }, {}).logoWidth
|
||||
).to.equal(275)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Logo position', function () {
|
||||
it('overrides the logoPosition', function () {
|
||||
expect(coalesceBadge({ logoPosition: -10 }, {}, {})).to.include({
|
||||
logoPosition: -10,
|
||||
})
|
||||
describe('Logo position', function() {
|
||||
it('overrides the logoPosition', function() {
|
||||
expect(
|
||||
coalesceBadge({ logoPosition: -10 }, {}, {}).logoPosition
|
||||
).to.equal(-10)
|
||||
})
|
||||
|
||||
it('applies the logo position', function () {
|
||||
it('applies the logo position', function() {
|
||||
expect(
|
||||
coalesceBadge({}, { namedLogo: 'npm', logoPosition: -10 }, {})
|
||||
).to.include({ logoPosition: -10 })
|
||||
.logoPosition
|
||||
).to.equal(-10)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Links', function () {
|
||||
it('overrides the links', function () {
|
||||
describe('Links', function() {
|
||||
it('overrides the links', function() {
|
||||
expect(
|
||||
coalesceBadge(
|
||||
{ link: 'https://circleci.com/gh/badges/daily-tests' },
|
||||
@@ -277,34 +277,18 @@ describe('coalesceBadge', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Style', function () {
|
||||
it('falls back to flat with invalid style', function () {
|
||||
expect(coalesceBadge({ style: 'pill' }, {}, {})).to.include({
|
||||
style: 'flat',
|
||||
})
|
||||
expect(coalesceBadge({ style: 7 }, {}, {})).to.include({
|
||||
style: 'flat',
|
||||
})
|
||||
expect(coalesceBadge({ style: undefined }, {}, {})).to.include({
|
||||
style: 'flat',
|
||||
})
|
||||
})
|
||||
|
||||
it('replaces legacy popout styles', function () {
|
||||
expect(coalesceBadge({ style: 'popout' }, {}, {})).to.include({
|
||||
style: 'flat',
|
||||
})
|
||||
expect(coalesceBadge({ style: 'popout-square' }, {}, {})).to.include({
|
||||
style: 'flat-square',
|
||||
})
|
||||
describe('Style', function() {
|
||||
it('overrides the template', function() {
|
||||
expect(coalesceBadge({ style: 'pill' }, {}, {}).template).to.equal('pill')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cache length', function () {
|
||||
it('overrides the cache length', function () {
|
||||
describe('Cache length', function() {
|
||||
it('overrides the cache length', function() {
|
||||
expect(
|
||||
coalesceBadge({ style: 'pill' }, { cacheSeconds: 123 }, {})
|
||||
).to.include({ cacheLengthSeconds: 123 })
|
||||
.cacheLengthSeconds
|
||||
).to.equal(123)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,16 +7,16 @@ const coalesce = require('./coalesce')
|
||||
// `undefined` instead of `null`, though h/t to
|
||||
// https://github.com/royriojas/coalescy for these tests!
|
||||
|
||||
describe('coalesce', function () {
|
||||
test(coalesce, function () {
|
||||
describe('coalesce', function() {
|
||||
test(coalesce, function() {
|
||||
given().expect(undefined)
|
||||
given(null, []).expect([])
|
||||
given(null, [], {}).expect([])
|
||||
given(null, undefined, 0, {}).expect(0)
|
||||
|
||||
const a = null
|
||||
const c = 0
|
||||
const d = 1
|
||||
const a = null,
|
||||
c = 0,
|
||||
d = 1
|
||||
let b
|
||||
given(a, b, c, d).expect(0)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const camelcase = require('camelcase')
|
||||
const BaseService = require('./base')
|
||||
const { isValidCategory } = require('./categories')
|
||||
@@ -26,17 +26,33 @@ function deprecatedService(attrs) {
|
||||
)
|
||||
|
||||
return class DeprecatedService extends BaseService {
|
||||
static name = name
|
||||
? `Deprecated${name}`
|
||||
: `Deprecated${camelcase(route.base.replace(/\//g, '_'), {
|
||||
pascalCase: true,
|
||||
})}`
|
||||
static get name() {
|
||||
return name
|
||||
? `Deprecated${name}`
|
||||
: `Deprecated${camelcase(route.base.replace(/\//g, '_'), {
|
||||
pascalCase: true,
|
||||
})}`
|
||||
}
|
||||
|
||||
static category = category
|
||||
static isDeprecated = true
|
||||
static route = route
|
||||
static examples = examples
|
||||
static defaultBadgeData = { label }
|
||||
static get category() {
|
||||
return category
|
||||
}
|
||||
|
||||
static get isDeprecated() {
|
||||
return true
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return route
|
||||
}
|
||||
|
||||
static get examples() {
|
||||
return examples
|
||||
}
|
||||
|
||||
static get defaultBadgeData() {
|
||||
return { label }
|
||||
}
|
||||
|
||||
async handle() {
|
||||
throw new Deprecated({ prettyMessage: message })
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const { expect } = require('chai')
|
||||
const deprecatedService = require('./deprecated-service')
|
||||
|
||||
describe('DeprecatedService', function () {
|
||||
describe('DeprecatedService', function() {
|
||||
const route = {
|
||||
base: 'service/that/no/longer/exists',
|
||||
format: '(?:.+)',
|
||||
@@ -12,33 +12,33 @@ describe('DeprecatedService', function () {
|
||||
const dateAdded = new Date()
|
||||
const commonAttrs = { route, category, dateAdded }
|
||||
|
||||
it('returns true on isDeprecated', function () {
|
||||
it('returns true on isDeprecated', function() {
|
||||
const service = deprecatedService({ ...commonAttrs })
|
||||
expect(service.isDeprecated).to.be.true
|
||||
})
|
||||
|
||||
it('has the expected name', function () {
|
||||
it('has the expected name', function() {
|
||||
const service = deprecatedService({ ...commonAttrs })
|
||||
expect(service.name).to.equal('DeprecatedServiceThatNoLongerExists')
|
||||
})
|
||||
|
||||
it('sets specified route', function () {
|
||||
it('sets specified route', function() {
|
||||
const service = deprecatedService({ ...commonAttrs })
|
||||
expect(service.route).to.deep.equal(route)
|
||||
})
|
||||
|
||||
it('sets specified label', function () {
|
||||
it('sets specified label', function() {
|
||||
const label = 'coverity'
|
||||
const service = deprecatedService({ ...commonAttrs, label })
|
||||
expect(service.defaultBadgeData.label).to.equal(label)
|
||||
})
|
||||
|
||||
it('sets specified category', function () {
|
||||
it('sets specified category', function() {
|
||||
const service = deprecatedService({ ...commonAttrs })
|
||||
expect(service.category).to.equal(category)
|
||||
})
|
||||
|
||||
it('sets specified examples', function () {
|
||||
it('sets specified examples', function() {
|
||||
const examples = [
|
||||
{
|
||||
title: 'Not sure we would have examples',
|
||||
@@ -48,7 +48,7 @@ describe('DeprecatedService', function () {
|
||||
expect(service.examples).to.deep.equal(examples)
|
||||
})
|
||||
|
||||
it('uses default deprecation message when no message specified', async function () {
|
||||
it('uses default deprecation message when no message specified', async function() {
|
||||
const service = deprecatedService({ ...commonAttrs })
|
||||
expect(await service.invoke()).to.deep.equal({
|
||||
isError: true,
|
||||
@@ -57,7 +57,7 @@ describe('DeprecatedService', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('uses custom deprecation message when specified', async function () {
|
||||
it('uses custom deprecation message when specified', async function() {
|
||||
const message = 'extended outage'
|
||||
const service = deprecatedService({ ...commonAttrs, message })
|
||||
expect(await service.invoke()).to.deep.equal({
|
||||
|
||||
@@ -56,7 +56,6 @@ class NotFound extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'NotFound'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return defaultNotFoundError
|
||||
}
|
||||
@@ -83,7 +82,6 @@ class InvalidResponse extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'InvalidResponse'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return 'invalid'
|
||||
}
|
||||
@@ -109,7 +107,6 @@ class Inaccessible extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'Inaccessible'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return 'inaccessible'
|
||||
}
|
||||
@@ -134,7 +131,6 @@ class ImproperlyConfigured extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'ImproperlyConfigured'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return 'improperly configured'
|
||||
}
|
||||
@@ -160,7 +156,6 @@ class InvalidParameter extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'InvalidParameter'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return 'invalid parameter'
|
||||
}
|
||||
@@ -185,7 +180,6 @@ class Deprecated extends ShieldsRuntimeError {
|
||||
get name() {
|
||||
return 'Deprecated'
|
||||
}
|
||||
|
||||
get defaultPrettyMessage() {
|
||||
return 'no longer available'
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const { pathToRegexp, compile } = require('path-to-regexp')
|
||||
const Joi = require('@hapi/joi')
|
||||
const pathToRegexp = require('path-to-regexp')
|
||||
const categories = require('../../services/categories')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
const { makeFullUrl } = require('./route')
|
||||
@@ -21,12 +21,19 @@ const schema = Joi.object({
|
||||
staticPreview: Joi.object({
|
||||
label: Joi.string(),
|
||||
message: Joi.alternatives()
|
||||
.try(Joi.string().allow('').required(), Joi.number())
|
||||
.try(
|
||||
Joi.string()
|
||||
.allow('')
|
||||
.required(),
|
||||
Joi.number()
|
||||
)
|
||||
.required(),
|
||||
color: Joi.string(),
|
||||
style: Joi.string(),
|
||||
}).required(),
|
||||
keywords: Joi.array().items(Joi.string()).default([]),
|
||||
keywords: Joi.array()
|
||||
.items(Joi.string())
|
||||
.default([]),
|
||||
documentation: Joi.string(), // Valid HTML.
|
||||
}).required()
|
||||
|
||||
@@ -52,9 +59,7 @@ function validateExample(example, index, ServiceClass) {
|
||||
|
||||
// Make sure we can build the full URL using these patterns.
|
||||
try {
|
||||
compile(pattern || ServiceClass.route.pattern, {
|
||||
encode: encodeURIComponent,
|
||||
})(namedParams)
|
||||
pathToRegexp.compile(pattern || ServiceClass.route.pattern)(namedParams)
|
||||
} catch (e) {
|
||||
throw Error(
|
||||
`In example for ${
|
||||
@@ -64,10 +69,7 @@ function validateExample(example, index, ServiceClass) {
|
||||
}
|
||||
// Make sure there are no extra keys.
|
||||
let keys = []
|
||||
pathToRegexp(pattern || ServiceClass.route.pattern, keys, {
|
||||
strict: true,
|
||||
sensitive: true,
|
||||
})
|
||||
pathToRegexp(pattern || ServiceClass.route.pattern, keys)
|
||||
keys = keys.map(({ name }) => name)
|
||||
const extraKeys = Object.keys(namedParams).filter(k => !keys.includes(k))
|
||||
if (extraKeys.length) {
|
||||
@@ -124,7 +126,12 @@ function transformExample(inExample, index, ServiceClass) {
|
||||
documentation,
|
||||
} = validateExample(inExample, index, ServiceClass)
|
||||
|
||||
const { label, message, color, style, namedLogo } = coalesceBadge(
|
||||
const {
|
||||
text: [label, message],
|
||||
color,
|
||||
template: style,
|
||||
namedLogo,
|
||||
} = coalesceBadge(
|
||||
{},
|
||||
staticPreview,
|
||||
ServiceClass.defaultBadgeData,
|
||||
|
||||
@@ -4,8 +4,8 @@ const { expect } = require('chai')
|
||||
const { test, given } = require('sazerac')
|
||||
const { validateExample, transformExample } = require('./examples')
|
||||
|
||||
describe('validateExample function', function () {
|
||||
it('passes valid examples', function () {
|
||||
describe('validateExample function', function() {
|
||||
it('passes valid examples', function() {
|
||||
const validExamples = [
|
||||
{
|
||||
title: 'Package manager versioning badge',
|
||||
@@ -23,7 +23,7 @@ describe('validateExample function', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid examples', function () {
|
||||
it('rejects invalid examples', function() {
|
||||
const invalidExamples = [
|
||||
{},
|
||||
{ staticPreview: { message: '123' } },
|
||||
@@ -74,7 +74,7 @@ describe('validateExample function', function () {
|
||||
})
|
||||
})
|
||||
|
||||
test(transformExample, function () {
|
||||
test(transformExample, function() {
|
||||
const ExampleService = {
|
||||
name: 'ExampleService',
|
||||
route: {
|
||||
|
||||
@@ -7,8 +7,8 @@ const { mergeQueries } = require('./graphql')
|
||||
|
||||
require('../register-chai-plugins.spec')
|
||||
|
||||
describe('mergeQueries function', function () {
|
||||
it('merges valid gql queries', function () {
|
||||
describe('mergeQueries function', function() {
|
||||
it('merges valid gql queries', function() {
|
||||
expect(
|
||||
print(
|
||||
mergeQueries(
|
||||
@@ -86,7 +86,7 @@ describe('mergeQueries function', function () {
|
||||
).to.equalIgnoreSpaces('{ foo bar }')
|
||||
})
|
||||
|
||||
it('throws an error when passed invalid params', function () {
|
||||
it('throws an error when passed invalid params', function() {
|
||||
expect(() => mergeQueries('', '')).to.throw(Error)
|
||||
expect(() => mergeQueries(undefined, 17, true)).to.throw(Error)
|
||||
expect(() => mergeQueries(gql``, gql`foo`)).to.throw(Error)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const BaseService = require('./base')
|
||||
const BaseJsonService = require('./base-json')
|
||||
const BaseGraphqlService = require('./base-graphql')
|
||||
const NonMemoryCachingBaseService = require('./base-non-memory-caching')
|
||||
const BaseStaticService = require('./base-static')
|
||||
const BaseSvgScrapingService = require('./base-svg-scraping')
|
||||
const BaseXmlService = require('./base-xml')
|
||||
@@ -21,6 +22,7 @@ module.exports = {
|
||||
BaseService,
|
||||
BaseJsonService,
|
||||
BaseGraphqlService,
|
||||
NonMemoryCachingBaseService,
|
||||
BaseStaticService,
|
||||
BaseSvgScrapingService,
|
||||
BaseXmlService,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use strict'
|
||||
|
||||
const request = require('request')
|
||||
const makeBadge = require('../../badge-maker/lib/make-badge')
|
||||
const queryString = require('query-string')
|
||||
const makeBadge = require('../../gh-badges/lib/make-badge')
|
||||
const { setCacheHeaders } = require('./cache-headers')
|
||||
const {
|
||||
Inaccessible,
|
||||
@@ -9,9 +10,24 @@ const {
|
||||
ShieldsRuntimeError,
|
||||
} = require('./errors')
|
||||
const { makeSend } = require('./legacy-result-sender')
|
||||
const LruCache = require('./lru-cache')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
|
||||
const userAgent = 'Shields.io/2003a'
|
||||
// We avoid calling the vendor's server for computation of the information in a
|
||||
// number of badges.
|
||||
const minAccuracy = 0.75
|
||||
|
||||
// The quotient of (vendor) data change frequency by badge request frequency
|
||||
// must be lower than this to trigger sending the cached data *before*
|
||||
// updating our data from the vendor's server.
|
||||
// Indeed, the accuracy of our badges are:
|
||||
// A(Δt) = 1 - min(# data change over Δt, # requests over Δt)
|
||||
// / (# requests over Δt)
|
||||
// = 1 - max(1, df) / rf
|
||||
const freqRatioMax = 1 - minAccuracy
|
||||
|
||||
// Request cache size of 5MB (~5000 bytes/image).
|
||||
const requestCache = new LruCache(1000)
|
||||
|
||||
// These query parameters are available to any badge. They are handled by
|
||||
// `coalesceBadge`.
|
||||
@@ -89,19 +105,7 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
} = handlerOptions
|
||||
|
||||
return (queryParams, match, end, ask) => {
|
||||
/*
|
||||
This is here for legacy reasons. The badge server and frontend used to live
|
||||
on two different servers. When we merged them there was a conflict so we
|
||||
did this to avoid moving the endpoint docs to another URL.
|
||||
|
||||
Never ever do this again.
|
||||
*/
|
||||
if (match[0] === '/endpoint' && Object.keys(queryParams).length === 0) {
|
||||
ask.res.statusCode = 301
|
||||
ask.res.setHeader('Location', '/endpoint/')
|
||||
ask.res.end()
|
||||
return
|
||||
}
|
||||
const reqTime = new Date()
|
||||
|
||||
// `defaultCacheLengthSeconds` can be overridden by
|
||||
// `serviceDefaultCacheLengthSeconds` (either by category or on a badge-
|
||||
@@ -131,10 +135,49 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
filteredQueryParams[key] = queryParams[key]
|
||||
})
|
||||
|
||||
// Use sindresorhus query-string because it sorts the keys, whereas the
|
||||
// builtin querystring module relies on the iteration order.
|
||||
const stringified = queryString.stringify(filteredQueryParams)
|
||||
const cacheIndex = `${match[0]}?${stringified}`
|
||||
|
||||
// Should we return the data right away?
|
||||
const cached = requestCache.get(cacheIndex)
|
||||
let cachedVersionSent = false
|
||||
if (cached !== undefined) {
|
||||
// A request was made not long ago.
|
||||
const tooSoon = +reqTime - cached.time < cached.interval
|
||||
if (tooSoon || cached.dataChange / cached.reqs <= freqRatioMax) {
|
||||
const svg = makeBadge(cached.data.badgeData)
|
||||
setCacheHeadersOnResponse(
|
||||
ask.res,
|
||||
cached.data.badgeData.cacheLengthSeconds
|
||||
)
|
||||
makeSend(cached.data.format, ask.res, end)(svg)
|
||||
cachedVersionSent = true
|
||||
// We do not wish to call the vendor servers.
|
||||
if (tooSoon) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// In case our vendor servers are unresponsive.
|
||||
let serverUnresponsive = false
|
||||
const serverResponsive = setTimeout(() => {
|
||||
serverUnresponsive = true
|
||||
if (cachedVersionSent) {
|
||||
return
|
||||
}
|
||||
if (requestCache.has(cacheIndex)) {
|
||||
const cached = requestCache.get(cacheIndex)
|
||||
const svg = makeBadge(cached.data.badgeData)
|
||||
setCacheHeadersOnResponse(
|
||||
ask.res,
|
||||
cached.data.badgeData.cacheLengthSeconds
|
||||
)
|
||||
makeSend(cached.data.format, ask.res, end)(svg)
|
||||
return
|
||||
}
|
||||
ask.res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
|
||||
const badgeData = coalesceBadge(
|
||||
filteredQueryParams,
|
||||
@@ -147,6 +190,8 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
makeSend(extension, ask.res, end)(svg)
|
||||
}, 25000)
|
||||
|
||||
// Only call vendor servers when last request is older than…
|
||||
let cacheInterval = 5000 // milliseconds
|
||||
function cachingRequest(uri, options, callback) {
|
||||
if (typeof options === 'function' && !callback) {
|
||||
callback = options
|
||||
@@ -159,10 +204,24 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
options = uri
|
||||
}
|
||||
options.headers = options.headers || {}
|
||||
options.headers['User-Agent'] = userAgent
|
||||
options.headers['User-Agent'] =
|
||||
options.headers['User-Agent'] || 'Shields.io'
|
||||
|
||||
let bufferLength = 0
|
||||
const r = request(options, callback)
|
||||
const r = request(options, (err, res, body) => {
|
||||
if (res != null && res.headers != null) {
|
||||
const cacheControl = res.headers['cache-control']
|
||||
if (cacheControl != null) {
|
||||
const age = cacheControl.match(/max-age=([0-9]+)/)
|
||||
// Would like to get some more test coverage on this before changing it.
|
||||
// eslint-disable-next-line no-self-compare
|
||||
if (age != null && +age[1] === +age[1]) {
|
||||
cacheInterval = +age[1] * 1000
|
||||
}
|
||||
}
|
||||
}
|
||||
callback(err, res, body)
|
||||
})
|
||||
r.on('data', chunk => {
|
||||
bufferLength += chunk.length
|
||||
if (bufferLength > fetchLimitBytes) {
|
||||
@@ -190,11 +249,30 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
return
|
||||
}
|
||||
clearTimeout(serverResponsive)
|
||||
// Check for a change in the data.
|
||||
let dataHasChanged = false
|
||||
if (
|
||||
cached !== undefined &&
|
||||
cached.data.badgeData.text[1] !== badgeData.text[1]
|
||||
) {
|
||||
dataHasChanged = true
|
||||
}
|
||||
// Add format to badge data.
|
||||
badgeData.format = format
|
||||
const svg = makeBadge(badgeData)
|
||||
setCacheHeadersOnResponse(ask.res, badgeData.cacheLengthSeconds)
|
||||
makeSend(format, ask.res, end)(svg)
|
||||
// Update information in the cache.
|
||||
const updatedCache = {
|
||||
reqs: cached ? cached.reqs + 1 : 1,
|
||||
dataChange: cached ? cached.dataChange + (dataHasChanged ? 1 : 0) : 1,
|
||||
time: +reqTime,
|
||||
interval: cacheInterval,
|
||||
data: { format, badgeData },
|
||||
}
|
||||
requestCache.set(cacheIndex, updatedCache)
|
||||
if (!cachedVersionSent) {
|
||||
const svg = makeBadge(badgeData)
|
||||
setCacheHeadersOnResponse(ask.res, badgeData.cacheLengthSeconds)
|
||||
makeSend(format, ask.res, end)(svg)
|
||||
}
|
||||
},
|
||||
cachingRequest
|
||||
)
|
||||
@@ -206,8 +284,14 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
function clearRequestCache() {
|
||||
requestCache.clear()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
handleRequest,
|
||||
promisify,
|
||||
userAgent,
|
||||
clearRequestCache,
|
||||
// Expose for testing.
|
||||
_requestCache: requestCache,
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@
|
||||
const { expect } = require('chai')
|
||||
const nock = require('nock')
|
||||
const portfinder = require('portfinder')
|
||||
const Camp = require('@shields_io/camp')
|
||||
const Camp = require('camp')
|
||||
const got = require('../got-test-client')
|
||||
const coalesceBadge = require('./coalesce-badge')
|
||||
const { handleRequest } = require('./legacy-request-handler')
|
||||
const {
|
||||
handleRequest,
|
||||
clearRequestCache,
|
||||
_requestCache,
|
||||
} = require('./legacy-request-handler')
|
||||
|
||||
async function performTwoRequests(baseUrl, first, second) {
|
||||
expect((await got(`${baseUrl}${first}`)).statusCode).to.equal(200)
|
||||
@@ -66,19 +70,20 @@ function fakeHandlerWithNetworkIo(queryParams, match, sendBadge, request) {
|
||||
})
|
||||
}
|
||||
|
||||
describe('The request handler', function () {
|
||||
describe('The request handler', function() {
|
||||
let port, baseUrl
|
||||
beforeEach(async function () {
|
||||
beforeEach(async function() {
|
||||
port = await portfinder.getPortPromise()
|
||||
baseUrl = `http://127.0.0.1:${port}`
|
||||
})
|
||||
|
||||
let camp
|
||||
beforeEach(function (done) {
|
||||
beforeEach(function(done) {
|
||||
camp = Camp.start({ port, hostname: '::' })
|
||||
camp.on('listening', () => done())
|
||||
})
|
||||
afterEach(function (done) {
|
||||
afterEach(function(done) {
|
||||
clearRequestCache()
|
||||
if (camp) {
|
||||
camp.close(() => done())
|
||||
camp = null
|
||||
@@ -87,17 +92,17 @@ describe('The request handler', function () {
|
||||
|
||||
const standardCacheHeaders = { defaultCacheLengthSeconds: 120 }
|
||||
|
||||
describe('the options object calling style', function () {
|
||||
beforeEach(function () {
|
||||
describe('the options object calling style', function() {
|
||||
beforeEach(function() {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(standardCacheHeaders, { handler: fakeHandler })
|
||||
)
|
||||
})
|
||||
|
||||
it('should return the expected response', async function () {
|
||||
it('should return the expected response', async function() {
|
||||
const { statusCode, body } = await got(`${baseUrl}/testing/123.json`, {
|
||||
responseType: 'json',
|
||||
json: true,
|
||||
})
|
||||
expect(statusCode).to.equal(200)
|
||||
expect(body).to.deep.equal({
|
||||
@@ -111,17 +116,17 @@ describe('The request handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('the function shorthand calling style', function () {
|
||||
beforeEach(function () {
|
||||
describe('the function shorthand calling style', function() {
|
||||
beforeEach(function() {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(standardCacheHeaders, fakeHandler)
|
||||
)
|
||||
})
|
||||
|
||||
it('should return the expected response', async function () {
|
||||
it('should return the expected response', async function() {
|
||||
const { statusCode, body } = await got(`${baseUrl}/testing/123.json`, {
|
||||
responseType: 'json',
|
||||
json: true,
|
||||
})
|
||||
expect(statusCode).to.equal(200)
|
||||
expect(body).to.deep.equal({
|
||||
@@ -135,8 +140,8 @@ describe('The request handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('the response size limit', function () {
|
||||
beforeEach(function () {
|
||||
describe('the response size limit', function() {
|
||||
beforeEach(function() {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(standardCacheHeaders, {
|
||||
@@ -146,13 +151,13 @@ describe('The request handler', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should not throw an error if the response <= fetchLimitBytes', async function () {
|
||||
it('should not throw an error if the response <= fetchLimitBytes', async function() {
|
||||
nock('https://www.google.com')
|
||||
.get('/foo/bar')
|
||||
.once()
|
||||
.reply(200, 'x'.repeat(100))
|
||||
const { statusCode, body } = await got(`${baseUrl}/testing/123.json`, {
|
||||
responseType: 'json',
|
||||
json: true,
|
||||
})
|
||||
expect(statusCode).to.equal(200)
|
||||
expect(body).to.deep.equal({
|
||||
@@ -165,13 +170,13 @@ describe('The request handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error if the response is > fetchLimitBytes', async function () {
|
||||
it('should throw an error if the response is > fetchLimitBytes', async function() {
|
||||
nock('https://www.google.com')
|
||||
.get('/foo/bar')
|
||||
.once()
|
||||
.reply(200, 'x'.repeat(101))
|
||||
const { statusCode, body } = await got(`${baseUrl}/testing/123.json`, {
|
||||
responseType: 'json',
|
||||
json: true,
|
||||
})
|
||||
expect(statusCode).to.equal(200)
|
||||
expect(body).to.deep.equal({
|
||||
@@ -184,36 +189,75 @@ describe('The request handler', function () {
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(function () {
|
||||
afterEach(function() {
|
||||
nock.cleanAll()
|
||||
})
|
||||
})
|
||||
|
||||
describe('caching', function () {
|
||||
describe('standard query parameters', function () {
|
||||
describe('caching', function() {
|
||||
describe('standard query parameters', function() {
|
||||
let handlerCallCount
|
||||
beforeEach(function() {
|
||||
handlerCallCount = 0
|
||||
})
|
||||
|
||||
function register({ cacheHeaderConfig }) {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(
|
||||
cacheHeaderConfig,
|
||||
(queryParams, match, sendBadge, request) => {
|
||||
++handlerCallCount
|
||||
fakeHandler(queryParams, match, sendBadge, request)
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
it('should set the expires header to current time + defaultCacheLengthSeconds', async function () {
|
||||
context('With standard cache settings', function() {
|
||||
beforeEach(function() {
|
||||
register({ cacheHeaderConfig: standardCacheHeaders })
|
||||
})
|
||||
|
||||
it('should cache identical requests', async function() {
|
||||
await performTwoRequests(
|
||||
baseUrl,
|
||||
'/testing/123.svg',
|
||||
'/testing/123.svg'
|
||||
)
|
||||
expect(handlerCallCount).to.equal(1)
|
||||
})
|
||||
|
||||
it('should differentiate known query parameters', async function() {
|
||||
await performTwoRequests(
|
||||
baseUrl,
|
||||
'/testing/123.svg?label=foo',
|
||||
'/testing/123.svg?label=bar'
|
||||
)
|
||||
expect(handlerCallCount).to.equal(2)
|
||||
})
|
||||
|
||||
it('should ignore unknown query parameters', async function() {
|
||||
await performTwoRequests(
|
||||
baseUrl,
|
||||
'/testing/123.svg?foo=1',
|
||||
'/testing/123.svg?foo=2'
|
||||
)
|
||||
expect(handlerCallCount).to.equal(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('should set the expires header to current time + defaultCacheLengthSeconds', async function() {
|
||||
register({ cacheHeaderConfig: { defaultCacheLengthSeconds: 900 } })
|
||||
const { headers } = await got(`${baseUrl}/testing/123.json`)
|
||||
const expectedExpiry = new Date(
|
||||
+new Date(headers.date) + 900000
|
||||
).toGMTString()
|
||||
expect(headers.expires).to.equal(expectedExpiry)
|
||||
expect(headers['cache-control']).to.equal('max-age=900, s-maxage=900')
|
||||
expect(headers['cache-control']).to.equal('max-age=900')
|
||||
})
|
||||
|
||||
it('should set the expected cache headers on cached responses', async function () {
|
||||
it('should set the expected cache headers on cached responses', async function() {
|
||||
register({ cacheHeaderConfig: { defaultCacheLengthSeconds: 900 } })
|
||||
|
||||
// Make first request.
|
||||
@@ -224,15 +268,16 @@ describe('The request handler', function () {
|
||||
+new Date(headers.date) + 900000
|
||||
).toGMTString()
|
||||
expect(headers.expires).to.equal(expectedExpiry)
|
||||
expect(headers['cache-control']).to.equal('max-age=900, s-maxage=900')
|
||||
expect(headers['cache-control']).to.equal('max-age=900')
|
||||
})
|
||||
|
||||
it('should let live service data override the default cache headers with longer value', async function () {
|
||||
it('should let live service data override the default cache headers with longer value', async function() {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(
|
||||
{ defaultCacheLengthSeconds: 300 },
|
||||
(queryParams, match, sendBadge, request) => {
|
||||
++handlerCallCount
|
||||
createFakeHandlerWithCacheLength(400)(
|
||||
queryParams,
|
||||
match,
|
||||
@@ -244,15 +289,16 @@ describe('The request handler', function () {
|
||||
)
|
||||
|
||||
const { headers } = await got(`${baseUrl}/testing/123.json`)
|
||||
expect(headers['cache-control']).to.equal('max-age=400, s-maxage=400')
|
||||
expect(headers['cache-control']).to.equal('max-age=400')
|
||||
})
|
||||
|
||||
it('should not let live service data override the default cache headers with shorter value', async function () {
|
||||
it('should not let live service data override the default cache headers with shorter value', async function() {
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
handleRequest(
|
||||
{ defaultCacheLengthSeconds: 300 },
|
||||
(queryParams, match, sendBadge, request) => {
|
||||
++handlerCallCount
|
||||
createFakeHandlerWithCacheLength(200)(
|
||||
queryParams,
|
||||
match,
|
||||
@@ -264,10 +310,10 @@ describe('The request handler', function () {
|
||||
)
|
||||
|
||||
const { headers } = await got(`${baseUrl}/testing/123.json`)
|
||||
expect(headers['cache-control']).to.equal('max-age=300, s-maxage=300')
|
||||
expect(headers['cache-control']).to.equal('max-age=300')
|
||||
})
|
||||
|
||||
it('should set the expires header to current time + cacheSeconds', async function () {
|
||||
it('should set the expires header to current time + cacheSeconds', async function() {
|
||||
register({ cacheHeaderConfig: { defaultCacheLengthSeconds: 0 } })
|
||||
const { headers } = await got(
|
||||
`${baseUrl}/testing/123.json?cacheSeconds=3600`
|
||||
@@ -276,10 +322,10 @@ describe('The request handler', function () {
|
||||
+new Date(headers.date) + 3600000
|
||||
).toGMTString()
|
||||
expect(headers.expires).to.equal(expectedExpiry)
|
||||
expect(headers['cache-control']).to.equal('max-age=3600, s-maxage=3600')
|
||||
expect(headers['cache-control']).to.equal('max-age=3600')
|
||||
})
|
||||
|
||||
it('should ignore cacheSeconds when shorter than defaultCacheLengthSeconds', async function () {
|
||||
it('should ignore cacheSeconds when shorter than defaultCacheLengthSeconds', async function() {
|
||||
register({ cacheHeaderConfig: { defaultCacheLengthSeconds: 600 } })
|
||||
const { headers } = await got(
|
||||
`${baseUrl}/testing/123.json?cacheSeconds=300`
|
||||
@@ -288,10 +334,10 @@ describe('The request handler', function () {
|
||||
+new Date(headers.date) + 600000
|
||||
).toGMTString()
|
||||
expect(headers.expires).to.equal(expectedExpiry)
|
||||
expect(headers['cache-control']).to.equal('max-age=600, s-maxage=600')
|
||||
expect(headers['cache-control']).to.equal('max-age=600')
|
||||
})
|
||||
|
||||
it('should set Cache-Control: no-cache, no-store, must-revalidate if cache seconds is 0', async function () {
|
||||
it('should set Cache-Control: no-cache, no-store, must-revalidate if cache seconds is 0', async function() {
|
||||
register({ cacheHeaderConfig: { defaultCacheLengthSeconds: 0 } })
|
||||
const { headers } = await got(`${baseUrl}/testing/123.json`)
|
||||
expect(headers.expires).to.equal(headers.date)
|
||||
@@ -299,11 +345,26 @@ describe('The request handler', function () {
|
||||
'no-cache, no-store, must-revalidate'
|
||||
)
|
||||
})
|
||||
|
||||
describe('the cache key', function() {
|
||||
beforeEach(function() {
|
||||
register({ cacheHeaderConfig: standardCacheHeaders })
|
||||
})
|
||||
const expectedCacheKey = '/testing/123.json?color=123&label=foo'
|
||||
it('should match expected and use canonical order - 1', async function() {
|
||||
await got(`${baseUrl}/testing/123.json?color=123&label=foo`)
|
||||
expect(_requestCache.cache).to.have.keys(expectedCacheKey)
|
||||
})
|
||||
it('should match expected and use canonical order - 2', async function() {
|
||||
await got(`${baseUrl}/testing/123.json?label=foo&color=123`)
|
||||
expect(_requestCache.cache).to.have.keys(expectedCacheKey)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('custom query parameters', function () {
|
||||
describe('custom query parameters', function() {
|
||||
let handlerCallCount
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
handlerCallCount = 0
|
||||
camp.route(
|
||||
/^\/testing\/([^/]+)\.(svg|png|gif|jpg|json)$/,
|
||||
@@ -317,7 +378,7 @@ describe('The request handler', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should differentiate them', async function () {
|
||||
it('should differentiate them', async function() {
|
||||
await performTwoRequests(
|
||||
baseUrl,
|
||||
'/testing/123.svg?foo=1',
|
||||
|
||||
@@ -3,12 +3,28 @@
|
||||
const BaseJsonService = require('../base-json')
|
||||
|
||||
class GoodServiceOne extends BaseJsonService {
|
||||
static category = 'build'
|
||||
static route = { base: 'good', pattern: 'one' }
|
||||
static get category() {
|
||||
return 'build'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'good',
|
||||
pattern: 'one',
|
||||
}
|
||||
}
|
||||
}
|
||||
class GoodServiceTwo extends BaseJsonService {
|
||||
static category = 'build'
|
||||
static route = { base: 'good', pattern: 'two' }
|
||||
static get category() {
|
||||
return 'build'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'good',
|
||||
pattern: 'two',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = [GoodServiceOne, GoodServiceTwo]
|
||||
|
||||
@@ -3,8 +3,16 @@
|
||||
const BaseJsonService = require('../base-json')
|
||||
|
||||
class GoodService extends BaseJsonService {
|
||||
static category = 'build'
|
||||
static route = { base: 'it/is', pattern: 'good' }
|
||||
static get category() {
|
||||
return 'build'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'it/is',
|
||||
pattern: 'good',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GoodService
|
||||
|
||||
@@ -3,12 +3,28 @@
|
||||
const BaseJsonService = require('../base-json')
|
||||
|
||||
class GoodServiceOne extends BaseJsonService {
|
||||
static category = 'build'
|
||||
static route = { base: 'good', pattern: 'one' }
|
||||
static get category() {
|
||||
return 'build'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'good',
|
||||
pattern: 'one',
|
||||
}
|
||||
}
|
||||
}
|
||||
class GoodServiceTwo extends BaseJsonService {
|
||||
static category = 'build'
|
||||
static route = { base: 'good', pattern: 'two' }
|
||||
static get category() {
|
||||
return 'build'
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return {
|
||||
base: 'good',
|
||||
pattern: 'two',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { GoodServiceOne, GoodServiceTwo }
|
||||
|
||||
@@ -82,12 +82,9 @@ function assertNamesUnique(names, { message }) {
|
||||
|
||||
function checkNames() {
|
||||
const services = loadServiceClasses()
|
||||
assertNamesUnique(
|
||||
services.map(({ name }) => name),
|
||||
{
|
||||
message: 'Duplicate service names found',
|
||||
}
|
||||
)
|
||||
assertNamesUnique(services.map(({ name }) => name), {
|
||||
message: 'Duplicate service names found',
|
||||
})
|
||||
}
|
||||
|
||||
function collectDefinitions() {
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
const { expect } = require('chai')
|
||||
const { loadServiceClasses, InvalidService } = require('./loader')
|
||||
|
||||
describe('loadServiceClasses function', function () {
|
||||
it('throws if module exports empty', function () {
|
||||
describe('loadServiceClasses function', function() {
|
||||
it('throws if module exports empty', function() {
|
||||
expect(() =>
|
||||
loadServiceClasses(['./loader-test-fixtures/empty-undefined.fixture.js'])
|
||||
).to.throw(InvalidService)
|
||||
@@ -26,7 +26,7 @@ describe('loadServiceClasses function', function () {
|
||||
).to.throw(InvalidService)
|
||||
})
|
||||
|
||||
it('throws if module exports invalid', function () {
|
||||
it('throws if module exports invalid', function() {
|
||||
expect(() =>
|
||||
loadServiceClasses(['./loader-test-fixtures/invalid-no-base.fixture.js'])
|
||||
).to.throw(InvalidService)
|
||||
@@ -47,7 +47,7 @@ describe('loadServiceClasses function', function () {
|
||||
).to.throw(InvalidService)
|
||||
})
|
||||
|
||||
it('registers services if module exports valid service classes', function () {
|
||||
it('registers services if module exports valid service classes', function() {
|
||||
expect(
|
||||
loadServiceClasses([
|
||||
'./loader-test-fixtures/valid-array.fixture.js',
|
||||
|
||||
136
core/base-service/lru-cache.js
Normal file
136
core/base-service/lru-cache.js
Normal file
@@ -0,0 +1,136 @@
|
||||
'use strict'
|
||||
|
||||
// In-memory KV, remove the oldest data when the capacity is reached.
|
||||
|
||||
const typeEnum = {
|
||||
unit: 0,
|
||||
heap: 1,
|
||||
}
|
||||
|
||||
// In bytes.
|
||||
let heapSize
|
||||
function computeHeapSize() {
|
||||
return (heapSize = process.memoryUsage().heapTotal)
|
||||
}
|
||||
|
||||
let heapSizeTimeout
|
||||
function getHeapSize() {
|
||||
if (heapSizeTimeout == null) {
|
||||
// Compute the heap size every 60 seconds.
|
||||
heapSizeTimeout = setInterval(computeHeapSize, 60 * 1000)
|
||||
return computeHeapSize()
|
||||
} else {
|
||||
return heapSize
|
||||
}
|
||||
}
|
||||
|
||||
function CacheSlot(key, value) {
|
||||
this.key = key
|
||||
this.value = value
|
||||
this.older = null // Newest slot that is older than this slot.
|
||||
this.newer = null // Oldest slot that is newer than this slot.
|
||||
}
|
||||
|
||||
function Cache(capacity, type) {
|
||||
type = type || 'unit'
|
||||
this.capacity = capacity
|
||||
this.type = typeEnum[type]
|
||||
this.cache = new Map() // Maps cache keys to CacheSlots.
|
||||
this.newest = null // Newest slot in the cache.
|
||||
this.oldest = null
|
||||
}
|
||||
|
||||
Cache.prototype = {
|
||||
set: function addToCache(cacheKey, cached) {
|
||||
let slot = this.cache.get(cacheKey)
|
||||
if (slot === undefined) {
|
||||
slot = new CacheSlot(cacheKey, cached)
|
||||
this.cache.set(cacheKey, slot)
|
||||
}
|
||||
this.makeNewest(slot)
|
||||
const numItemsToRemove = this.limitReached()
|
||||
if (numItemsToRemove > 0) {
|
||||
for (let i = 0; i < numItemsToRemove; i++) {
|
||||
this.removeOldest()
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
get: function getFromCache(cacheKey) {
|
||||
const slot = this.cache.get(cacheKey)
|
||||
if (slot !== undefined) {
|
||||
this.makeNewest(slot)
|
||||
return slot.value
|
||||
}
|
||||
},
|
||||
|
||||
has: function hasInCache(cacheKey) {
|
||||
return this.cache.has(cacheKey)
|
||||
},
|
||||
|
||||
makeNewest: function makeNewestSlot(slot) {
|
||||
const previousNewest = this.newest
|
||||
if (previousNewest === slot) {
|
||||
return
|
||||
}
|
||||
const older = slot.older
|
||||
const newer = slot.newer
|
||||
|
||||
if (older !== null) {
|
||||
older.newer = newer
|
||||
} else if (newer !== null) {
|
||||
this.oldest = newer
|
||||
}
|
||||
if (newer !== null) {
|
||||
newer.older = older
|
||||
}
|
||||
this.newest = slot
|
||||
|
||||
if (previousNewest !== null) {
|
||||
slot.older = previousNewest
|
||||
slot.newer = null
|
||||
previousNewest.newer = slot
|
||||
} else {
|
||||
// If previousNewest is null, the cache used to be empty.
|
||||
this.oldest = slot
|
||||
}
|
||||
},
|
||||
|
||||
removeOldest: function removeOldest() {
|
||||
const cacheKey = this.oldest.key
|
||||
if (this.oldest !== null) {
|
||||
this.oldest = this.oldest.newer
|
||||
if (this.oldest !== null) {
|
||||
this.oldest.older = null
|
||||
}
|
||||
}
|
||||
this.cache.delete(cacheKey)
|
||||
},
|
||||
|
||||
// Returns the number of elements to remove if we're past the limit.
|
||||
limitReached: function heuristic() {
|
||||
if (this.type === typeEnum.unit) {
|
||||
// Remove the excess.
|
||||
return Math.max(0, this.cache.size - this.capacity)
|
||||
} else if (this.type === typeEnum.heap) {
|
||||
if (getHeapSize() >= this.capacity) {
|
||||
console.log('LRU HEURISTIC heap:', getHeapSize())
|
||||
// Remove half of them.
|
||||
return this.cache.size >> 1
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
} else {
|
||||
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
|
||||
return 1
|
||||
}
|
||||
},
|
||||
|
||||
clear: function() {
|
||||
this.cache.clear()
|
||||
this.newest = null
|
||||
this.oldest = null
|
||||
},
|
||||
}
|
||||
|
||||
module.exports = Cache
|
||||
134
core/base-service/lru-cache.spec.js
Normal file
134
core/base-service/lru-cache.spec.js
Normal file
@@ -0,0 +1,134 @@
|
||||
'use strict'
|
||||
|
||||
const { expect } = require('chai')
|
||||
const LRU = require('./lru-cache')
|
||||
|
||||
function expectCacheSlots(cache, keys) {
|
||||
expect(cache.cache.size).to.equal(keys.length)
|
||||
|
||||
const slots = keys.map(k => cache.cache.get(k))
|
||||
|
||||
const first = slots[0]
|
||||
const last = slots.slice(-1)[0]
|
||||
|
||||
expect(cache.oldest).to.equal(first)
|
||||
expect(cache.newest).to.equal(last)
|
||||
|
||||
expect(first.older).to.be.null
|
||||
expect(last.newer).to.be.null
|
||||
|
||||
for (let i = 0; i + 1 < slots.length; ++i) {
|
||||
const current = slots[i]
|
||||
const next = slots[i + 1]
|
||||
expect(current.newer).to.equal(next)
|
||||
expect(next.older).to.equal(current)
|
||||
}
|
||||
}
|
||||
|
||||
describe('The LRU cache', function() {
|
||||
it('should support a zero capacity', function() {
|
||||
const cache = new LRU(0)
|
||||
cache.set('key', 'value')
|
||||
expect(cache.cache.size).to.equal(0)
|
||||
})
|
||||
|
||||
it('should support a one capacity', function() {
|
||||
const cache = new LRU(1)
|
||||
cache.set('key1', 'value1')
|
||||
expectCacheSlots(cache, ['key1'])
|
||||
cache.set('key2', 'value2')
|
||||
expectCacheSlots(cache, ['key2'])
|
||||
expect(cache.get('key1')).to.be.undefined
|
||||
expect(cache.get('key2')).to.equal('value2')
|
||||
})
|
||||
|
||||
it('should remove the oldest element when reaching capacity', function() {
|
||||
const cache = new LRU(2)
|
||||
|
||||
cache.set('key1', 'value1')
|
||||
cache.set('key2', 'value2')
|
||||
cache.set('key3', 'value3')
|
||||
cache.cache.get('key1')
|
||||
|
||||
expectCacheSlots(cache, ['key2', 'key3'])
|
||||
expect(cache.cache.get('key1')).to.be.undefined
|
||||
expect(cache.get('key1')).to.be.undefined
|
||||
expect(cache.get('key2')).to.equal('value2')
|
||||
expect(cache.get('key3')).to.equal('value3')
|
||||
})
|
||||
|
||||
it('should make sure that resetting a key in cache makes it newest', function() {
|
||||
const cache = new LRU(2)
|
||||
|
||||
cache.set('key', 'value')
|
||||
cache.set('key2', 'value2')
|
||||
|
||||
expectCacheSlots(cache, ['key', 'key2'])
|
||||
|
||||
cache.set('key', 'value')
|
||||
|
||||
expectCacheSlots(cache, ['key2', 'key'])
|
||||
})
|
||||
|
||||
describe('getting a key in the cache', function() {
|
||||
context('when the requested key is oldest', function() {
|
||||
it('should leave the keys in the expected order', function() {
|
||||
const cache = new LRU(2)
|
||||
cache.set('key1', 'value1')
|
||||
cache.set('key2', 'value2')
|
||||
|
||||
expectCacheSlots(cache, ['key1', 'key2'])
|
||||
|
||||
expect(cache.get('key1')).to.equal('value1')
|
||||
|
||||
expectCacheSlots(cache, ['key2', 'key1'])
|
||||
})
|
||||
})
|
||||
|
||||
context('when the requested key is newest', function() {
|
||||
it('should leave the keys in the expected order', function() {
|
||||
const cache = new LRU(2)
|
||||
cache.set('key1', 'value1')
|
||||
cache.set('key2', 'value2')
|
||||
|
||||
expect(cache.get('key2')).to.equal('value2')
|
||||
|
||||
expectCacheSlots(cache, ['key1', 'key2'])
|
||||
})
|
||||
})
|
||||
|
||||
context('when the requested key is in the middle', function() {
|
||||
it('should leave the keys in the expected order', function() {
|
||||
const cache = new LRU(3)
|
||||
cache.set('key1', 'value1')
|
||||
cache.set('key2', 'value2')
|
||||
cache.set('key3', 'value3')
|
||||
|
||||
expectCacheSlots(cache, ['key1', 'key2', 'key3'])
|
||||
|
||||
expect(cache.get('key2')).to.equal('value2')
|
||||
|
||||
expectCacheSlots(cache, ['key1', 'key3', 'key2'])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('should clear', function() {
|
||||
// Set up.
|
||||
const cache = new LRU(2)
|
||||
cache.set('key1', 'value1')
|
||||
cache.set('key2', 'value2')
|
||||
|
||||
// Confidence check.
|
||||
expect(cache.get('key1')).to.equal('value1')
|
||||
expect(cache.get('key2')).to.equal('value2')
|
||||
|
||||
// Run.
|
||||
cache.clear()
|
||||
|
||||
// Test.
|
||||
expect(cache.get('key1')).to.be.undefined
|
||||
expect(cache.get('key2')).to.be.undefined
|
||||
expect(cache.cache.size).to.equal(0)
|
||||
})
|
||||
})
|
||||
@@ -11,17 +11,9 @@ class MetricHelper {
|
||||
serviceFamily,
|
||||
name,
|
||||
})
|
||||
this.serviceResponseSizeHistogram = metricInstance.createServiceResponseSizeHistogram(
|
||||
{
|
||||
category,
|
||||
serviceFamily,
|
||||
name,
|
||||
}
|
||||
)
|
||||
} else {
|
||||
this.metricInstance = undefined
|
||||
this.serviceRequestCounter = undefined
|
||||
this.serviceResponseSizeHistogram = undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,16 +40,6 @@ class MetricHelper {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
noteServiceResponseSize(size) {
|
||||
if (this.serviceResponseSizeHistogram) {
|
||||
return this.serviceResponseSizeHistogram.observe(size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MetricNames = Object.freeze({
|
||||
SERVICE_RESPONSE_SIZE: Symbol('service-response-size'),
|
||||
})
|
||||
|
||||
module.exports = { MetricHelper, MetricNames }
|
||||
module.exports = { MetricHelper }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
const camelcase = require('camelcase')
|
||||
const emojic = require('emojic')
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const queryString = require('query-string')
|
||||
const BaseService = require('./base')
|
||||
const {
|
||||
@@ -41,15 +41,27 @@ module.exports = function redirector(attrs) {
|
||||
} = Joi.attempt(attrs, attrSchema, `Redirector for ${attrs.route.base}`)
|
||||
|
||||
return class Redirector extends BaseService {
|
||||
static name =
|
||||
name ||
|
||||
`${camelcase(route.base.replace(/\//g, '_'), {
|
||||
pascalCase: true,
|
||||
})}Redirect`
|
||||
static get name() {
|
||||
if (name) {
|
||||
return name
|
||||
} else {
|
||||
return `${camelcase(route.base.replace(/\//g, '_'), {
|
||||
pascalCase: true,
|
||||
})}Redirect`
|
||||
}
|
||||
}
|
||||
|
||||
static category = category
|
||||
static isDeprecated = true
|
||||
static route = route
|
||||
static get category() {
|
||||
return category
|
||||
}
|
||||
|
||||
static get isDeprecated() {
|
||||
return true
|
||||
}
|
||||
|
||||
static get route() {
|
||||
return route
|
||||
}
|
||||
|
||||
static register({ camp, metricInstance }, { rasterUrl }) {
|
||||
const { regex, captureNames } = prepareRoute({
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use strict'
|
||||
|
||||
const Camp = require('@shields_io/camp')
|
||||
const Camp = require('camp')
|
||||
const portfinder = require('portfinder')
|
||||
const { expect } = require('chai')
|
||||
const got = require('../got-test-client')
|
||||
const redirector = require('./redirector')
|
||||
|
||||
describe('Redirector', function () {
|
||||
describe('Redirector', function() {
|
||||
const route = {
|
||||
base: 'very/old/service',
|
||||
pattern: ':namedParamA',
|
||||
@@ -16,15 +16,15 @@ describe('Redirector', function () {
|
||||
const dateAdded = new Date()
|
||||
const attrs = { category, route, transformPath, dateAdded }
|
||||
|
||||
it('returns true on isDeprecated', function () {
|
||||
it('returns true on isDeprecated', function() {
|
||||
expect(redirector(attrs).isDeprecated).to.be.true
|
||||
})
|
||||
|
||||
it('has the expected name', function () {
|
||||
it('has the expected name', function() {
|
||||
expect(redirector(attrs).name).to.equal('VeryOldServiceRedirect')
|
||||
})
|
||||
|
||||
it('overrides the name', function () {
|
||||
it('overrides the name', function() {
|
||||
expect(
|
||||
redirector({
|
||||
...attrs,
|
||||
@@ -33,33 +33,33 @@ describe('Redirector', function () {
|
||||
).to.equal('ShinyRedirect')
|
||||
})
|
||||
|
||||
it('sets specified route', function () {
|
||||
it('sets specified route', function() {
|
||||
expect(redirector(attrs).route).to.deep.equal(route)
|
||||
})
|
||||
|
||||
it('sets specified category', function () {
|
||||
it('sets specified category', function() {
|
||||
expect(redirector(attrs).category).to.equal(category)
|
||||
})
|
||||
|
||||
it('throws the expected error when dateAdded is missing', function () {
|
||||
it('throws the expected error when dateAdded is missing', function() {
|
||||
expect(() =>
|
||||
redirector({ route, category, transformPath }).validateDefinition()
|
||||
).to.throw('"dateAdded" is required')
|
||||
})
|
||||
|
||||
describe('ScoutCamp integration', function () {
|
||||
describe('ScoutCamp integration', function() {
|
||||
let port, baseUrl
|
||||
beforeEach(async function () {
|
||||
beforeEach(async function() {
|
||||
port = await portfinder.getPortPromise()
|
||||
baseUrl = `http://127.0.0.1:${port}`
|
||||
})
|
||||
|
||||
let camp
|
||||
beforeEach(async function () {
|
||||
beforeEach(async function() {
|
||||
camp = Camp.start({ port, hostname: '::' })
|
||||
await new Promise(resolve => camp.on('listening', () => resolve()))
|
||||
})
|
||||
afterEach(async function () {
|
||||
afterEach(async function() {
|
||||
if (camp) {
|
||||
await new Promise(resolve => camp.close(resolve))
|
||||
camp = undefined
|
||||
@@ -68,7 +68,7 @@ describe('Redirector', function () {
|
||||
|
||||
const transformPath = ({ namedParamA }) => `/new/service/${namedParamA}`
|
||||
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
const ServiceClass = redirector({
|
||||
category,
|
||||
route,
|
||||
@@ -81,7 +81,7 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should redirect as configured', async function () {
|
||||
it('should redirect as configured', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/very/old/service/hello-world.svg`,
|
||||
{
|
||||
@@ -93,7 +93,7 @@ describe('Redirector', function () {
|
||||
expect(headers.location).to.equal('/new/service/hello-world.svg')
|
||||
})
|
||||
|
||||
it('should redirect raster extensions to the canonical path as configured', async function () {
|
||||
it('should redirect raster extensions to the canonical path as configured', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/very/old/service/hello-world.png`,
|
||||
{
|
||||
@@ -107,7 +107,7 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward the query params', async function () {
|
||||
it('should forward the query params', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/very/old/service/hello-world.svg?color=123&style=flat-square`,
|
||||
{
|
||||
@@ -121,14 +121,14 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
describe('transformQueryParams', function () {
|
||||
describe('transformQueryParams', function() {
|
||||
const route = {
|
||||
base: 'another/old/service',
|
||||
pattern: 'token/:token/:namedParamA',
|
||||
}
|
||||
const transformQueryParams = ({ token }) => ({ token })
|
||||
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
const ServiceClass = redirector({
|
||||
category,
|
||||
route,
|
||||
@@ -139,7 +139,7 @@ describe('Redirector', function () {
|
||||
ServiceClass.register({ camp }, {})
|
||||
})
|
||||
|
||||
it('should forward the transformed query params', async function () {
|
||||
it('should forward the transformed query params', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/another/old/service/token/abc123/hello-world.svg`,
|
||||
{
|
||||
@@ -153,7 +153,7 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should forward the specified and transformed query params', async function () {
|
||||
it('should forward the specified and transformed query params', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/another/old/service/token/abc123/hello-world.svg?color=123&style=flat-square`,
|
||||
{
|
||||
@@ -167,7 +167,7 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should use transformed query params on param conflicts by default', async function () {
|
||||
it('should use transformed query params on param conflicts by default', async function() {
|
||||
const { statusCode, headers } = await got(
|
||||
`${baseUrl}/another/old/service/token/abc123/hello-world.svg?color=123&style=flat-square&token=def456`,
|
||||
{
|
||||
@@ -181,7 +181,7 @@ describe('Redirector', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('should use specified query params on param conflicts when configured', async function () {
|
||||
it('should use specified query params on param conflicts when configured', async function() {
|
||||
const route = {
|
||||
base: 'override/service',
|
||||
pattern: 'token/:token/:namedParamA',
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
'use strict'
|
||||
|
||||
const escapeStringRegexp = require('escape-string-regexp')
|
||||
const Joi = require('joi')
|
||||
const { pathToRegexp } = require('path-to-regexp')
|
||||
const Joi = require('@hapi/joi')
|
||||
const pathToRegexp = require('path-to-regexp')
|
||||
|
||||
function makeFullUrl(base, partialUrl) {
|
||||
return `/${[base, partialUrl].filter(Boolean).join('/')}`
|
||||
}
|
||||
|
||||
const isValidRoute = Joi.object({
|
||||
base: Joi.string().allow('').required(),
|
||||
base: Joi.string()
|
||||
.allow('')
|
||||
.required(),
|
||||
pattern: Joi.string().allow(''),
|
||||
format: Joi.string(),
|
||||
capture: Joi.alternatives().conditional('format', {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const { expect } = require('chai')
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { test, given, forCases } = require('sazerac')
|
||||
const {
|
||||
prepareRoute,
|
||||
@@ -9,8 +9,8 @@ const {
|
||||
getQueryParamNames,
|
||||
} = require('./route')
|
||||
|
||||
describe('Route helpers', function () {
|
||||
context('A `pattern` with a named param is declared', function () {
|
||||
describe('Route helpers', function() {
|
||||
context('A `pattern` with a named param is declared', function() {
|
||||
const { regex, captureNames } = prepareRoute({
|
||||
base: 'foo',
|
||||
pattern: ':namedParamA',
|
||||
@@ -36,7 +36,7 @@ describe('Route helpers', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('A `format` with a named param is declared', function () {
|
||||
context('A `format` with a named param is declared', function() {
|
||||
const { regex, captureNames } = prepareRoute({
|
||||
base: 'foo',
|
||||
format: '([^/]+?)',
|
||||
@@ -62,7 +62,7 @@ describe('Route helpers', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('No named params are declared', function () {
|
||||
context('No named params are declared', function() {
|
||||
const { regex, captureNames } = prepareRoute({
|
||||
base: 'foo',
|
||||
format: '(?:[^/]+)',
|
||||
@@ -78,7 +78,7 @@ describe('Route helpers', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('The wrong number of params are declared', function () {
|
||||
context('The wrong number of params are declared', function() {
|
||||
const { regex, captureNames } = prepareRoute({
|
||||
base: 'foo',
|
||||
format: '([^/]+)/([^/]+)',
|
||||
@@ -94,7 +94,7 @@ describe('Route helpers', function () {
|
||||
)
|
||||
})
|
||||
|
||||
it('getQueryParamNames', function () {
|
||||
it('getQueryParamNames', function() {
|
||||
expect(
|
||||
getQueryParamNames({
|
||||
queryParamSchema: Joi.object({ foo: Joi.string() }).required(),
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
|
||||
// This should be kept in sync with the schema in
|
||||
// `frontend/lib/service-definitions/index.ts`.
|
||||
|
||||
const arrayOfStrings = Joi.array().items(Joi.string()).min(0).required()
|
||||
const arrayOfStrings = Joi.array()
|
||||
.items(Joi.string())
|
||||
.min(0)
|
||||
.required()
|
||||
|
||||
const objectOfKeyValues = Joi.object()
|
||||
.pattern(/./, Joi.string().allow(null))
|
||||
@@ -36,7 +39,9 @@ const serviceDefinition = Joi.object({
|
||||
}).required(),
|
||||
preview: Joi.object({
|
||||
label: Joi.string(),
|
||||
message: Joi.string().allow('').required(),
|
||||
message: Joi.string()
|
||||
.allow('')
|
||||
.required(),
|
||||
color: Joi.string().required(),
|
||||
style: Joi.string(),
|
||||
namedLogo: Joi.string(),
|
||||
@@ -65,7 +70,9 @@ const serviceDefinitionExport = Joi.object({
|
||||
})
|
||||
)
|
||||
.required(),
|
||||
services: Joi.array().items(serviceDefinition).required(),
|
||||
services: Joi.array()
|
||||
.items(serviceDefinition)
|
||||
.required(),
|
||||
}).required()
|
||||
|
||||
function assertValidServiceDefinitionExport(examples, message = undefined) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
const emojic = require('emojic')
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const trace = require('./trace')
|
||||
|
||||
function validate(
|
||||
@@ -21,8 +21,8 @@ function validate(
|
||||
}
|
||||
const options = { abortEarly: false }
|
||||
if (allowAndStripUnknownKeys) {
|
||||
options.allowUnknown = true
|
||||
options.stripUnknown = true
|
||||
options['allowUnknown'] = true
|
||||
options['stripUnknown'] = true
|
||||
}
|
||||
const { error, value } = schema.validate(data, options)
|
||||
if (error) {
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
'use strict'
|
||||
|
||||
const Joi = require('joi')
|
||||
const Joi = require('@hapi/joi')
|
||||
const { expect } = require('chai')
|
||||
const sinon = require('sinon')
|
||||
const trace = require('./trace')
|
||||
const { InvalidParameter } = require('./errors')
|
||||
const validate = require('./validate')
|
||||
|
||||
describe('validate', function () {
|
||||
describe('validate', function() {
|
||||
const schema = Joi.object({
|
||||
requiredString: Joi.string().required(),
|
||||
}).required()
|
||||
|
||||
let sandbox
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox = sinon.createSandbox()
|
||||
})
|
||||
afterEach(function () {
|
||||
afterEach(function() {
|
||||
sandbox.restore()
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach(function() {
|
||||
sandbox.stub(trace, 'logTrace')
|
||||
})
|
||||
|
||||
@@ -35,8 +35,8 @@ describe('validate', function () {
|
||||
traceSuccessMessage,
|
||||
}
|
||||
|
||||
context('schema is not provided', function () {
|
||||
it('throws the expected programmer error', function () {
|
||||
context('schema is not provided', function() {
|
||||
it('throws the expected programmer error', function() {
|
||||
try {
|
||||
validate(options, { requiredString: 'bar' }, undefined)
|
||||
expect.fail('Expected to throw')
|
||||
@@ -47,8 +47,8 @@ describe('validate', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('data matches schema', function () {
|
||||
it('logs the data', function () {
|
||||
context('data matches schema', function() {
|
||||
it('logs the data', function() {
|
||||
validate(options, { requiredString: 'bar' }, schema)
|
||||
expect(trace.logTrace).to.be.calledWithMatch(
|
||||
'validate',
|
||||
@@ -60,8 +60,8 @@ describe('validate', function () {
|
||||
})
|
||||
})
|
||||
|
||||
context('data does not match schema', function () {
|
||||
it('logs the data and throws the expected error', function () {
|
||||
context('data does not match schema', function() {
|
||||
it('logs the data and throws the expected error', function() {
|
||||
try {
|
||||
validate(
|
||||
options,
|
||||
@@ -84,8 +84,8 @@ describe('validate', function () {
|
||||
)
|
||||
})
|
||||
|
||||
context('with includeKeys: true', function () {
|
||||
it('includes keys in the error text', function () {
|
||||
context('with includeKeys: true', function() {
|
||||
it('includes keys in the error text', function() {
|
||||
try {
|
||||
validate(
|
||||
{ ...options, includeKeys: true },
|
||||
@@ -108,7 +108,7 @@ describe('validate', function () {
|
||||
})
|
||||
})
|
||||
|
||||
it('allowAndStripUnknownKeys', function () {
|
||||
it('allowAndStripUnknownKeys', function() {
|
||||
try {
|
||||
validate(
|
||||
{ ...options, allowAndStripUnknownKeys: false, includeKeys: true },
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
'use strict'
|
||||
|
||||
const merge = require('deepmerge')
|
||||
const config = require('config').util.toObject()
|
||||
const portfinder = require('portfinder')
|
||||
const Server = require('./server')
|
||||
|
||||
async function createTestServer(customConfig = {}) {
|
||||
const mergedConfig = merge(config, customConfig)
|
||||
if (!mergedConfig.public.bind.port) {
|
||||
mergedConfig.public.bind.port = await portfinder.getPortPromise()
|
||||
function createTestServer({ port }) {
|
||||
const serverConfig = {
|
||||
...config,
|
||||
public: {
|
||||
...config.public,
|
||||
bind: {
|
||||
...config.public.bind,
|
||||
port,
|
||||
},
|
||||
},
|
||||
}
|
||||
return new Server(mergedConfig)
|
||||
|
||||
return new Server(serverConfig)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
'use strict'
|
||||
const os = require('os')
|
||||
const { promisify } = require('util')
|
||||
const { post } = require('request')
|
||||
const postAsync = promisify(post)
|
||||
const generateInstanceId = require('./instance-id-generator')
|
||||
const { promClientJsonToInfluxV2 } = require('./metrics/format-converters')
|
||||
const log = require('./log')
|
||||
|
||||
module.exports = class InfluxMetrics {
|
||||
constructor(metricInstance, config) {
|
||||
this._metricInstance = metricInstance
|
||||
this._config = config
|
||||
this._instanceId = this.getInstanceId()
|
||||
}
|
||||
|
||||
async sendMetrics() {
|
||||
const auth = {
|
||||
user: this._config.username,
|
||||
pass: this._config.password,
|
||||
}
|
||||
const request = {
|
||||
uri: this._config.url,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: await this.metrics(),
|
||||
timeout: this._config.timeoutMillseconds,
|
||||
auth,
|
||||
}
|
||||
|
||||
let response
|
||||
try {
|
||||
response = await postAsync(request)
|
||||
} catch (error) {
|
||||
log.error(
|
||||
new Error(`Cannot push metrics. Cause: ${error.name}: ${error.message}`)
|
||||
)
|
||||
}
|
||||
if (response && response.statusCode >= 300) {
|
||||
log.error(
|
||||
new Error(
|
||||
`Cannot push metrics. ${response.request.href} responded with status code ${response.statusCode}`
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
startPushingMetrics() {
|
||||
this._intervalId = setInterval(
|
||||
() => this.sendMetrics(),
|
||||
this._config.intervalSeconds * 1000
|
||||
)
|
||||
}
|
||||
|
||||
async metrics() {
|
||||
return promClientJsonToInfluxV2(await this._metricInstance.metrics(), {
|
||||
env: this._config.envLabel,
|
||||
application: 'shields',
|
||||
instance: this._instanceId,
|
||||
})
|
||||
}
|
||||
|
||||
getInstanceId() {
|
||||
const {
|
||||
hostnameAliases = {},
|
||||
instanceIdFrom,
|
||||
instanceIdEnvVarName,
|
||||
} = this._config
|
||||
let instance
|
||||
if (instanceIdFrom === 'env-var') {
|
||||
instance = process.env[instanceIdEnvVarName]
|
||||
} else if (instanceIdFrom === 'hostname') {
|
||||
const hostname = os.hostname()
|
||||
instance = hostnameAliases[hostname] || hostname
|
||||
} else if (instanceIdFrom === 'random') {
|
||||
instance = generateInstanceId()
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
stopPushingMetrics() {
|
||||
if (this._intervalId) {
|
||||
clearInterval(this._intervalId)
|
||||
this._intervalId = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
'use strict'
|
||||
const os = require('os')
|
||||
const nock = require('nock')
|
||||
const sinon = require('sinon')
|
||||
const { expect } = require('chai')
|
||||
const log = require('./log')
|
||||
const InfluxMetrics = require('./influx-metrics')
|
||||
require('../register-chai-plugins.spec')
|
||||
describe('Influx metrics', function () {
|
||||
const metricInstance = {
|
||||
metrics() {
|
||||
return [
|
||||
{
|
||||
help: 'counter 1 help',
|
||||
name: 'counter1',
|
||||
type: 'counter',
|
||||
values: [{ value: 11, labels: {} }],
|
||||
aggregator: 'sum',
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
describe('"metrics" function', function () {
|
||||
let osHostnameStub
|
||||
afterEach(function () {
|
||||
nock.enableNetConnect()
|
||||
delete process.env.INSTANCE_ID
|
||||
if (osHostnameStub) {
|
||||
osHostnameStub.restore()
|
||||
}
|
||||
})
|
||||
it('should use an environment variable value as an instance label', async function () {
|
||||
process.env.INSTANCE_ID = 'instance3'
|
||||
const influxMetrics = new InfluxMetrics(metricInstance, {
|
||||
instanceIdFrom: 'env-var',
|
||||
instanceIdEnvVarName: 'INSTANCE_ID',
|
||||
})
|
||||
|
||||
expect(await influxMetrics.metrics()).to.contain('instance=instance3')
|
||||
})
|
||||
|
||||
it('should use a hostname as an instance label', async function () {
|
||||
osHostnameStub = sinon.stub(os, 'hostname').returns('test-hostname')
|
||||
const customConfig = {
|
||||
instanceIdFrom: 'hostname',
|
||||
}
|
||||
const influxMetrics = new InfluxMetrics(metricInstance, customConfig)
|
||||
|
||||
expect(await influxMetrics.metrics()).to.be.contain(
|
||||
'instance=test-hostname'
|
||||
)
|
||||
})
|
||||
|
||||
it('should use a random string as an instance label', async function () {
|
||||
const customConfig = {
|
||||
instanceIdFrom: 'random',
|
||||
}
|
||||
const influxMetrics = new InfluxMetrics(metricInstance, customConfig)
|
||||
|
||||
expect(await influxMetrics.metrics()).to.be.match(/instance=\w+ /)
|
||||
})
|
||||
|
||||
it('should use a hostname alias as an instance label', async function () {
|
||||
osHostnameStub = sinon.stub(os, 'hostname').returns('test-hostname')
|
||||
const customConfig = {
|
||||
instanceIdFrom: 'hostname',
|
||||
hostnameAliases: { 'test-hostname': 'test-hostname-alias' },
|
||||
}
|
||||
const influxMetrics = new InfluxMetrics(metricInstance, customConfig)
|
||||
|
||||
expect(await influxMetrics.metrics()).to.be.contain(
|
||||
'instance=test-hostname-alias'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startPushingMetrics', function () {
|
||||
let influxMetrics, clock
|
||||
beforeEach(function () {
|
||||
clock = sinon.useFakeTimers()
|
||||
})
|
||||
afterEach(function () {
|
||||
influxMetrics.stopPushingMetrics()
|
||||
nock.cleanAll()
|
||||
nock.enableNetConnect()
|
||||
delete process.env.INSTANCE_ID
|
||||
clock.restore()
|
||||
})
|
||||
|
||||
it('should send metrics', async function () {
|
||||
const scope = nock('http://shields-metrics.io/', {
|
||||
reqheaders: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
})
|
||||
.persist()
|
||||
.post(
|
||||
'/metrics',
|
||||
'prometheus,application=shields,env=test-env,instance=instance2 counter1=11'
|
||||
)
|
||||
.basicAuth({ user: 'metrics-username', pass: 'metrics-password' })
|
||||
.reply(200)
|
||||
process.env.INSTANCE_ID = 'instance2'
|
||||
influxMetrics = new InfluxMetrics(metricInstance, {
|
||||
url: 'http://shields-metrics.io/metrics',
|
||||
timeoutMillseconds: 100,
|
||||
intervalSeconds: 0.001,
|
||||
username: 'metrics-username',
|
||||
password: 'metrics-password',
|
||||
instanceIdFrom: 'env-var',
|
||||
instanceIdEnvVarName: 'INSTANCE_ID',
|
||||
envLabel: 'test-env',
|
||||
})
|
||||
|
||||
influxMetrics.startPushingMetrics()
|
||||
|
||||
await clock.tickAsync(10)
|
||||
expect(scope.isDone()).to.be.equal(
|
||||
true,
|
||||
`pending mocks: ${scope.pendingMocks()}`
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendMetrics', function () {
|
||||
beforeEach(function () {
|
||||
sinon.stub(log, 'error')
|
||||
})
|
||||
afterEach(function () {
|
||||
log.error.restore()
|
||||
nock.cleanAll()
|
||||
nock.enableNetConnect()
|
||||
})
|
||||
|
||||
const influxMetrics = new InfluxMetrics(metricInstance, {
|
||||
url: 'http://shields-metrics.io/metrics',
|
||||
timeoutMillseconds: 50,
|
||||
intervalSeconds: 0,
|
||||
username: 'metrics-username',
|
||||
password: 'metrics-password',
|
||||
})
|
||||
it('should log errors', async function () {
|
||||
nock.disableNetConnect()
|
||||
|
||||
await influxMetrics.sendMetrics()
|
||||
|
||||
expect(log.error).to.be.calledWith(
|
||||
sinon.match
|
||||
.instanceOf(Error)
|
||||
.and(
|
||||
sinon.match.has(
|
||||
'message',
|
||||
'Cannot push metrics. Cause: NetConnectNotAllowedError: Nock: Disallowed net connect for "shields-metrics.io:80/metrics"'
|
||||
)
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('should log error responses', async function () {
|
||||
nock('http://shields-metrics.io/').persist().post('/metrics').reply(400)
|
||||
|
||||
await influxMetrics.sendMetrics()
|
||||
|
||||
expect(log.error).to.be.calledWith(
|
||||
sinon.match
|
||||
.instanceOf(Error)
|
||||
.and(
|
||||
sinon.match.has(
|
||||
'message',
|
||||
'Cannot push metrics. http://shields-metrics.io/metrics responded with status code 400'
|
||||
)
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,8 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
function generateInstanceId() {
|
||||
// from https://gist.github.com/gordonbrander/2230317
|
||||
return Math.random().toString(36).substr(2, 9)
|
||||
}
|
||||
|
||||
module.exports = generateInstanceId
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user