Aller au contenu

Open source / Gauge / pkg-field-gauge

pkg-field-gauge

Validate package.json before you publish: exports/main/types/bin consistency and condition order, targets that do not exist or are not in "files", ESM/CJS mismatches, name/version rules, repository, keywords, license and sideEffects. Text/JSON/SARIF/Markdown, allowlist with expiry, GitHub Action. Zero deps.

Sur npm
$ npm install pkg-field-gauge

README

pkg-field-gauge

npm version CI Node License: MIT

Validate package.json before you publish: exports/main/types consistency, files, repository, keywords and sideEffects.

A package can pass its tests and still ship broken. The types condition sits after import, so TypeScript never sees it. require points at an ESM file. main and exports["."] load different files. The .d.ts isn't covered by files. sideEffects: false lets bundlers drop your CSS. The repository doesn't match the git remote, so provenance publishing fails. pkg-field-gauge resolves every entry point on disk and checks each field the way Node, TypeScript, bundlers and npm read it. Every finding has a line number and a concrete fix.

CLI, library and GitHub Action. Node.js 18+, zero runtime dependencies. By Louis Wright.

Features

  • Entry points: main (resolved like Node: +.js, /index.js), module, browser, types/typings, every bin (plus a #! shebang check) and every exports target, including subpath patterns (./utils/*), conditions and fallback arrays.
  • exports rules: targets must start with ./ and stay inside the package; subpaths and conditions can't be mixed; types must come first and default last; require must not point at ESM and import must not point at CommonJS (checked against the extension and "type"); a types condition must point at a .d.ts; main/types must be reachable through exports["."]; ./package.json should be exported.
  • files: every entry point must be published (npm always includes package.json, README, LICENSE, main and bin), and entries that match nothing are reported.
  • Metadata: npm name rules, SemVer version, field types, type value, description, keywords, SPDX license, repository format and agreement with git remote origin, homepage/bugs, deprecated fields (preferGlobal, typings, licenses…), sideEffects validity and the CSS trap. --require adds your own required fields.
  • Output: text, JSON, SARIF 2.1.0 and Markdown, with package.json line numbers; --fail-on; exit codes 0/1/2; allowlist entries with expiry dates.

Types per resolution mode, tarball linting and HTML reports

pkg-field-gauge --pack                 # lint what npm would publish (npm pack --dry-run)
pkg-field-gauge -f html > report.html  # self-contained HTML report
  • For every subpath export, pkg-field-gauge works out which .d.ts TypeScript loads under node10, node16 (CJS and ESM) and bundler resolution, and flags missing types and types that masquerade as the wrong module format (the classic dual-package mistake of one ESM index.d.ts for both import and require).
  • Per-package API for tools such as monorepo-gauge:
import { checkPackage } from 'pkg-field-gauge';   // or require('pkg-field-gauge')
const { name, findings } = checkPackage('packages/a', { skip: ['keywords-missing'] });
  • Scope: package.json entry points and metadata only. engines checks live in engines-gauge and README checks in readme-gauge.

Module formats and types

Ships ESM and CommonJS (import and require both work, via exports), with TypeScript declarations generated from the source at build time. Tests run on Node 18/20/22 in GitHub Actions (test/), including require/import checks against the packed tarball; releases are published with npm provenance.

Rules

RuleDefault severityWhat it catches
invalid-namecriticalname is missing or not a valid npm package name
invalid-versionhighversion is missing or not valid SemVer
entry-missinghighmain/module/types/bin/browser points at a file that does not exist
exports-target-missinghighAn exports target does not exist
exports-invalidhighexports is malformed (relative ./ targets, subpaths vs conditions)
not-in-fileshighAn entry point is not included by "files", so it will not be published
format-mismatchmediumrequire/import target has the wrong module format for its extension and "type"
exports-condition-ordermedium"types" must be the first condition and "default" the last
types-not-exportedmediumtypes exist but exports["."] has no "types" condition
main-not-exportedmediummain is not reachable through exports["."]
bin-no-shebangmediumbin file has no #! shebang
side-effects-invalidmediumsideEffects is not a boolean or array of globs, or would drop CSS
repository-missingmediumNo repository field
license-missingmediumNo license field
field-typemediumField has the wrong type
repository-mismatchlowrepository does not match the git remote or is malformed
files-entry-unmatchedlowA "files" entry matches nothing
keywords-missinglowNo keywords (hurts npm search)
description-missinglowNo description
license-invalidlowlicense is not a valid SPDX expression
deprecated-fieldlowDeprecated or non-standard field
required-fieldlowA field required by your config is missing
package-json-not-exportedinfoexports hides ./package.json from tools
homepage-missinginfoNo homepage or bugs URL
allowlist-expiredmediumAllowlist entry has expired
allowlist-unusedinfoAllowlist entry matched nothing

Install and run

npx pkg-field-gauge                         # check ./package.json (run after your build)
npx pkg-field-gauge packages/core --fail-on medium
npx pkg-field-gauge --require funding,author

Add it to prepublishOnly so a broken manifest can never be published:

{ "scripts": { "prepublishOnly": "npm run build && pkg-field-gauge --fail-on medium" } }

Sample output

pkg-field-gauge — Broken_Pkg@1.0
ESM package; exports, 1 bin(s), files: 2 entries

CRITICAL package.json:2 name "Broken_Pkg" contains uppercase letters [invalid-name]
         ↳ fix: Use a lowercase, URL-safe name (optionally @scope/name).
HIGH     package.json:14 types target "lib/index.d.ts" is not included by "files", so it will be missing from the published package [not-in-files]
         ↳ fix: Add "lib" to "files".
MEDIUM   package.json:7 exports["."]: "types" is condition #3; TypeScript only sees it when it comes first [exports-condition-order]
         ↳ fix: Move "types" to the top of the object.
MEDIUM   package.json:7 exports["."].require → "./lib/index.js" is ESM ("type": "module") [format-mismatch]
         ↳ fix: Point "require" at a .cjs build (or drop the condition if you only ship ESM).

Options

pkg-field-gauge 1.0.0 — validate package.json fields before you publish

Usage: pkg-field-gauge [dir] [options]

Fields
      --require <fields>    Extra required fields (comma-separated, dotted paths ok: funding,author)

Common
  -c, --config <file>     JSON config (default: .pkg-field-gauge.json or "pkgFieldGauge" in package.json)
  -f, --format <fmt>      text (default) | json | sarif | markdown
      --json <file>       Also write a JSON report
      --sarif <file>      Also write SARIF 2.1.0
      --markdown <file>   Also write Markdown (e.g. for a job summary)
      --fail-on <sev>     critical | high | medium | low | info | none (default: high)
      --list-rules        Print rules and default severities
      --no-fixes          Hide fix suggestions in text output
      --no-color          Disable colours
  -v, --version / -h, --help

Exit codes: 0 = passed, 1 = findings at or above --fail-on, 2 = usage, config or read error.

Configuration and allowlist

Options can live in .pkg-field-gauge.json (or a "pkgFieldGauge" key in package.json, or --config <file>):

{
  "failOn": "medium",
  "severity": { "package-json-not-exported": "low" },
  "allowlist": [
    { "rule": "keywords-missing", "subject": "exports:./legacy", "reason": "Kept for v1 consumers until 2027", "expires": "2027-03-31" }
  ],
  "require": ["description", "keywords", "license", "repository", "funding"]
}
  • severity changes a rule's severity, or turns it "off".
  • allowlist entries suppress matching findings. Each needs a reason and matches on any combination of rule, file, subject (globs with *) and match (a substring of the message). Add expires (YYYY-MM-DD) so the exception is time-boxed: once it lapses the finding comes back along with an allowlist-expired finding (medium). Entries that no longer match anything are reported as allowlist-unused (info).

Output and exit codes

  • --format text (default), json, sarif (SARIF 2.1.0 for GitHub code scanning) or markdown (for job summaries and PR comments). --json, --sarif and --markdown write extra report files in the same run.
  • --fail-on <severity> sets the threshold (critical, high, medium, low, info, none; default high).
  • Exit codes: 0 passed, 1 findings at or above --fail-on, 2 usage, config or read error.

GitHub Action

permissions:
  contents: read
  security-events: write   # only needed for the SARIF upload
jobs:
  pkg-field-gauge:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
        with: { persist-credentials: false }
      - uses: MrLouisWright/pkg-field-gauge@v1
        with:
          fail-on: high
          sarif: pkg-field-gauge.sarif
      - uses: github/codeql-action/upload-sarif@v3
        if: always()
        with: { sarif_file: pkg-field-gauge.sarif }
InputDescriptionDefault
pathProject directory.
fail-onFailure thresholdhigh
configConfig file path
sarif / jsonWrite SARIF / JSON report to this path
job-summaryAdd the Markdown report to the job summarytrue
argsExtra CLI arguments

The action runs the bundled CLI with Node 20; it has no dependencies to install. Pin it to a commit SHA if your policy requires it.

Run it after your build step so the files under exports exist.

Library

import { check, validName, validLicense } from 'pkg-field-gauge';
const report = check('.');
validName('My-Package'); // ['contains uppercase letters']
validLicense('(MIT OR Apache-2.0)'); // true

Types are included.

Requirements

Node.js 18 or newer. Zero runtime dependencies.

Support

If this project is useful to you, you can support its development with a donation: Buy me a coffee. It helps keep these tools maintained, documented and free for everyone.

Credit (optional)

Free to use under MIT, no attribution required. If pkg-field-gauge helps you, a link back is appreciated:

<a href="https://louiswright.co.uk">Built with pkg-field-gauge by Louis Wright</a>
[![Built with pkg-field-gauge by Louis Wright](https://img.shields.io/badge/built%20with-pkg--field--gauge-blue)](https://louiswright.co.uk)

Licence

MIT © Louis Wright (Louis Wright)