Giter Club home page Giter Club logo

package-json's Introduction

@npmcli/package-json

npm version Build Status

Programmatic API to update package.json files. Updates and saves files the same way the npm cli handles them.

Install

npm install @npmcli/package-json

Usage:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load(path)
// $ cat package.json
// {
//   "name": "foo",
//   "version": "1.0.0",
//   "dependencies": {
//     "a": "^1.0.0",
//     "abbrev": "^1.1.1"
//   }
// }

pkgJson.update({
  dependencies: {
    a: '^1.0.0',
    b: '^1.2.3',
  },
  workspaces: [
    './new-workspace',
  ],
})

await pkgJson.save()
// $ cat package.json
// {
//   "name": "foo",
//   "version": "1.0.0",
//   "dependencies": {
//     "a": "^1.0.0",
//     "b": "^1.2.3"
//   },
//   "workspaces": [
//     "./new-workspace"
//   ]
// }

API:

constructor()

Creates a new empty instance of PackageJson.


async PackageJson.create(path)

Creates an empty package.json at the given path. If one already exists it will be overwritten.


async PackageJson.load(path, opts = {})

Loads a package.json at the given path.

  • opts: Object can contain:
    • create: Boolean if true, a new package.json will be created if one does not already exist. Will not clobber ane existing package.json that can not be parsed.

Example:

Loads contents of a package.json file located at ./:

const PackageJson = require('@npmcli/package-json')
const pkgJson = new PackageJson()
await pkgJson.load('./')

Throws an error in case a package.json file is missing or has invalid contents.


static async PackageJson.load(path)

Convenience static method that returns a new instance and loads the contents of a package.json file from that location.

  • path: String that points to the folder from where to read the package.json from

Example:

Loads contents of a package.json file located at ./:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')

async PackageJson.normalize()

Intended for normalizing package.json files in a node_modules tree. Some light normalization is done to ensure that it is ready for use in @npmcli/arborist

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

static async PackageJson.normalize(path, opts = {})

Convenience static that calls load before calling normalize

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

async PackageJson.prepare()

Like normalize but intended for preparing package.json files for publish.


static async PackageJson.prepare(path, opts = {})

Convenience static that calls load before calling prepare

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

async PackageJson.fix()

Like normalize but intended for the npm pkg fix command.


PackageJson.update(content)

Updates the contents of a package.json with the content provided.

  • content: Object containing the properties to be updated/replaced in the package.json file.

Special properties like dependencies, devDependencies, optionalDependencies, peerDependencies will have special logic to handle the update of these options, such as sorting and deduplication.

Example:

Adds a new script named new-script to your package.json scripts property:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
  scripts: {
    ...pkgJson.content.scripts,
    'new-script': 'echo "Bom dia!"'
  }
})

NOTE: When working with dependencies, it's important to provide values for all known dependency types as the update logic has some interdependence in between these properties.

Example:

A safe way to add a devDependency AND remove all peer dependencies of an existing package.json:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
  dependencies: pkgJson.content.dependencies,
  devDependencies: {
    ...pkgJson.content.devDependencies,
    foo: '^[email protected]',
  },
  peerDependencies: {},
  optionalDependencies: pkgJson.content.optionalDependencies,
})

get PackageJson.content

Getter that retrieves the normalized Object read from the loaded package.json file.

Example:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.content
// -> {
//   name: 'foo',
//   version: '1.0.0'
// }

async PackageJson.save()

Saves the current content to the same location used when calling load().

LICENSE

ISC

package-json's People

Contributors

10xlacroixdrinker avatar dependabot[bot] avatar github-actions[bot] avatar lukekarrys avatar ruyadorno avatar wraithgar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

package-json's Issues

[BUG] Redirect Installation of package x when a request for package y installation is made using config in package.json

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Need to change the entire sourcecode for the npmjs project or use an local alias to install a different package B instead of package A.

Expected Behavior

I should be able to redirect installation of a npmjs A package to npmjs B package from package.json config.

Citing my repositories as an example to ensure not to make phpcgijs old versions unfindable. What I am wishing to do is redirect phpcgijs to cgijs

package.json

