### Install badge-maker Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Install the badge-maker package using npm. ```sh npm install badge-maker ``` -------------------------------- ### Global Installation and Console Usage Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Install badge-maker globally and use it from the console to build badges. ```sh npm install -g badge-maker badge build passed :brightgreen > mybadge.svg ``` -------------------------------- ### Start Server in Debug Mode Source: https://github.com/badges/shields/blob/master/README.md Command to start the development server in debug mode, enabling debugging capabilities. ```bash npm run debug:server ``` -------------------------------- ### Example Badges for Various Metrics Source: https://github.com/badges/shields/blob/master/README.md These examples demonstrate how to generate badges for different metrics like code coverage, release versions, package status, and more. They can be directly embedded in markdown files. ```markdown ![coverage](https://img.shields.io/badge/coverage-80%25-yellowgreen) ``` ```markdown ![version](https://img.shields.io/badge/version-1.2.3-blue) ``` ```markdown ![gem](https://img.shields.io/badge/gem-2.2.0-blue) ``` ```markdown ![dependencies](https://img.shields.io/badge/dependencies-out%20of%20date-orange) ``` ```markdown ![codacy](https://img.shields.io/badge/codacy-B-green) ``` ```markdown ![semver](https://img.shields.io/badge/semver-2.0.0-blue) ``` ```markdown ![receives](https://img.shields.io/badge/receives-2.00%20USD%2Fweek-yellow) ``` ```markdown ![downloads](https://img.shields.io/badge/downloads-13k%2Fmonth-brightgreen) ``` ```markdown ![rating](https://img.shields.io/badge/rating-★★★★☆-brightgreen) ``` ```markdown ![uptime](https://img.shields.io/badge/uptime-100%25-brightgreen) ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Installs all necessary Node.js dependencies for the Shields project. A sudo prefix might be required depending on your system's permissions. ```sh npm ci # You may need sudo for this. ``` -------------------------------- ### Install Node.js 22 on Ubuntu/Debian Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Installs Node.js version 22 using the NodeSource repository. This is a prerequisite for building Shields from source. ```sh curl -sL https://deb.nodesource.com/setup_22.x | sudo -E bash -; sudo apt-get install -y nodejs ``` -------------------------------- ### Start Shields Server Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Starts the Shields server. By default, it runs on port 80, which requires sudo privileges. For other ports, use environment variables or pass the port number as an argument. ```sh sudo node server ``` ```sh PORT=8080 node server ``` ```sh node server 8080 ``` -------------------------------- ### Raster Format Conversion Example Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Shows how to pipe the SVG output from the badge command-line tool to ImageMagick for conversion to a GIF format. ```sh badge build passed :green | magick svg:- gif:- ``` -------------------------------- ### Example JSONPath Query (After Fix) Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Shows the equivalent JSONPath query that achieves the same result as the previous example but is compatible with the updated, more secure JSONPath library. This uses negative indexing for array selection. ```json $..keywords[-1:] ``` -------------------------------- ### Start Server without Sentry DSN Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Start the server. If Sentry DSN is configured via other means (e.g., config file), this command will start the server with Sentry enabled. ```sh sudo node server ``` -------------------------------- ### Start Server with Sentry DSN Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Run the server with the SENTRY_DSN environment variable set to enable Sentry integration for error tracking. Replace xxx, yyy, and zzz with your actual Sentry credentials. ```sh sudo SENTRY_DSN=https://xxx:yyy@sentry.io/zzz node server ``` -------------------------------- ### Build Shields Frontend Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Compiles and builds the frontend assets for the Shields application. This command should be run after installing dependencies. ```sh npm run build ``` -------------------------------- ### Running Integration Tests with PostgreSQL Source: https://github.com/badges/shields/blob/master/CONTRIBUTING.md To run integration tests, ensure PostgreSQL is installed and configured. Set the connection string via an environment variable or a YAML config file. Then, apply database migrations and execute the tests. ```bash npm run migrate up ``` ```bash npm run test:integration ``` -------------------------------- ### Example Service Badge Implementation Source: https://github.com/badges/shields/blob/master/doc/TUTORIAL.md This snippet demonstrates how to create a basic service badge that displays text passed as a route parameter. It extends BaseService and defines static properties for category and route, along with an async handle function to return badge data. ```javascript import { BaseService } from '../index.js' export default class Example extends BaseService { static category = 'build' static route = { base: 'example', pattern: ':text' } async handle({ text }) { return { label: 'example', message: text, color: 'blue', } } } ``` -------------------------------- ### Comprehensive Test File for Retired Service Source: https://github.com/badges/shields/blob/master/doc/retiring-badges.md This example demonstrates a complete test file for a retired service, including initialization of `ServiceTester` and multiple test cases validating the 'retired badge' message for different badge types previously offered by the service. ```javascript import { ServiceTester } from '../tester.js' export const t = new ServiceTester({ id: 'imagelayers', title: 'ImageLayers', }) t.create('retired badge (previously image size)') .get('/image-size/_/ubuntu/latest.json') .expectBadge({ label: 'imagelayers', message: 'retired badge', }) t.create('retired badge (previously number of layers)') .get('/layers/_/ubuntu/latest.json') .expectBadge({ label: 'imagelayers', message: 'retired badge', }) ``` -------------------------------- ### Generate a Custom Static Badge Source: https://github.com/badges/shields/blob/master/README.md This example shows how to quickly create a custom static badge by specifying the left and right text, and a color. This is useful for simple, one-off badges. ```markdown https://img.shields.io/badge/left-right-f39f37 ``` -------------------------------- ### Color Specification Examples Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Illustrates various ways to specify colors for labels and messages, including named colors, hex codes, and CSS color values. ```js # Shields named colors: # ![][brightgreen] # ![][green] # ![][yellow] # ![][yellowgreen] # ![][orange] # ![][red] # ![][blue] # ![][grey] ![][gray] – the default `labelColor` # ![][lightgrey] ![][lightgray] – the default `color` # ![][success] # ![][important] # ![][critical] # ![][informational] # ![][inactive] – the default `color` # Three- or six-character hex color, optionally prefixed with "#": # ![][9cf] # ![][#007fff] # Any valid CSS color, e.g. # `rgb(...)`, `rgba(...)' # `hsl(...)`, `hsla(...)' # ![][aqua] ![][fuchsia] ![][lightslategray] etc. ``` -------------------------------- ### Example JSONPath Query (Before Fix) Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Illustrates a JSONPath query that previously worked but is no longer supported due to security changes. This query selected the last element from a keywords array. ```json $..keywords[(@.length-1)] ``` -------------------------------- ### JSONPath Dot Notation Examples Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Illustrates various ways to access JSON properties using dot notation, including special characters, quoted keys, and recursive descent. ```jsonpath $.key-dash ``` ```jsonpath $."key" ``` ```jsonpath $.."key" ``` ```jsonpath $. ``` ```jsonpath $.length ``` ```jsonpath $.$ ``` ```jsonpath $.?? ``` ```jsonpath $.2 ``` ```jsonpath $.-1 ``` ```jsonpath $.'key' ``` ```jsonpath $..'key' ``` ```jsonpath $.'some.key' ``` ```jsonpath $. a ``` ```jsonpath $..* ``` ```jsonpath $a ``` ```jsonpath .key ``` ```jsonpath key ``` -------------------------------- ### Retired Service Redirector Example Source: https://github.com/badges/shields/blob/master/doc/badge-redirectors.md This pattern is used when a redirector is no longer needed and should be retired. It links to an issue explaining the migration path. ```javascript import { retiredService } from '../index.js' export default retiredService({ category: 'build', route: { base: 'github/workflow/status', pattern: ':various+', }, label: 'githubworkflowstatus', issueUrl: 'https://github.com/badges/shields/issues/8671', dateAdded: new Date('2025-11-29'), }) ``` -------------------------------- ### Open in GitHub Codespaces Badge Source: https://github.com/badges/shields/blob/master/README.md Badge that links to open the project in GitHub Codespaces for a quick development environment setup. ```markdown [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/badges/shields?quickstart=1) ``` -------------------------------- ### Pull and Run Shields Docker Image from DockerHub Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Pulls the latest 'next' Docker image from DockerHub and runs it. This is a quick way to get a Shields server instance up and running. ```sh # DockerHub $ docker pull shieldsio/shields:next $ docker run shieldsio/shields:next ``` -------------------------------- ### Embed Shields.io Badges in HTML Source: https://github.com/badges/shields/blob/master/README.md These examples show how to embed various Shields.io badges into an HTML document. They are typically used in README files or project websites. ```html ``` ```html ``` ```html ``` ```html ``` ```html Daily Tests Status ``` ```html Code Coverage ``` ```html Chat on Discord ``` -------------------------------- ### Bracket Notation with Spaces and Multiple Literals Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Shows bracket notation with spaces around a key, and examples with two literals separated by a dot, both quoted and unquoted. ```jsonpath $[ 'a' ] ``` ```jsonpath $['two'.'some'] ``` ```jsonpath $[two.some] ``` -------------------------------- ### Test Docs Badge with No Version Specified Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the docs badge by making a GET request to '/tokio.json'. It uses Joi to assert that the 'label' is 'docs' and the 'message' can be either 'passing' or 'failing'. This test interacts with the live API without mocking. ```javascript import Joi from 'joi' t.create('Docs with no version specified') .get('/tokio.json') .expectBadge({ label: 'docs', message: Joi.equal('passing', 'failing'), }) ``` -------------------------------- ### JSONPath Filter Expression Examples Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Demonstrates the use of filter expressions in JSONPath to select elements based on conditions, including comparisons, boolean logic, and array operations. ```jsonpath $[?(@.key)] ``` ```jsonpath $..*[?(@.id>2)] ``` ```jsonpath $..[?(@.id==2)] ``` ```jsonpath $[?(@.key+50==100)] ``` ```jsonpath $[?(@.key>0 && false)] ``` ```jsonpath $[?(@.key>0 && true)] ``` ```jsonpath $[?(@.key>0 || false)] ``` ```jsonpath $[?(@.key>0 || true)] ``` ```jsonpath $[?(@[-1]==2)] ``` ```jsonpath $[?(@[1]=='b')] ``` ```jsonpath $[?(@)] ``` ```jsonpath $[?(@.a && @.b || @.c)] ``` ```jsonpath $[?(@.key/10==5)] ``` ```jsonpath $[?(@.key-dash == 'value')] ``` ```jsonpath $[?(@.2 == 'second')] ``` ```jsonpath $[?(@.2 == 'third')] ``` ```jsonpath $[?()] ``` ```jsonpath $[?(@.key==42)] ``` ```jsonpath $[?(@==42)] ``` ```jsonpath $[?(@.key==42)] ``` ```jsonpath $[?(@.d==["v1","v2"])] ``` ```jsonpath $[?(@[0:1]==[1])] ``` ```jsonpath $[?(@.*==[1,2])] ``` ```jsonpath $[?(@.d==["v1","v2"] || (@.d == true))] ``` ```jsonpath $[?(@.d==['v1','v2'])] ``` ```jsonpath $[?((@.key<44)==false)] ``` ```jsonpath $[?(@.key==false)] ``` ```jsonpath $[?(@.key==null)] ``` ```jsonpath $[?(@[0:1]==1)] ``` ```jsonpath $[?(@[*]==2)] ``` -------------------------------- ### Build Frontend with Custom Base URL Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Build the frontend application, specifying the BASE_URL for your custom server. This is necessary when hosting the frontend separately. ```sh BASE_URL=https://your-server.example.com npm run build ``` -------------------------------- ### Profile Server Performance with Flamebearer Source: https://github.com/badges/shields/blob/master/doc/performance-testing.md Profile the backend server performance by running 'npm run profile:server'. Process the generated log file with flamebearer for visualization. ```bash npm install -g flamebearer node --prof-process --preprocess -j isolate-00000244AB6ED3B0-11920-v8.log | flamebearer ``` -------------------------------- ### Bracket Notation without Quotes Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Example of bracket notation used without quotes for a key, which can be ambiguous or unsupported in some implementations. ```jsonpath $[key] ``` -------------------------------- ### Array Slice with Leading Zeros Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Example of array slicing where the step value includes leading zeros, a format that might be handled differently by parsers. ```jsonpath $[010:024:010] ``` -------------------------------- ### Run Specific Service Tests Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Demonstrates how to filter service tests using --fgrep to target specific test descriptions. ```bash npm run test:services -- --only="docsrs" --fgrep="Passing docs for version" ``` -------------------------------- ### Enable Prometheus Metrics Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Enable Prometheus metrics collection and expose the metrics endpoint by setting METRICS_PROMETHEUS_ENABLED and METRICS_PROMETHEUS_ENDPOINT_ENABLED to true. The metrics will be available at the /metrics endpoint. ```bash METRICS_PROMETHEUS_ENABLED=true METRICS_PROMETHEUS_ENDPOINT_ENABLED=true npm start ``` -------------------------------- ### Current Object Navigation Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Demonstrates navigating the current object using dot notation with '@'. ```jsonpath @.a ``` -------------------------------- ### Retrieve Badge Data in JSON Format Source: https://github.com/badges/shields/blob/master/doc/json-format.md Append .json to the badge URL to get the payload. Fields 'name' and 'value' are deprecated; use 'label' and 'message' instead. ```json { "name": "hello", "label": "hello", "value": "world", "message": "world", "color": "brightgreen" } ``` -------------------------------- ### Initialize ServiceTester for Retired Services Source: https://github.com/badges/shields/blob/master/doc/retiring-badges.md When using `RetiredService` classes, create the `ServiceTester` class directly instead of using `createServiceTester()`. This is necessary because `RetiredService` has different testing requirements. ```javascript import { ServiceTester } from '../tester.js' export const t = new ServiceTester({ id: 'imagelayers', title: 'ImageLayers', }) ``` -------------------------------- ### Generate a Badge with Basic Format Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Create a badge using a simple format object. The generated SVG is logged to the console. ```js const format = { label: 'build', message: 'passed', color: 'brightgreen', } const svg = makeBadge(format) console.log(svg) // nock('https://docs.rs/crate') .get('/tokio/1.32.1/status.json') .reply(200, { doc_status: false }), ) .expectBadge({ label: 'docs@1.32.1', message: 'failing', color: 'red', }) ``` -------------------------------- ### Generate and Open Coverage Report Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Commands to generate a code coverage report for service tests and open it in a browser. ```bash npm run coverage:test:services -- -- --only=docsrs ``` ```bash npm run coverage:report:open ``` -------------------------------- ### Import badge-maker Library Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Import the necessary functions from the badge-maker library in your JavaScript project. ```js import { makeBadge, ValidationError } from 'badge-maker' ``` -------------------------------- ### Configure Bitbucket Server Credentials and Origins Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Provide authorized origins, username, and password for basic authentication to access a private Bitbucket Server instance. ```yml public: services: bitbucketServer: authorizedOrigins: ['...'] private: bitbucket_server_username: '...' bitbucket_server_password: '...' ``` -------------------------------- ### Debug a Badge from Command Line Source: https://github.com/badges/shields/blob/master/README.md Command to debug a specific badge from the command line. Supports both badge paths and full URLs. ```bash npm run badge -- /npm/v/nock ``` ```bash npm run badge -- https://img.shields.io/npm/v/nock ``` -------------------------------- ### Set Production Environment Variable Source: https://github.com/badges/shields/blob/master/doc/production-hosting.md Set this environment variable to bootstrap non-secret configuration settings for the server. ```bash NODE_CONFIG_ENV=shields-io-production ``` -------------------------------- ### Basic Static Badge Source: https://github.com/badges/shields/blob/master/frontend/docs/static-badges.md Create a simple static badge with custom text and color. The text and color are URL-encoded. ```markdown ![any text you like](https://img.shields.io/badge/any%20text-you%20like-blue) ``` -------------------------------- ### Libraries.io/Bower Token Configuration Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Configure Libraries.io tokens for both Libraries.io and Bower badges. This can be a single token string or an array of tokens. ```yaml private: librariesio_tokens: my-token ``` ```yaml private: librariesio_tokens: [my-token some-other-token] ``` -------------------------------- ### Set Server Secrets via Environment Variables Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Use environment variables to set secrets, which is a common practice in PaaS environments. Ensure to define authorized origins for services that require them. ```sh DRONE_TOKEN=... DRONE_ORIGINS="https://drone.example.com" ``` -------------------------------- ### Configure CurseForge API Key Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Enter a CurseForge API key obtained from the CurseForge Console to use the CurseForge API for badges. ```yml private: curseforge_api_key: '...' ``` -------------------------------- ### PostgreSQL Connection String Configuration Source: https://github.com/badges/shields/blob/master/CONTRIBUTING.md Configure the PostgreSQL connection string for integration tests. This can be done using an environment variable or by specifying it in a YAML configuration file. ```bash POSTGRES_URL=postgresql://user:pass@127.0.0.1:5432/db_name ``` ```yaml private: postgres_url: 'postgresql://user:pass@127.0.0.1:5432/db_name' ``` -------------------------------- ### Configure Bitbucket (Cloud) Credentials Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Set Bitbucket username and password for basic authentication to access private repositories on bitbucket.org. ```yml private: bitbucket_username: '...' bitbucket_password: '...' ``` -------------------------------- ### Convert Path Parameters to Query Parameters Source: https://github.com/badges/shields/blob/master/doc/badge-redirectors.md Migrates from path-based parameters to query-based parameters. Use when the new badge design uses query strings instead of path segments. ```javascript import { redirector } from '../index.js' export default redirector({ category: 'monitoring', route: { base: 'website', pattern: ':protocol(https|http)/:hostAndPath+', }, transformPath: () => '/website', transformQueryParams: ({ protocol, hostAndPath }) => ({ url: `${protocol}://${hostAndPath}`, }), dateAdded: new Date('2025-03-03'), }) ``` -------------------------------- ### Preview Snapshot Changes Source: https://github.com/badges/shields/blob/master/README.md Command to preview changes to saved snapshots without updating them. Useful for reviewing intended modifications. ```bash SNAPSHOT_DRY=1 npm run test:package ``` -------------------------------- ### Create Service Tester Boilerplate Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Use this boilerplate to initialize a ServiceTester object for testing a specific service. Ensure your service module exports a single class. ```javascript import { createServiceTester } from '../tester.js' export const t = await createServiceTester() ``` -------------------------------- ### Test Failing Docs for Version Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the Docs.rs badge endpoint for a version where documentation build failed, expecting a 'failing' status. ```javascript t.create('Failing docs for version').get('/tokio/1.32.1.json').expectBadge({ label: 'docs@1.32.1', message: 'failing', color: 'red', }) ``` -------------------------------- ### Equivalent OpenAPI Parameter Object Source: https://github.com/badges/shields/blob/master/doc/TUTORIAL.md Shows the expanded, equivalent OpenAPI Parameter object for a path parameter, as generated by the `pathParams` helper function. ```javascript parameters: [ { name: 'gem', in: 'path', required: true, schema: { type: 'string' }, example: 'formatador', description: 'Name of the Ruby Gem', }, ] ``` -------------------------------- ### Define a Shared Joi Schema Source: https://github.com/badges/shields/blob/master/doc/input-validation.md Use Joi to define a schema that can be applied to multiple badges, such as license and version. This promotes code reuse and consistency. ```javascript const schema = Joi.object({ license: Joi.string().required(), version: Joi.string().required(), }).required() ``` -------------------------------- ### Array Slice with Negative Step Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Illustrates various array slicing scenarios using negative steps, which are prone to implementation-specific interpretations. ```jsonpath $[3:0:-2] ``` ```jsonpath $[7:3:-1] ``` ```jsonpath $[::-2] ``` ```jsonpath $[3::-1] ``` ```jsonpath $[:2:-1] ``` -------------------------------- ### Configure Server Root Redirect Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Set the REDIRECT_URI environment variable to make the Shields server redirect requests from the server root. This is useful for custom deployments. ```sh REDIRECT_URI=http://my-custom-shields.s3.amazonaws.com/ ``` -------------------------------- ### Libraries.io/Bower Token Environment Variable Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md When using the environment variable for multiple Libraries.io tokens, separate them with a space. ```bash LIBRARIESIO_TOKENS="my-token some-other-token" ``` -------------------------------- ### Simple Path Redirect Source: https://github.com/badges/shields/blob/master/doc/badge-redirectors.md Redirects a simple old URL pattern to a new one. Use when the URL structure changes but no parameters need transformation. ```javascript import { redirector } from '../index.js' export default redirector({ category: 'other', route: { base: 'badge/endpoint', pattern: '', }, transformPath: () => '/endpoint', dateAdded: new Date('2025-01-01'), }) ``` -------------------------------- ### Micro-benchmark Badge Generation Source: https://github.com/badges/shields/blob/master/doc/performance-testing.md Use console.time and console.timeEnd to measure the execution time of specific badge generation code. Modify the 'benchmark:badge' script in package.json to change iteration counts. ```javascript console.time('makeBadge') const svg = makeBadge(badgeData) console.timeEnd('makeBadge') ``` -------------------------------- ### Test Version Not Found Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the Docs.rs badge endpoint for a non-existent version of a crate, expecting a 'not found' message. ```javascript t.create('Version not found') .get('/tokio/0.8.json') .expectBadge({ label: 'docs', message: 'not found' }) ``` -------------------------------- ### Test Crate Not Found Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the Docs.rs badge endpoint for a non-existent crate, expecting a 'not found' message. ```javascript t.create('Crate not found') .get('/not-a-crate/latest.json') .expectBadge({ label: 'docs', message: 'not found' }) ``` -------------------------------- ### Update Service Implementation with RetiredService Source: https://github.com/badges/shields/blob/master/doc/retiring-badges.md Replace the existing service class with `RetiredService` from `./core/base-service/retired-service.js`. Ensure the `category`, `route`, and `label` are set correctly, and the badge label reflects the service name. ```javascript import { retiredService } from '../index.js' export default retiredService({ category: 'size', route: { base: 'imagelayers', pattern: ':various+', }, label: 'imagelayers', dateAdded: new Date('2019-xx-xx'), // Be sure to update this with today's date! }) ``` -------------------------------- ### Basic Redirector Test Structure Source: https://github.com/badges/shields/blob/master/doc/badge-redirectors.md Tests for redirectors should verify that the old URL correctly redirects to the new URL using `expectRedirect()`. This helper checks for a 301 response and the correct `Location` header. ```javascript import { createServiceTester } from '../tester.js' export const t = await createServiceTester() t.create('Total downloads redirect: unscoped package') .get('/dt/left-pad.svg') .expectRedirect('/npm/d18m/left-pad.svg') t.create('Total downloads redirect: scoped package') .get('/dt/@cycle/core.svg') .expectRedirect('/npm/d18m/@cycle/core.svg') ``` -------------------------------- ### Test Passing Docs for Version Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the Docs.rs badge endpoint for a specific version, expecting a 'passing' status. ```javascript t.create('Passing docs for version').get('/tokio/1.37.0.json').expectBadge({ label: 'docs@1.37.0', message: 'passing', color: 'brightgreen', }) ``` -------------------------------- ### Service Class with OpenAPI Specification Source: https://github.com/badges/shields/blob/master/doc/TUTORIAL.md Defines a service class for a Gem Version badge, including its category and an OpenAPI 3 specification for the '/gem/v/{gem}' endpoint. ```javascript import { pathParams } from '../index.js' export default class GemVersion extends BaseJsonService { // ... static category = 'version' static openApi = { '/gem/v/{gem}': { get: { summary: 'Gem Version', description: '[Ruby Gems](https://rubygems.org/) is a registry for ruby libraries', parameters: pathParams({ name: 'gem', description: 'Name of the Ruby Gem', example: 'formatador', }), }, }, } } ``` -------------------------------- ### Deploy Shields to Heroku Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Deploys the Shields application to Heroku. This involves logging into the Heroku CLI, creating an application, and pushing the code. ```bash heroku login heroku create your-app-name git push heroku master heroku open ``` -------------------------------- ### Redirect with Path Parameters Source: https://github.com/badges/shields/blob/master/doc/badge-redirectors.md Redirects URLs with parameters to a new structure. Use when the old URL's parameters need to be mapped to a different path format. ```javascript import { redirector } from '../index.js' export default redirector({ category: 'analysis', route: { base: 'scrutinizer', pattern: ':vcs(g|b)/:user/:repo/:branch*', }, transformPath: ({ vcs, user, repo, branch }) => `/scrutinizer/quality/${vcs}/${user}/${repo}${branch ? `/${branch}` : ''}`, dateAdded: new Date('2025-02-02'), }) ``` -------------------------------- ### Using SimpleIcons in Badges Source: https://github.com/badges/shields/blob/master/frontend/docs/logos.md Reference SimpleIcons using their icon slugs. Ensure the icon is available in Shields.io; refer to the SimpleIcons repository for the latest slugs and update information. ```markdown ![](https://img.shields.io/npm/v/npm.svg?logo=nodedotjs) - https://img.shields.io/npm/v/npm.svg?logo=nodedotjs ``` -------------------------------- ### JSONPath Union with Wildcard and Keys Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Use a wildcard to select all properties and then specify keys to extract from the resulting objects. ```JSONPath $.*['c','d'] ``` -------------------------------- ### Pull and Run Shields Docker Image from GHCR Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Pulls the latest 'next' Docker image from GitHub Container Registry and runs it. This provides an alternative to using DockerHub. ```sh # GHCR $ docker pull ghcr.io/badges/shields:next $ docker pull ghcr.io/badges/shields:next ``` -------------------------------- ### JSONPath Union with Wildcard and Slice Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Select all properties and then apply an array slice to the values. ```JSONPath $.*[0,:5] ``` -------------------------------- ### Static Badge with 'for-the-badge' Style Source: https://github.com/badges/shields/blob/master/frontend/docs/static-badges.md Apply the 'for-the-badge' style to a static badge, which changes the badge's appearance. The text is URL-encoded. ```markdown ![ 'for the badge' style](https://img.shields.io/badge/%27for%20the%20badge%27%20style-20B2AA?style=for-the-badge) ``` -------------------------------- ### Set Server Secrets via Configuration File Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Configure secrets using a `config/local.yml` file for services. This method allows for cascading configurations as detailed in the node-config documentation. ```yml public: services: drone: authorizedOrigins: ['https://drone.example.com'] private: drone_token: '...' ``` -------------------------------- ### Bracket Notation with Quoted Literals Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Illustrates bracket notation using quoted strings for various literal values, including special characters and slice syntax. ```jsonpath $[':'] ``` ```jsonpath $[']'] ``` ```jsonpath $['@'] ``` ```jsonpath $['\'] ``` ```jsonpath $['\''] ``` ```jsonpath $['$'] ``` ```jsonpath $[':@."$,*\'\'] ``` ```jsonpath $['single'quote'] ``` ```jsonpath $[','] ``` ```jsonpath $['*'] ``` -------------------------------- ### Parens Notation Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Use parentheses for grouping multiple keys or expressions. ```JSONPath $(key,more) ``` -------------------------------- ### Configure Sentry DSN in YAML Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Alternatively to environment variables, configure the Sentry DSN within the server's configuration file using YAML format. Ensure the sentry_dsn value is correctly set. ```yml private: sentry_dsn: ... ``` -------------------------------- ### Handle ValidationError Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Demonstrates how to catch a ValidationError when an invalid format object is provided to makeBadge. ```js try { makeBadge({}) } catch (e) { console.log(e) // ValidationError: Field `message` is required } ``` -------------------------------- ### Run Shields Docker Container Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Runs the Shields Docker container, mapping port 8080 and setting the PORT environment variable. This allows access to the server at http://localhost:8080/. ```console $ docker run --rm -p 8080:8080 --env PORT=8080 --name shields shieldsio/shields:next Configuration: ... 0916211515 Server is starting up: http://0.0.0.0:8080/ ``` -------------------------------- ### Gem Version Badge Service Source: https://github.com/badges/shields/blob/master/doc/TUTORIAL.md This service queries the RubyGems API to fetch and display the version of a gem. It extends BaseJsonService and uses Joi for schema validation. ```javascript // (1) import { renderVersionBadge } from '../version.js' // (2) import { BaseJsonService } from '../index.js' // (3) import Joi from 'joi' const schema = Joi.object({ version: Joi.string().required(), }).required() // (4) export default class GemVersion extends BaseJsonService { // (5) static category = 'version' // (6) static route = { base: 'gem/v', pattern: ':gem' } // (7) static defaultBadgeData = { label: 'gem' } // (10) static render({ version }) { return renderVersionBadge({ version }) } // (9) async fetch({ gem }) { return this._requestJson({ schema, url: `https://rubygems.org/api/v1/gems/${gem}.json`, }) } // (8) async handle({ gem }) { const { version } = await this.fetch({ gem }) return this.constructor.render({ version }) } } ``` -------------------------------- ### Run Service Tests with Debug Output Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Runs service tests for the 'docsrs' service with additional debug logging enabled. This is useful for troubleshooting failing tests. ```bash npm run test:services:trace -- --only=docsrs ``` -------------------------------- ### Badge Format Object Source: https://github.com/badges/shields/blob/master/badge-maker/README.md Defines the structure of the format object used to configure badge properties like label, message, colors, logo, links, style, and ID suffix. ```js { label: 'build', // (Optional) Badge label message: 'passed', // (Required) Badge message labelColor: '#555', // (Optional) Label color color: '#4c0', // (Optional) Message color logoBase64: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iOCIgZmlsbD0iI2IxY2U1NiIvPjxwYXRoIGQ9Ik04IDBoMjR2NjRIOGMtNC40MzIgMC04LTMuNTY4LTgtOFY4YzAtNC40MzIgMy41NjgtOCA4LTh6IiBmaWxsPSIjNWQ1ZDVkIi8+PC9zdmc+', // (Optional) Any custom logo can be passed in a URL parameter by base64 encoding links: ['https://example.com', 'https://example.com'], // (Optional) Links array of maximum two links // (Optional) One of: 'plastic', 'flat', 'flat-square', 'for-the-badge' or 'social' // Each offers a different visual design. style: 'flat', // (Optional) A string with only letters, numbers, -, and _. This can be used // to ensure every element id within the SVG is unique and prevent CSS // cross-contamination when the SVG badge is rendered inline in HTML pages. idSuffix: 'dd' } ``` -------------------------------- ### Configure Discord Bot Token Source: https://github.com/badges/shields/blob/master/doc/server-secrets.md Optionally provide a Discord bot token to enable higher API rates when fetching Discord-related badge information. Register an application and create a bot in the Discord developer console to obtain the token. ```yml private: discord_bot_token: '...' ``` -------------------------------- ### Test Malformed Version Source: https://github.com/badges/shields/blob/master/doc/service-tests.md Tests the Docs.rs badge endpoint for a malformed version string, expecting a 'malformed version' message. ```javascript t.create('Malformed version') .get('/tokio/not-a-version.json') .expectBadge({ label: 'docs', message: 'malformed version' }) ``` -------------------------------- ### Clone Shields Repository and Checkout Latest Tag Source: https://github.com/badges/shields/blob/master/doc/self-hosting.md Clones the Shields repository and checks out the latest stable release tag for the server. This ensures you are working with a tested version. ```sh git clone https://github.com/badges/shields.git cd shields git checkout $(git tag | grep server | tail -n 1) # checkout the latest tag ``` -------------------------------- ### Array Slice with Range of 0 and Step 0 Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Shows array slicing with a range of 0 and a step of 0, edge cases that may exhibit different behaviors. ```jsonpath $[0:0] ``` ```jsonpath $[0:3:0] ``` -------------------------------- ### Array Slice with Large Numbers and Negative Step Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Demonstrates array slicing with large numbers for end and negative steps, which can lead to divergent behavior across JSONPath implementations. ```jsonpath $[2:-113667776004:-1] ``` ```jsonpath $[113667776004:2:-1] ``` -------------------------------- ### Throwing Custom NotFound Error Source: https://github.com/badges/shields/blob/master/doc/TUTORIAL.md Illustrates how to manually throw a `NotFound` error with a custom message when dealing with non-standard error conditions in API responses. ```javascript import { NotFound } from '../index.js' throw new NotFound({ prettyMessage: 'package not found' }) ``` -------------------------------- ### Update Snapshot Changes Source: https://github.com/badges/shields/blob/master/README.md Command to update saved snapshots after making deliberate changes to output. Use with caution. ```bash SNAPSHOT_UPDATE=1 npm run test:package ``` -------------------------------- ### Function 'sum' Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Calculate the sum of values in an array property. ```JSONPath $.data.sum() ``` -------------------------------- ### Dot Notation After Recursive Descent and Union Source: https://github.com/badges/shields/blob/master/frontend/blog/2024-09-25-rce.md Shows dot notation following recursive descent with an extra dot, and dot notation after a union of keys. ```jsonpath ...key ``` ```jsonpath $['one','three'].key ```