{
...
"repository": {
    "type": "git",
    "url": "https://github.com/ganeshkbhat/cgi-js.git",
    "redirect": "newpackagename_preferably--OR--differentrepository"
  }
}

OR

{
...
"redirect": "newpackagename_preferably"
"repository": {
    "type": "git",
    "url": "https://github.com/ganeshkbhat/cgi-js.git"
  }
}

Steps To Reproduce

NA

Environment

  • npm: Current
  • Node: Current
  • OS: Windows / Linux / Mac
  • platform: Windows / Linux / Mac

[BUG] `bin` was converted to an object warnings when using string as `bin`.

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

In the package.json's bin documentation, it's documented that you can use an object with one or more bin file references OR use a single string.

image

Unfortunately, this is now marked as "error in your package.json when publishing".

image

Expected Behavior

I expected this notation to not be marked as an error, as the documentation clearly documents this as a valid option.

Steps To Reproduce

  • $ npm init
  • Add a bin file
  • Configure "bin": "path/to/file.js"
  • $ npm publish

image

Environment

  • npm: 10.2.4
  • Node: 20.10.0
  • OS: MacOS Sonoma 14.2.1
  • platform: Macbook Pro (14", 2023)

Consider a mode that does not strip build-id

Build id is a pretty grey area for semver and the npm registry. Since it's not part of semver resolution it's stripped when sending the packument data, but kept in the package.json in the tarball.

Discussion at npm/cli#1479

npm pkg fix may want to not strip build id by default.

Release 3.1.0 does not correctly normalize package bins

[email protected] was published but never tagged latest due to a bug found during release. below is a root cause of the bug, but the tl;dr is that [email protected] will be deprecated and [email protected] will be published once the bug is fixed.

we switched from read-package-json to @npmcli/package-json which recently received an update to bring all the features from the former to the latter. lost in this port was a minor change to normalizing package bins. previously we would not parse package.json#directories.bin if a package.json#bin was present (ref: https://github.com/npm/read-package-json/blob/main/lib/read-json.js#L351-L353) but now we do regardless of whether a bin object is there (ref: https://github.com/npm/package-json/blob/main/lib/normalize.js#L161)

next steps:

  • deprecate [email protected]. this version exists on the registry and contains breaking changes that would impact users if you publish packages using both bin and directories.bin
  • make a fix for this bug in @npmcli/package.json
  • do a further analysis of the changes between read-package-json and @npmcli/package-json and assert this behavior in news tests to ensure no other breaking changes occurred
  • do a new release for [email protected]

Originally posted by @lukekarrys in npm/cli#6470 (comment)

[BUG] `normalize` will report a missing scripts as invalid, then delete it instead of creating it

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

When the scripts key is entirely missing from a package.json, the normalize function will report it as invalid and that it was removed, then delete. Of course, the key never existed at all, so deleting it does nothing.

See:
npm/cli#7127

Expected Behavior

If scripts being required to be at least an empty object is intended, then I'd expect normalize to set it to that instead of deleting it. If scripts can be omitted, then I'd expect it to not report them as invalid.

As an aside, the message Removed invalid "scripts" is very misleading if scripts was already missing.

Steps To Reproduce

  1. npm init -y
  2. npm pkg delete scripts
  3. npm i @npmcli/package-json
  4. Put this as index.js:
const changes = [];
require("@npmcli/package-json")
  .fix(".", { changes })
  .then(
    (res) => console.log(changes.join("\n"), res.content.scripts),
    console.error
  );
  1. node index.js
  2. Prints Removed invalid "scripts" undefined, it errored about the missing scripts, but didn't fix it.

Environment

  • npm: 10.3.0
  • Node: 21.9.0
  • OS: macOS 13.6.3
  • platform: Macbook Pro

Reporting a vulnerability

Hello!

I hope you are doing well!

We are a security research team. Our tool automatically detected a vulnerability in this repository. We want to disclose it responsibly. GitHub has a feature called Private vulnerability reporting, which enables security research to privately disclose a vulnerability. Unfortunately, it is not enabled for this repository.

Can you enable it, so that we can report it?

Thanks in advance!

PS: you can read about how to enable private vulnerability reporting here: https://docs.github.com/en/code-security/security-advisories/repository-security-advisories/configuring-private-vulnerability-reporting-for-a-repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.