From bc34aba6507c2d3be175ae5d970ae6d1bd3af142 Mon Sep 17 00:00:00 2001 From: Zoltan Kochan Date: Mon, 5 Mar 2018 13:53:40 +0200 Subject: [PATCH] style: adhere conventions --- src/api/checkCompatibility.ts | 87 ----- .../checkCompatibility/BreakingChangeError.ts | 19 + .../checkCompatibility/ErrorRelatedSources.ts | 5 + .../ModulesBreakingChangeError.ts | 20 + .../UnexpectedStoreError.ts | 16 + src/api/checkCompatibility/index.ts | 33 ++ src/api/extendInstallOptions.ts | 82 ++-- src/api/extendPruneOptions.ts | 30 +- src/api/extendRebuildOptions.ts | 40 +- src/api/extendStoreStatusOptions.ts | 24 +- src/api/extendUninstallOptions.ts | 30 +- src/api/getContext.ts | 28 +- src/api/index.ts | 2 +- src/api/install.ts | 358 +++++++++--------- src/api/link.ts | 64 ++-- src/api/lock.ts | 8 +- src/api/prune.ts | 24 +- src/api/rebuild.ts | 70 ++-- src/api/removeOrphanPkgs.ts | 52 +-- src/api/shrinkwrapsEqual.ts | 2 +- src/api/storePrune.ts | 2 +- src/api/storeStatus.ts | 12 +- src/api/uninstall.ts | 60 +-- src/api/unlink.ts | 28 +- src/binify.ts | 18 +- src/depsFromPackage.ts | 10 +- src/depsToSpecs.ts | 18 +- src/errorTypes.ts | 2 +- src/fs/getPkgDirs.ts | 18 +- src/fs/modulesController.ts | 8 +- src/fs/readPkg.ts | 2 +- src/fs/realNodeModulesDir.ts | 2 +- src/fs/safeReadPkg.ts | 4 +- src/fs/shrinkwrap.ts | 2 +- src/getPkgInfoFromShr.ts | 4 +- src/index.ts | 2 +- src/install/getIsInstallable.ts | 18 +- src/install/postInstall.ts | 58 +-- src/link/index.ts | 140 +++---- src/link/linkBins.ts | 30 +- src/link/resolvePeers.ts | 116 +++--- src/link/updateShrinkwrap.ts | 70 ++-- src/loggers.ts | 8 +- src/logging/logInstallStatus.ts | 2 +- src/memoize.ts | 6 +- src/parseWantedDependencies.ts | 16 +- src/readShrinkwrapFiles.ts | 34 +- src/removeDeps.ts | 12 +- src/removeTopDependency.ts | 14 +- src/resolveDependencies.ts | 242 ++++++------ src/runScript.ts | 22 +- src/safeIsInnerLink.ts | 8 +- src/save.ts | 18 +- src/types.ts | 8 +- test/api.ts | 4 +- test/breakingChanges.ts | 22 +- test/cache.ts | 18 +- test/index.ts | 20 +- test/install/aliases.ts | 16 +- test/install/auth.ts | 94 ++--- test/install/dedupe.ts | 4 +- test/install/fromRepo.ts | 38 +- test/install/fromTarball.ts | 10 +- test/install/global.ts | 12 +- test/install/hooks.ts | 6 +- test/install/independentLeaves.ts | 12 +- test/install/index.ts | 26 +- test/install/installationChecks.ts | 22 +- test/install/lifecycleScripts.ts | 90 ++--- test/install/local.ts | 40 +- test/install/misc.ts | 272 ++++++------- test/install/only.ts | 8 +- test/install/optionalDependencies.ts | 40 +- test/install/peerDependencies.ts | 20 +- test/install/reporting.ts | 22 +- test/install/shamefullyFlatten.ts | 40 +- test/install/shrinkwrapOnly.ts | 14 +- test/install/sideEffects.ts | 14 +- test/install/store.ts | 8 +- test/install/update.ts | 4 +- test/install/updatingPkgJson.ts | 44 +-- test/link.ts | 26 +- test/offline.ts | 10 +- test/packageImportMethods.ts | 36 +- test/prune.ts | 10 +- test/rebuild.ts | 24 +- test/shrinkwrap.ts | 190 +++++----- test/storePrune.ts | 26 +- test/storeStatus.ts | 10 +- test/uninstall.ts | 66 ++-- test/unlink.ts | 60 +-- test/utils/index.ts | 4 +- test/utils/isExecutable.ts | 8 +- test/utils/prepare.ts | 44 +-- test/utils/testDefaults.ts | 18 +- tslint.json | 3 + 96 files changed, 1745 insertions(+), 1718 deletions(-) delete mode 100644 src/api/checkCompatibility.ts create mode 100644 src/api/checkCompatibility/BreakingChangeError.ts create mode 100644 src/api/checkCompatibility/ErrorRelatedSources.ts create mode 100644 src/api/checkCompatibility/ModulesBreakingChangeError.ts create mode 100644 src/api/checkCompatibility/UnexpectedStoreError.ts create mode 100644 src/api/checkCompatibility/index.ts diff --git a/src/api/checkCompatibility.ts b/src/api/checkCompatibility.ts deleted file mode 100644 index 16fef07b34..0000000000 --- a/src/api/checkCompatibility.ts +++ /dev/null @@ -1,87 +0,0 @@ -import {stripIndent, oneLine} from 'common-tags' -import {Modules, LAYOUT_VERSION} from '../fs/modulesController' -import {PnpmError, PnpmErrorCode} from '../errorTypes' -import semver = require('semver') -import path = require('path') - -class UnexpectedStoreError extends PnpmError { - constructor ( - opts: { - expectedStorePath: string, - actualStorePath: string, - } - ) { - super('UNEXPECTED_STORE', 'Unexpected store used for installation') - this.expectedStorePath = opts.expectedStorePath - this.actualStorePath = opts.actualStorePath - } - expectedStorePath: string - actualStorePath: string -} - -type BreakingChangeErrorOptions = ErrorRelatedSources & { - code: PnpmErrorCode, - message: string, -} - -type ErrorRelatedSources = { - additionalInformation?: string, - relatedIssue?: number, - relatedPR?: number, -} - -class BreakingChangeError extends PnpmError { - constructor (opts: BreakingChangeErrorOptions) { - super(opts.code, opts.message) - this.relatedIssue = opts.relatedIssue - this.relatedPR = opts.relatedPR - this.additionalInformation = opts.additionalInformation - } - relatedIssue?: number - relatedPR?: number - additionalInformation?: string -} - -type ModulesBreakingChangeErrorOptions = ErrorRelatedSources & { - modulesPath: string, -} - -class ModulesBreakingChangeError extends BreakingChangeError { - constructor (opts: ModulesBreakingChangeErrorOptions) { - super({ - code: 'MODULES_BREAKING_CHANGE', - message: `The node_modules structure at ${opts.modulesPath} was changed. Try running the same command with the --force parameter.`, - additionalInformation: opts.additionalInformation, - relatedIssue: opts.relatedIssue, - relatedPR: opts.relatedPR, - }) - this.modulesPath = opts.modulesPath - } - modulesPath: string -} - -export default function checkCompatibility ( - modules: Modules, - opts: { - storePath: string, - modulesPath: string, - } -) { - // Important: comparing paths with path.relative() - // is the only way to compare paths correctly on Windows - // as of Node.js 4-9 - // See related issue: https://github.com/pnpm/pnpm/issues/996 - if (path.relative(modules.store, opts.storePath) !== '') { - throw new UnexpectedStoreError({ - expectedStorePath: modules.store, - actualStorePath: opts.storePath, - }) - } - if (!modules.layoutVersion || modules.layoutVersion !== LAYOUT_VERSION) { - throw new ModulesBreakingChangeError({ - modulesPath: opts.modulesPath, - additionalInformation: 'The change was needed to make `independent-leafs` not the default installation layout', - relatedIssue: 821, - }) - } -} diff --git a/src/api/checkCompatibility/BreakingChangeError.ts b/src/api/checkCompatibility/BreakingChangeError.ts new file mode 100644 index 0000000000..a1e8ce66af --- /dev/null +++ b/src/api/checkCompatibility/BreakingChangeError.ts @@ -0,0 +1,19 @@ +import {PnpmError, PnpmErrorCode} from '../../errorTypes' +import ErrorRelatedSources from './ErrorRelatedSources' + +export type BreakingChangeErrorOptions = ErrorRelatedSources & { + code: PnpmErrorCode, + message: string, +} + +export default class BreakingChangeError extends PnpmError { + public relatedIssue?: number + public relatedPR?: number + public additionalInformation?: string + constructor (opts: BreakingChangeErrorOptions) { + super(opts.code, opts.message) + this.relatedIssue = opts.relatedIssue + this.relatedPR = opts.relatedPR + this.additionalInformation = opts.additionalInformation + } +} diff --git a/src/api/checkCompatibility/ErrorRelatedSources.ts b/src/api/checkCompatibility/ErrorRelatedSources.ts new file mode 100644 index 0000000000..80a10e6158 --- /dev/null +++ b/src/api/checkCompatibility/ErrorRelatedSources.ts @@ -0,0 +1,5 @@ +export default interface ErrorRelatedSources { + additionalInformation?: string, + relatedIssue?: number, + relatedPR?: number, +} diff --git a/src/api/checkCompatibility/ModulesBreakingChangeError.ts b/src/api/checkCompatibility/ModulesBreakingChangeError.ts new file mode 100644 index 0000000000..271d9fd861 --- /dev/null +++ b/src/api/checkCompatibility/ModulesBreakingChangeError.ts @@ -0,0 +1,20 @@ +import BreakingChangeError from './BreakingChangeError' +import ErrorRelatedSources from './ErrorRelatedSources' + +export type ModulesBreakingChangeErrorOptions = ErrorRelatedSources & { + modulesPath: string, +} + +export default class ModulesBreakingChangeError extends BreakingChangeError { + public modulesPath: string + constructor (opts: ModulesBreakingChangeErrorOptions) { + super({ + additionalInformation: opts.additionalInformation, + code: 'MODULES_BREAKING_CHANGE', + message: `The node_modules structure at ${opts.modulesPath} was changed. Try running the same command with the --force parameter.`, + relatedIssue: opts.relatedIssue, + relatedPR: opts.relatedPR, + }) + this.modulesPath = opts.modulesPath + } +} diff --git a/src/api/checkCompatibility/UnexpectedStoreError.ts b/src/api/checkCompatibility/UnexpectedStoreError.ts new file mode 100644 index 0000000000..72fff8b003 --- /dev/null +++ b/src/api/checkCompatibility/UnexpectedStoreError.ts @@ -0,0 +1,16 @@ +import {PnpmError, PnpmErrorCode} from '../../errorTypes' + +export default class UnexpectedStoreError extends PnpmError { + public expectedStorePath: string + public actualStorePath: string + constructor ( + opts: { + expectedStorePath: string, + actualStorePath: string, + }, + ) { + super('UNEXPECTED_STORE', 'Unexpected store used for installation') + this.expectedStorePath = opts.expectedStorePath + this.actualStorePath = opts.actualStorePath + } +} diff --git a/src/api/checkCompatibility/index.ts b/src/api/checkCompatibility/index.ts new file mode 100644 index 0000000000..db90381f40 --- /dev/null +++ b/src/api/checkCompatibility/index.ts @@ -0,0 +1,33 @@ +import {oneLine, stripIndent} from 'common-tags' +import path = require('path') +import semver = require('semver') +import {PnpmError, PnpmErrorCode} from '../../errorTypes' +import {LAYOUT_VERSION, Modules} from '../../fs/modulesController' +import ModulesBreakingChangeError from './ModulesBreakingChangeError' +import UnexpectedStoreError from './UnexpectedStoreError' + +export default function checkCompatibility ( + modules: Modules, + opts: { + storePath: string, + modulesPath: string, + }, +) { + // Important: comparing paths with path.relative() + // is the only way to compare paths correctly on Windows + // as of Node.js 4-9 + // See related issue: https://github.com/pnpm/pnpm/issues/996 + if (path.relative(modules.store, opts.storePath) !== '') { + throw new UnexpectedStoreError({ + actualStorePath: opts.storePath, + expectedStorePath: modules.store, + }) + } + if (!modules.layoutVersion || modules.layoutVersion !== LAYOUT_VERSION) { + throw new ModulesBreakingChangeError({ + additionalInformation: 'The change was needed to make `independent-leafs` not the default installation layout', + modulesPath: opts.modulesPath, + relatedIssue: 821, + }) + } +} diff --git a/src/api/extendInstallOptions.ts b/src/api/extendInstallOptions.ts index 235c5af9db..7d47a9b7e6 100644 --- a/src/api/extendInstallOptions.ts +++ b/src/api/extendInstallOptions.ts @@ -1,13 +1,13 @@ -import path = require('path') import logger from '@pnpm/logger' -import pnpmPkgJson from '../pnpmPkgJson' -import {LAYOUT_VERSION} from '../fs/modulesController' +import { ReadPackageHook } from '@pnpm/types' import normalizeRegistryUrl = require('normalize-registry-url') import {StoreController} from 'package-store' +import path = require('path') +import {LAYOUT_VERSION} from '../fs/modulesController' +import pnpmPkgJson from '../pnpmPkgJson' import { ReporterFunction } from '../types' -import { ReadPackageHook } from '@pnpm/types' -export type InstallOptions = { +export interface InstallOptions { storeController: StoreController, store: string, reporter?: ReporterFunction, @@ -102,49 +102,49 @@ const defaults = async (opts: InstallOptions) => { version: pnpmPkgJson.version, } const prefix = opts.prefix || process.cwd() - return { - storeController: opts.storeController, - shrinkwrap: true, - shrinkwrapOnly: false, - saveExact: false, - global: false, - store: opts.store, - locks: path.join(opts.store, '_locks'), - ignoreScripts: false, - tag: 'latest', - production: true, - development: true, + return { bin: path.join(prefix, 'node_modules', '.bin'), - prefix, - nodeVersion: process.version, - force: false, - depth: 0, - engineStrict: false, - lockStaleDuration: 60 * 1000, // 1 minute - lock: true, childConcurrency: 5, - registry: 'https://registry.npmjs.org/', - userAgent: `${packageManager.name}/${packageManager.version} npm/? node/${process.version} ${process.platform} ${process.arch}`, - rawNpmConfig: {}, - update: false, - repeatInstallDepth: -1, - optional: typeof opts.production === 'boolean' ? opts.production : true, - independentLeaves: false, - packageManager, - verifyStoreIntegrity: true, + depth: 0, + development: true, + engineStrict: false, + force: false, + global: false, hooks: {}, + ignoreScripts: false, + independentLeaves: false, + lock: true, + lockStaleDuration: 60 * 1000, // 1 minute + locks: path.join(opts.store, '_locks'), + nodeVersion: process.version, + optional: typeof opts.production === 'boolean' ? opts.production : true, + packageManager, + prefix, + production: true, + rawNpmConfig: {}, + registry: 'https://registry.npmjs.org/', + repeatInstallDepth: -1, + saveDev: false, + saveExact: false, + saveOptional: false, savePrefix: '^', shamefullyFlatten: false, + shrinkwrap: true, + shrinkwrapOnly: false, sideEffectsCache: false, sideEffectsCacheReadonly: false, + store: opts.store, + storeController: opts.storeController, + tag: 'latest', unsafePerm: process.platform === 'win32' || - process.platform === 'cygwin' || - !(process.getuid && process.setuid && - process.getgid && process.setgid) || - process.getuid() !== 0, - saveDev: false, - saveOptional: false, - } + process.platform === 'cygwin' || + !(process.getuid && process.setuid && + process.getgid && process.setgid) || + process.getuid() !== 0, + update: false, + userAgent: `${packageManager.name}/${packageManager.version} npm/? node/${process.version} ${process.platform} ${process.arch}`, + verifyStoreIntegrity: true, + } as StrictInstallOptions } export default async ( @@ -182,7 +182,7 @@ export default async ( const subfolder = LAYOUT_VERSION.toString() + independentLeavesSuffix + shamefullyFlattenSuffix extendedOpts.prefix = path.join(extendedOpts.prefix, subfolder) } - extendedOpts.rawNpmConfig['registry'] = extendedOpts.registry + extendedOpts.rawNpmConfig['registry'] = extendedOpts.registry // tslint:disable-line:no-string-literal // if sideEffectsCacheReadonly is true, sideEffectsCache is necessarily true too if (extendedOpts.sideEffectsCache && extendedOpts.sideEffectsCacheReadonly) { logger.warn("--side-effects-cache-readonly turns on side effects cache too, you don't need to specify both") diff --git a/src/api/extendPruneOptions.ts b/src/api/extendPruneOptions.ts index b23392d970..462c5007eb 100644 --- a/src/api/extendPruneOptions.ts +++ b/src/api/extendPruneOptions.ts @@ -1,12 +1,12 @@ -import path = require('path') import logger from '@pnpm/logger' -import pnpmPkgJson from '../pnpmPkgJson' -import {LAYOUT_VERSION} from '../fs/modulesController' import normalizeRegistryUrl = require('normalize-registry-url') import {StoreController} from 'package-store' +import path = require('path') +import {LAYOUT_VERSION} from '../fs/modulesController' +import pnpmPkgJson from '../pnpmPkgJson' import { ReporterFunction } from '../types' -export type PruneOptions = { +export interface PruneOptions { prefix?: string, store: string, independentLeaves?: boolean, @@ -42,21 +42,21 @@ export type StrictPruneOptions = PruneOptions & { const defaults = async (opts: PruneOptions) => { const prefix = opts.prefix || process.cwd() - return { - shamefullyFlatten: false, - storeController: opts.storeController, - global: false, - store: opts.store, + return { bin: path.join(prefix, 'node_modules', '.bin'), - prefix, - force: false, - registry: 'https://registry.npmjs.org/', - independentLeaves: false, - production: true, development: true, + force: false, + global: false, + independentLeaves: false, optional: true, + prefix, + production: true, + registry: 'https://registry.npmjs.org/', + shamefullyFlatten: false, shrinkwrap: true, - } + store: opts.store, + storeController: opts.storeController, + } as StrictPruneOptions } export default async ( diff --git a/src/api/extendRebuildOptions.ts b/src/api/extendRebuildOptions.ts index 15c4b40700..60e19b883b 100644 --- a/src/api/extendRebuildOptions.ts +++ b/src/api/extendRebuildOptions.ts @@ -1,12 +1,12 @@ -import path = require('path') import logger from '@pnpm/logger' -import pnpmPkgJson from '../pnpmPkgJson' -import {LAYOUT_VERSION} from '../fs/modulesController' import normalizeRegistryUrl = require('normalize-registry-url') import {StoreController} from 'package-store' +import path = require('path') +import {LAYOUT_VERSION} from '../fs/modulesController' +import pnpmPkgJson from '../pnpmPkgJson' import { ReporterFunction } from '../types' -export type RebuildOptions = { +export interface RebuildOptions { prefix?: string, store: string, // TODO: remove this property independentLeaves?: boolean, @@ -57,26 +57,26 @@ const defaults = async (opts: RebuildOptions) => { version: pnpmPkgJson.version, } const prefix = opts.prefix || process.cwd() - return { - pending: false, - global: false, - store: opts.store, + return { bin: path.join(prefix, 'node_modules', '.bin'), - userAgent: `${packageManager.name}/${packageManager.version} npm/? node/${process.version} ${process.platform} ${process.arch}`, - packageManager, - prefix, force: false, - registry: 'https://registry.npmjs.org/', - rawNpmConfig: {}, + global: false, independentLeaves: false, - unsafePerm: process.platform === 'win32' || - process.platform === 'cygwin' || - !(process.getuid && process.setuid && - process.getgid && process.setgid) || - process.getuid() !== 0, - shrinkwrap: true, + packageManager, + pending: false, + prefix, + rawNpmConfig: {}, + registry: 'https://registry.npmjs.org/', shamefullyFlatten: false, - } + shrinkwrap: true, + store: opts.store, + unsafePerm: process.platform === 'win32' || + process.platform === 'cygwin' || + !(process.getuid && process.setuid && + process.getgid && process.setgid) || + process.getuid() !== 0, + userAgent: `${packageManager.name}/${packageManager.version} npm/? node/${process.version} ${process.platform} ${process.arch}`, + } as StrictRebuildOptions } export default async ( diff --git a/src/api/extendStoreStatusOptions.ts b/src/api/extendStoreStatusOptions.ts index 31c6e46d9d..e4e801c14e 100644 --- a/src/api/extendStoreStatusOptions.ts +++ b/src/api/extendStoreStatusOptions.ts @@ -1,13 +1,13 @@ -import path = require('path') import logger from '@pnpm/logger' -import pnpmPkgJson from '../pnpmPkgJson' -import {LAYOUT_VERSION} from '../fs/modulesController' +import { ReadPackageHook } from '@pnpm/types' import normalizeRegistryUrl = require('normalize-registry-url') import {StoreController} from 'package-store' +import path = require('path') +import {LAYOUT_VERSION} from '../fs/modulesController' +import pnpmPkgJson from '../pnpmPkgJson' import { ReporterFunction } from '../types' -import { ReadPackageHook } from '@pnpm/types' -export type StoreStatusOptions = { +export interface StoreStatusOptions { prefix?: string, store: string, independentLeaves?: boolean, @@ -38,17 +38,17 @@ export type StrictStoreStatusOptions = StoreStatusOptions & { const defaults = async (opts: StoreStatusOptions) => { const prefix = opts.prefix || process.cwd() - return { - global: false, - store: opts.store, + return { bin: path.join(prefix, 'node_modules', '.bin'), - prefix, force: false, - registry: 'https://registry.npmjs.org/', + global: false, independentLeaves: false, - shrinkwrap: true, + prefix, + registry: 'https://registry.npmjs.org/', shamefullyFlatten: false, - } + shrinkwrap: true, + store: opts.store, + } as StrictStoreStatusOptions } export default async ( diff --git a/src/api/extendUninstallOptions.ts b/src/api/extendUninstallOptions.ts index 12cd7d27dc..005ccb4df1 100644 --- a/src/api/extendUninstallOptions.ts +++ b/src/api/extendUninstallOptions.ts @@ -1,12 +1,12 @@ -import path = require('path') import logger from '@pnpm/logger' -import pnpmPkgJson from '../pnpmPkgJson' -import {LAYOUT_VERSION} from '../fs/modulesController' import normalizeRegistryUrl = require('normalize-registry-url') import {StoreController} from 'package-store' +import path = require('path') +import {LAYOUT_VERSION} from '../fs/modulesController' +import pnpmPkgJson from '../pnpmPkgJson' import { ReporterFunction } from '../types' -export type UninstallOptions = { +export interface UninstallOptions { prefix?: string, store: string, independentLeaves?: boolean, @@ -55,22 +55,22 @@ const defaults = async (opts: UninstallOptions) => { version: pnpmPkgJson.version, } const prefix = opts.prefix || process.cwd() - return { - shamefullyFlatten: false, - storeController: opts.storeController, - global: false, - store: opts.store, - locks: path.join(opts.store, '_locks'), + return { bin: path.join(prefix, 'node_modules', '.bin'), - prefix, force: false, - lockStaleDuration: 60 * 1000, // 1 minute - lock: true, - registry: 'https://registry.npmjs.org/', + global: false, independentLeaves: false, + lock: true, + lockStaleDuration: 60 * 1000, // 1 minute + locks: path.join(opts.store, '_locks'), packageManager, + prefix, + registry: 'https://registry.npmjs.org/', + shamefullyFlatten: false, shrinkwrap: true, - } + store: opts.store, + storeController: opts.storeController, + } as StrictUninstallOptions } export default async ( diff --git a/src/api/getContext.ts b/src/api/getContext.ts index 16195b23ca..038a78bb2c 100644 --- a/src/api/getContext.ts +++ b/src/api/getContext.ts @@ -1,21 +1,21 @@ +import logger from '@pnpm/logger' +import {PackageJson} from '@pnpm/types' +import mkdirp = require('mkdirp-promise') +import normalizePath = require('normalize-path') import path = require('path') -import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' -import writePkg = require('write-pkg') -import {StrictSupiOptions} from '../types' import {Shrinkwrap} from 'pnpm-shrinkwrap' +import removeAllExceptOuterLinks = require('remove-all-except-outer-links') +import writePkg = require('write-pkg') import { read as readModules, } from '../fs/modulesController' -import mkdirp = require('mkdirp-promise') -import {PackageJson} from '@pnpm/types' -import normalizePath = require('normalize-path') -import removeAllExceptOuterLinks = require('remove-all-except-outer-links') -import logger from '@pnpm/logger' -import checkCompatibility from './checkCompatibility' +import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' import {packageJsonLogger} from '../loggers' import readShrinkwrapFile from '../readShrinkwrapFiles' +import {StrictSupiOptions} from '../types' +import checkCompatibility from './checkCompatibility' -export type PnpmContext = { +export interface PnpmContext { pkg: PackageJson, storePath: string, root: string, @@ -82,12 +82,12 @@ export default async function getContext ( mkdirp(storePath), ]) const ctx: PnpmContext = { + hoistedAliases: modules && modules.hoistedAliases || {}, + pendingBuilds: modules && modules.pendingBuilds || [], pkg: files[0] || {} as PackageJson, root, - storePath, skipped: new Set(modules && modules.skipped || []), - pendingBuilds: modules && modules.pendingBuilds || [], - hoistedAliases: modules && modules.hoistedAliases || {}, + storePath, ...await readShrinkwrapFile(opts), } packageJsonLogger.debug({ initial: ctx.pkg }) @@ -97,8 +97,8 @@ export default async function getContext ( const DefaultGlobalPkg: PackageJson = { name: 'pnpm-global-pkg', - version: '1.0.0', private: true, + version: '1.0.0', } async function readGlobalPkgJson (globalPkgPath: string) { diff --git a/src/api/index.ts b/src/api/index.ts index efa42fbc30..f77311b9d2 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -5,8 +5,8 @@ export * from './unlink' export * from './rebuild' import link from './link' -import storeStatus from './storeStatus' import storePrune from './storePrune' +import storeStatus from './storeStatus' import uninstall from './uninstall' export { link, diff --git a/src/api/install.ts b/src/api/install.ts index 6ca467ac1c..fea687e19d 100644 --- a/src/api/install.ts +++ b/src/api/install.ts @@ -1,93 +1,93 @@ -import { - Dependencies, - PackageJson, -} from '@pnpm/types' -import * as dp from 'dependency-path' -import path = require('path') import logger, { streamParser, } from '@pnpm/logger' -import { - stageLogger, - summaryLogger, - packageJsonLogger, - rootLogger, -} from '../loggers' -import logStatus from '../logging/logInstallStatus' -import pLimit = require('p-limit') -import pFilter = require('p-filter') -import R = require('ramda') -import safeIsInnerLink from '../safeIsInnerLink' -import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' -import { - WantedDependency, -} from '../types' -import getContext, {PnpmContext} from './getContext' -import resolveDependencies, {InstalledPackage} from '../resolveDependencies' -import externalLink from './link' -import linkPackages from '../link' -import save from '../save' -import getSaveType from '../getSaveType' -import postInstall, {npmRunScript} from '../install/postInstall' -import extendOptions, { - InstallOptions, - StrictInstallOptions, -} from './extendInstallOptions' -import lock from './lock' -import { - write as saveShrinkwrap, - writeWantedOnly as saveWantedShrinkwrapOnly, - writeCurrentOnly as saveCurrentShrinkwrapOnly, - Shrinkwrap, -} from 'pnpm-shrinkwrap' -import {absolutePathToRef} from '../fs/shrinkwrap' -import { - save as saveModules, - LAYOUT_VERSION, -} from '../fs/modulesController' -import {DependencyTreeNode} from '../link/resolvePeers' -import depsToSpecs, {similarDepsToSpecs} from '../depsToSpecs' -import shrinkwrapsEqual from './shrinkwrapsEqual' -import { - StoreController, -} from 'package-store' -import depsFromPackage, {getPreferredVersionsFromPackage} from '../depsFromPackage' -import parseWantedDependencies from '../parseWantedDependencies' import { DirectoryResolution, Resolution, } from '@pnpm/resolver-base' import { - nodeIdContainsSequence, + Dependencies, + PackageJson, +} from '@pnpm/types' +import * as dp from 'dependency-path' +import pFilter = require('p-filter') +import pLimit = require('p-limit') +import { + StoreController, +} from 'package-store' +import path = require('path') +import { + Shrinkwrap, + write as saveShrinkwrap, + writeCurrentOnly as saveCurrentShrinkwrapOnly, + writeWantedOnly as saveWantedShrinkwrapOnly, +} from 'pnpm-shrinkwrap' +import R = require('ramda') +import depsFromPackage, {getPreferredVersionsFromPackage} from '../depsFromPackage' +import depsToSpecs, {similarDepsToSpecs} from '../depsToSpecs' +import { + LAYOUT_VERSION, + save as saveModules, +} from '../fs/modulesController' +import realNodeModulesDir from '../fs/realNodeModulesDir' +import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' +import {absolutePathToRef} from '../fs/shrinkwrap' +import getSaveType from '../getSaveType' +import getSpecFromPackageJson from '../getSpecFromPackageJson' +import postInstall, {npmRunScript} from '../install/postInstall' +import linkPackages from '../link' +import {DependencyTreeNode} from '../link/resolvePeers' +import { + packageJsonLogger, + rootLogger, + stageLogger, + summaryLogger, +} from '../loggers' +import logStatus from '../logging/logInstallStatus' +import { createNodeId, + nodeIdContainsSequence, ROOT_NODE_ID, } from '../nodeIdUtils' -import realNodeModulesDir from '../fs/realNodeModulesDir' -import getSpecFromPackageJson from '../getSpecFromPackageJson' +import parseWantedDependencies from '../parseWantedDependencies' +import resolveDependencies, {InstalledPackage} from '../resolveDependencies' +import safeIsInnerLink from '../safeIsInnerLink' +import save from '../save' +import { + WantedDependency, +} from '../types' +import extendOptions, { + InstallOptions, + StrictInstallOptions, +} from './extendInstallOptions' +import getContext, {PnpmContext} from './getContext' +import externalLink from './link' +import lock from './lock' +import shrinkwrapsEqual from './shrinkwrapsEqual' const ENGINE_NAME = `${process.platform}-${process.arch}-node-${process.version.split('.')[0]}` -export type InstalledPackages = { +export interface InstalledPackages { [name: string]: InstalledPackage } -export type TreeNode = { +export interface TreeNode { children: (() => {[alias: string]: string}) | {[alias: string]: string}, // child nodeId by child alias name pkg: InstalledPackage, depth: number, installable: boolean, } -export type TreeNodeMap = { +export interface TreeNodeMap { [nodeId: string]: TreeNode, } -export type InstallContext = { +export interface InstallContext { defaultTag: string, dryRun: boolean, installs: InstalledPackages, outdatedPkgs: {[pkgId: string]: string}, - localPackages: { + localPackages: Array<{ optional: boolean, dev: boolean, resolution: DirectoryResolution, @@ -97,15 +97,15 @@ export type InstallContext = { specRaw: string, normalizedPref?: string, alias: string, - }[], - childrenByParentId: {[parentId: string]: {alias: string, pkgId: string}[]}, - nodesToBuild: { + }>, + childrenByParentId: {[parentId: string]: Array<{alias: string, pkgId: string}>}, + nodesToBuild: Array<{ alias: string, nodeId: string, pkg: InstalledPackage, depth: number, installable: boolean, - }[], + }>, wantedShrinkwrap: Shrinkwrap, currentShrinkwrap: Shrinkwrap, storeController: StoreController, @@ -119,7 +119,7 @@ export type InstallContext = { engineStrict: boolean, nodeVersion: string, pnpmVersion: string, - rawNpmConfig: Object, + rawNpmConfig: object, nodeModules: string, verifyStoreInegrity: boolean, preferredVersions: { @@ -152,7 +152,7 @@ export async function install (maybeOpts: InstallOptions) { streamParser.removeListener('data', reporter) } - async function _install() { + async function _install () { const installType = 'general' const ctx = await getContext(opts, installType) @@ -180,50 +180,50 @@ export async function install (maybeOpts: InstallOptions) { const scripts = !opts.ignoreScripts && ctx.pkg && ctx.pkg.scripts || {} - if (scripts['prepublish']) { + if (scripts['prepublish']) { // tslint:disable-line:no-string-literal logger.warn('`prepublish` scripts are deprecated. Use `prepare` for build steps and `prepublishOnly` for upload-only.') } const scriptsOpts = { - rawNpmConfig: opts.rawNpmConfig, modulesDir: await realNodeModulesDir(opts.prefix), - root: opts.prefix, pkgId: opts.prefix, + rawNpmConfig: opts.rawNpmConfig, + root: opts.prefix, stdio: 'inherit', unsafePerm: opts.unsafePerm || false, } - if (scripts['preinstall']) { + if (scripts['preinstall']) { // tslint:disable-line:no-string-literal await npmRunScript('preinstall', ctx.pkg, scriptsOpts) } await installInContext(installType, specs, [], ctx, preferredVersions, opts) - if (scripts['install']) { + if (scripts['install']) {// tslint:disable-line:no-string-literal await npmRunScript('install', ctx.pkg, scriptsOpts) } - if (scripts['postinstall']) { + if (scripts['postinstall']) {// tslint:disable-line:no-string-literal await npmRunScript('postinstall', ctx.pkg, scriptsOpts) } - if (scripts['prepublish']) { + if (scripts['prepublish']) {// tslint:disable-line:no-string-literal await npmRunScript('prepublish', ctx.pkg, scriptsOpts) } - if (scripts['prepare']) { + if (scripts['prepare']) {// tslint:disable-line:no-string-literal await npmRunScript('prepare', ctx.pkg, scriptsOpts) } } } -function specsToInstallFromPackage( +function specsToInstallFromPackage ( pkg: PackageJson, opts: { prefix: string, - } + }, ): WantedDependency[] { const depsToInstall = depsFromPackage(pkg) return depsToSpecs(depsToInstall, { - optionalDependencies: pkg.optionalDependencies || {}, devDependencies: pkg.devDependencies || {}, + optionalDependencies: pkg.optionalDependencies || {}, }) } @@ -262,21 +262,21 @@ export async function installPkgs ( const saveType = getSaveType(opts) const optionalDependencies = saveType ? {} : ctx.pkg.optionalDependencies || {} const devDependencies = saveType ? {} : ctx.pkg.devDependencies || {} - let packagesToInstall = Array.isArray(fuzzyDeps) + const packagesToInstall = Array.isArray(fuzzyDeps) ? parseWantedDependencies(fuzzyDeps, { + currentPrefs, defaultTag: opts.tag, dev: opts.saveDev, - optional: opts.saveOptional, - currentPrefs, - optionalDependencies, devDependencies, + optional: opts.saveOptional, + optionalDependencies, }) : similarDepsToSpecs(fuzzyDeps, { - dev: opts.saveDev, - optional: opts.saveOptional, currentPrefs, - optionalDependencies, + dev: opts.saveDev, devDependencies, + optional: opts.saveOptional, + optionalDependencies, }) if (!Object.keys(packagesToInstall).length && !opts.reinstallForFlatten) { @@ -287,7 +287,7 @@ export async function installPkgs ( return installInContext( installType, packagesToInstall, - packagesToInstall.map(wantedDependency => wantedDependency.raw), + packagesToInstall.map((wantedDependency) => wantedDependency.raw), ctx, preferredVersions, opts) @@ -327,20 +327,10 @@ async function installInContext ( const hasManifestInShrinkwrap = typeof ctx.wantedShrinkwrap.shrinkwrapMinorVersion === 'number' const installCtx: InstallContext = { - defaultTag: opts.tag, - dryRun: opts.shrinkwrapOnly, - installs: {}, - outdatedPkgs: {}, - localPackages: [], childrenByParentId: {}, - nodesToBuild: [], - wantedShrinkwrap: ctx.wantedShrinkwrap, currentShrinkwrap: ctx.currentShrinkwrap, - skipped: ctx.skipped, - tree: {}, - registry: ctx.wantedShrinkwrap.registry, - force: opts.force, - depth: (function () { + defaultTag: opts.tag, + depth: (() => { // This can be remove from shrinkwrap v4 if (!hasManifestInShrinkwrap) { // The shrinkwrap file has to be updated to contain @@ -355,35 +345,45 @@ async function installInContext ( } return Infinity })(), + dryRun: opts.shrinkwrapOnly, + engineStrict: opts.engineStrict, + force: opts.force, + installs: {}, + localPackages: [], + nodeModules: nodeModulesPath, + nodeVersion: opts.nodeVersion, + nodesToBuild: [], + outdatedPkgs: {}, + pnpmVersion: opts.packageManager.name === 'pnpm' ? opts.packageManager.version : '', + preferredVersions, prefix: opts.prefix, rawNpmConfig: opts.rawNpmConfig, - nodeModules: nodeModulesPath, - verifyStoreInegrity: opts.verifyStoreIntegrity, - engineStrict: opts.engineStrict, - nodeVersion: opts.nodeVersion, - pnpmVersion: opts.packageManager.name === 'pnpm' ? opts.packageManager.version : '', + registry: ctx.wantedShrinkwrap.registry, + skipped: ctx.skipped, storeController: opts.storeController, - preferredVersions, + tree: {}, + verifyStoreInegrity: opts.verifyStoreIntegrity, + wantedShrinkwrap: ctx.wantedShrinkwrap, } const installOpts = { - root: ctx.root, - resolvedDependencies: { - ...ctx.wantedShrinkwrap.devDependencies, - ...ctx.wantedShrinkwrap.dependencies, - ...ctx.wantedShrinkwrap.optionalDependencies - }, - update: opts.update, + currentDepth: 0, + hasManifestInShrinkwrap, keypath: [], parentNodeId: ROOT_NODE_ID, - currentDepth: 0, readPackageHook: opts.hooks.readPackage, - hasManifestInShrinkwrap, - sideEffectsCache: opts.sideEffectsCache, reinstallForFlatten: opts.reinstallForFlatten, + resolvedDependencies: { + ...ctx.wantedShrinkwrap.dependencies, + ...ctx.wantedShrinkwrap.devDependencies, + ...ctx.wantedShrinkwrap.optionalDependencies, + }, + root: ctx.root, shamefullyFlatten: opts.shamefullyFlatten, + sideEffectsCache: opts.sideEffectsCache, + update: opts.update, } const nonLinkedPkgs: WantedDependency[] = [] - const linkedPkgs: (WantedDependency & {alias: string})[] = [] + const linkedPkgs: Array = [] for (const wantedDependency of packagesToInstall) { if (!wantedDependency.alias) { nonLinkedPkgs.push(wantedDependency) @@ -398,10 +398,10 @@ async function installInContext ( } rootLogger.debug({ linked: { - name: wantedDependency.alias, - from: isInnerLink as string, - to: nodeModulesPath, dependencyType: wantedDependency.dev && 'dev' || wantedDependency.optional && 'optional' || 'prod', + from: isInnerLink as string, + name: wantedDependency.alias, + to: nodeModulesPath, }, }) // This info-log might be better to be moved to the reporter @@ -412,33 +412,33 @@ async function installInContext ( const rootPkgs = await resolveDependencies( installCtx, nonLinkedPkgs, - installOpts + installOpts, ) stageLogger.debug('resolution_done') - installCtx.nodesToBuild.forEach(nodeToBuild => { + installCtx.nodesToBuild.forEach((nodeToBuild) => { installCtx.tree[nodeToBuild.nodeId] = { - pkg: nodeToBuild.pkg, children: () => buildTree(installCtx, nodeToBuild.nodeId, nodeToBuild.pkg.id, installCtx.childrenByParentId[nodeToBuild.pkg.id], nodeToBuild.depth + 1, nodeToBuild.installable), depth: nodeToBuild.depth, installable: nodeToBuild.installable, + pkg: nodeToBuild.pkg, } }) const rootNodeIdsByAlias = rootPkgs - .reduce((rootNodeIdsByAlias, rootPkg) => { + .reduce((acc, rootPkg) => { const pkg = installCtx.tree[rootPkg.nodeId].pkg const specRaw = pkg.specRaw - const spec = R.find(spec => spec.raw === specRaw, packagesToInstall) - rootNodeIdsByAlias[rootPkg.alias] = rootPkg.nodeId - return rootNodeIdsByAlias + const spec = R.find((sp) => sp.raw === specRaw, packagesToInstall) + acc[rootPkg.alias] = rootPkg.nodeId + return acc }, {}) const pkgsToSave = ( rootPkgs - .map(rootPkg => ({ + .map((rootPkg) => ({ ...installCtx.tree[rootPkg.nodeId].pkg, alias: rootPkg.alias, normalizedPref: rootPkg.normalizedPref, - })) as { + })) as Array<{ alias: string, optional: boolean, dev: boolean, @@ -448,7 +448,7 @@ async function installInContext ( name: string, specRaw: string, normalizedPref?: string, - }[]) + }>) .concat(installCtx.localPackages) let newPkg: PackageJson | undefined = ctx.pkg @@ -461,16 +461,16 @@ async function installInContext ( newPkg = await save( pkgJsonPath, pkgsToSave // tslint:disable-line - .map(dep => { + .map((dep) => { return { name: dep.alias, pref: dep.normalizedPref || getPref(dep.alias, dep.name, dep.version, { saveExact: opts.saveExact, savePrefix: opts.savePrefix, - }) + }), } }), - saveType + saveType, ) } else { packageJsonLogger.debug({ updated: ctx.pkg }) @@ -485,7 +485,7 @@ async function installInContext ( const devDeps = newPkg.devDependencies || {} const optionalDeps = newPkg.optionalDependencies || {} - linkedPkgs.forEach(linkedPkg => { + linkedPkgs.forEach((linkedPkg) => { ctx.wantedShrinkwrap.specifiers[linkedPkg.alias] = getSpecFromPackageJson(newPkg as PackageJson, linkedPkg.alias) as string }) @@ -522,46 +522,46 @@ async function installInContext ( ? await getTopParents( R.difference( R.keys(depsFromPackage(ctx.pkg)), - newPkgRawSpecs && pkgsToSave.filter(pkgToSave => newPkgRawSpecs.indexOf(pkgToSave.specRaw) !== -1).map(pkg => pkg.alias) || [] + newPkgRawSpecs && pkgsToSave.filter((pkgToSave) => newPkgRawSpecs.indexOf(pkgToSave.specRaw) !== -1).map((pkg) => pkg.alias) || [], ), - nodeModulesPath + nodeModulesPath, ) : [] const result = await linkPackages(rootNodeIdsByAlias, installCtx.tree, { + baseNodeModules: nodeModulesPath, + bin: opts.bin, + currentShrinkwrap: ctx.currentShrinkwrap, + development: opts.development, dryRun: opts.shrinkwrapOnly, force: opts.force, global: opts.global, - baseNodeModules: nodeModulesPath, - bin: opts.bin, - topParents, - wantedShrinkwrap: ctx.wantedShrinkwrap, - production: opts.production, - development: opts.development, - optional: opts.optional, - root: ctx.root, - currentShrinkwrap: ctx.currentShrinkwrap, - skipped: ctx.skipped, - pkg: newPkg || ctx.pkg, - independentLeaves: opts.independentLeaves, - storeController: opts.storeController, - makePartialCurrentShrinkwrap, - updateShrinkwrapMinorVersion: installType === 'general' || R.isEmpty(ctx.currentShrinkwrap.packages), - outdatedPkgs: installCtx.outdatedPkgs, - sideEffectsCache: opts.sideEffectsCache, - shamefullyFlatten: opts.shamefullyFlatten, - reinstallForFlatten: Boolean(opts.reinstallForFlatten), hoistedAliases: ctx.hoistedAliases, + independentLeaves: opts.independentLeaves, + makePartialCurrentShrinkwrap, + optional: opts.optional, + outdatedPkgs: installCtx.outdatedPkgs, + pkg: newPkg || ctx.pkg, + production: opts.production, + reinstallForFlatten: Boolean(opts.reinstallForFlatten), + root: ctx.root, + shamefullyFlatten: opts.shamefullyFlatten, + sideEffectsCache: opts.sideEffectsCache, + skipped: ctx.skipped, + storeController: opts.storeController, + topParents, + updateShrinkwrapMinorVersion: installType === 'general' || R.isEmpty(ctx.currentShrinkwrap.packages), + wantedShrinkwrap: ctx.wantedShrinkwrap, }) ctx.hoistedAliases = result.hoistedAliases ctx.pendingBuilds = ctx.pendingBuilds - .filter(pkgId => !result.removedPkgIds.has(dp.resolve(ctx.wantedShrinkwrap.registry, pkgId))) + .filter((pkgId) => !result.removedPkgIds.has(dp.resolve(ctx.wantedShrinkwrap.registry, pkgId))) if (opts.ignoreScripts) { // we can use concat here because we always only append new packages, which are guaranteed to not be there by definition ctx.pendingBuilds = ctx.pendingBuilds - .concat(result.newDepPaths.map(depPath => dp.relative(ctx.wantedShrinkwrap.registry, depPath))) + .concat(result.newDepPaths.map((depPath) => dp.relative(ctx.wantedShrinkwrap.registry, depPath))) } if (opts.shrinkwrapOnly) { @@ -574,14 +574,14 @@ async function installInContext ( result.currentShrinkwrap.packages === undefined && result.removedPkgIds.size === 0 ? Promise.resolve() : saveModules(path.join(ctx.root, 'node_modules'), { - packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, - store: ctx.storePath, - skipped: Array.from(installCtx.skipped), - layoutVersion: LAYOUT_VERSION, + hoistedAliases: ctx.hoistedAliases, independentLeaves: opts.independentLeaves, + layoutVersion: LAYOUT_VERSION, + packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, pendingBuilds: ctx.pendingBuilds, shamefullyFlatten: opts.shamefullyFlatten, - hoistedAliases: ctx.hoistedAliases, + skipped: Array.from(installCtx.skipped), + store: ctx.storePath, }), ]) @@ -590,15 +590,15 @@ async function installInContext ( const limitChild = pLimit(opts.childConcurrency) await Promise.all( R.props(result.newDepPaths, result.linkedPkgsMap) - .filter(pkg => !pkg.isBuilt) - .map(pkg => limitChild(async () => { + .filter((pkg) => !pkg.isBuilt) + .map((pkg) => limitChild(async () => { try { const hasSideEffects = await postInstall(pkg.peripheralLocation, { - rawNpmConfig: installCtx.rawNpmConfig, initialWD: ctx.root, - userAgent: opts.userAgent, pkgId: pkg.id, + rawNpmConfig: installCtx.rawNpmConfig, unsafePerm: opts.unsafePerm || false, + userAgent: opts.userAgent, }) if (hasSideEffects && opts.sideEffectsCache && !opts.sideEffectsCacheReadonly) { try { @@ -611,8 +611,8 @@ async function installInContext ( logger.warn(`The store server disabled upload requests, could not upload ${pkg.id}`) } else { logger.warn({ - message: `An error occurred while uploading ${pkg.id}`, err, + message: `An error occurred while uploading ${pkg.id}`, }) } } @@ -620,30 +620,30 @@ async function installInContext ( } catch (err) { if (installCtx.installs[pkg.id].optional) { logger.warn({ - message: `Skipping failed optional dependency ${pkg.id}`, err, + message: `Skipping failed optional dependency ${pkg.id}`, }) return } throw err } - }) - ) + }), + ), ) } if (installCtx.localPackages.length) { const linkOpts = { ...opts, - skipInstall: true, linkToBin: opts.bin, + skipInstall: true, } - const externalPkgs = installCtx.localPackages.map(localPackage => localPackage.resolution.directory) + const externalPkgs = installCtx.localPackages.map((localPackage) => localPackage.resolution.directory) await externalLink(externalPkgs, installCtx.nodeModules, linkOpts) - installCtx.localPackages.forEach(async localPackage => { + installCtx.localPackages.forEach(async (localPackage) => { logStatus({ - status: 'installed', pkgId: localPackage.id, + status: 'installed', }) }) } @@ -655,11 +655,11 @@ async function installInContext ( // skipped packages might have not been reanalized on a repeat install // so lets just ignore those by excluding nulls .filter(Boolean) - .map(pkg => pkg.fetchingFiles) + .map((pkg) => pkg.fetchingFiles), ) // waiting till package requests are finished - await Promise.all(R.values(installCtx.installs).map(installed => installed.finishing)) + await Promise.all(R.values(installCtx.installs).map((installed) => installed.finishing)) summaryLogger.info(undefined) @@ -670,9 +670,9 @@ function buildTree ( ctx: InstallContext, parentNodeId: string, parentId: string, - children: {alias: string, pkgId: string}[], + children: Array<{alias: string, pkgId: string}>, depth: number, - installable: boolean + installable: boolean, ) { const childrenNodeIds = {} for (const child of children) { @@ -683,10 +683,10 @@ function buildTree ( childrenNodeIds[child.alias] = childNodeId installable = installable && !ctx.skipped.has(child.pkgId) ctx.tree[childNodeId] = { - pkg: ctx.installs[child.pkgId], children: () => buildTree(ctx, childNodeId, child.pkgId, ctx.childrenByParentId[child.pkgId], depth + 1, installable), depth, installable, + pkg: ctx.installs[child.pkgId], } } return childrenNodeIds @@ -694,7 +694,7 @@ function buildTree ( async function getTopParents (pkgNames: string[], modules: string) { const pkgs = await Promise.all( - pkgNames.map(pkgName => path.join(modules, pkgName)).map(safeReadPkgFromDir) + pkgNames.map((pkgName) => path.join(modules, pkgName)).map(safeReadPkgFromDir), ) return pkgs.filter(Boolean).map((pkg: PackageJson) => ({ name: pkg.name, @@ -709,9 +709,9 @@ function getPref ( opts: { saveExact: boolean, savePrefix: string, - } + }, ) { - let prefix = alias !== name ? `npm:${name}@` : '' + const prefix = alias !== name ? `npm:${name}@` : '' if (opts.saveExact) return `${prefix}${version}` return `${prefix}${opts.savePrefix}${version}` } diff --git a/src/api/link.ts b/src/api/link.ts index e1f2613787..95a9f0af50 100644 --- a/src/api/link.ts +++ b/src/api/link.ts @@ -1,30 +1,30 @@ -import path = require('path') -import loadJsonFile = require('load-json-file') -import symlinkDir = require('symlink-dir') import logger, {streamParser} from '@pnpm/logger' import {PackageJson} from '@pnpm/types' -import {install} from './install' -import pathAbsolute = require('path-absolute') +import loadJsonFile = require('load-json-file') import normalize = require('normalize-path') -import R = require('ramda') -import {linkPkgBins} from '../link/linkBins' -import extendOptions, { - InstallOptions, -} from './extendInstallOptions' -import readShrinkwrapFile from '../readShrinkwrapFiles' -import removeOrphanPkgs from './removeOrphanPkgs' import pLimit = require('p-limit') +import path = require('path') +import pathAbsolute = require('path-absolute') import { - Shrinkwrap, prune as pruneShrinkwrap, + Shrinkwrap, write as saveShrinkwrap, writeCurrentOnly as saveCurrentShrinkwrapOnly, } from 'pnpm-shrinkwrap' -import safeReadPackage from '../fs/safeReadPkg' -import getSpecFromPackageJson from '../getSpecFromPackageJson' +import R = require('ramda') +import symlinkDir = require('symlink-dir') import { read as readModules, } from '../fs/modulesController' +import safeReadPackage from '../fs/safeReadPkg' +import getSpecFromPackageJson from '../getSpecFromPackageJson' +import {linkPkgBins} from '../link/linkBins' +import readShrinkwrapFile from '../readShrinkwrapFiles' +import extendOptions, { + InstallOptions, +} from './extendInstallOptions' +import {install} from './install' +import removeOrphanPkgs from './removeOrphanPkgs' const linkLogger = logger('link') const installLimit = pLimit(4) @@ -35,7 +35,7 @@ export default async function link ( maybeOpts: InstallOptions & { skipInstall?: boolean, linkToBin?: string, - } + }, ) { const reporter = maybeOpts && maybeOpts.reporter if (reporter) { @@ -45,33 +45,33 @@ export default async function link ( if (!maybeOpts || !maybeOpts.skipInstall) { await Promise.all( - linkFromPkgs.map(prefix => installLimit(() => + linkFromPkgs.map((prefix) => installLimit(() => install({ ...opts, - prefix, bin: path.join(prefix, 'node_modules', '.bin'), global: false, - }) - )) + prefix, + }), + )), ) } const shrFiles = await readShrinkwrapFile({ - prefix: opts.prefix, - shrinkwrap: opts.shrinkwrap, force: opts.force, + prefix: opts.prefix, registry: opts.registry, + shrinkwrap: opts.shrinkwrap, }) const oldShrinkwrap = R.clone(shrFiles.currentShrinkwrap) const pkg = await safeReadPackage(path.join(opts.prefix, 'package.json')) || undefined - const linkedPkgs: {path: string, pkg: PackageJson}[] = [] + const linkedPkgs: Array<{path: string, pkg: PackageJson}> = [] for (const linkFrom of linkFromPkgs) { const linkedPkg = await loadJsonFile(path.join(linkFrom, 'package.json')) const packagePath = normalize(path.relative(opts.prefix, linkFrom)) const addLinkOpts = { - packagePath, linkedPkgName: linkedPkg.name, + packagePath, pkg, } addLinkToShrinkwrap(shrFiles.currentShrinkwrap, addLinkOpts) @@ -84,13 +84,13 @@ export default async function link ( const updatedWantedShrinkwrap = pruneShrinkwrap(shrFiles.wantedShrinkwrap) const modulesInfo = await readModules(destModules) await removeOrphanPkgs({ - oldShrinkwrap, - newShrinkwrap: updatedCurrentShrinkwrap, bin: opts.bin, + hoistedAliases: modulesInfo && modulesInfo.hoistedAliases || {}, + newShrinkwrap: updatedCurrentShrinkwrap, + oldShrinkwrap, prefix: opts.prefix, shamefullyFlatten: opts.shamefullyFlatten, storeController: opts.storeController, - hoistedAliases: modulesInfo && modulesInfo.hoistedAliases || {}, }) // Linking should happen after removing orphans @@ -116,8 +116,8 @@ export default async function link ( function addLinkToShrinkwrap ( shr: Shrinkwrap, opts: { - packagePath: string, linkedPkgName: string, + packagePath: string, pkg?: PackageJson, }, ) { @@ -156,7 +156,7 @@ async function linkToModules (pkgName: string, linkFrom: string, modules: string export async function linkFromGlobal ( pkgNames: string[], linkTo: string, - maybeOpts: InstallOptions & {globalPrefix: string} + maybeOpts: InstallOptions & {globalPrefix: string}, ) { const reporter = maybeOpts && maybeOpts.reporter if (reporter) { @@ -164,7 +164,7 @@ export async function linkFromGlobal ( } const opts = await extendOptions(maybeOpts) const globalPkgPath = pathAbsolute(maybeOpts.globalPrefix) - const linkFromPkgs = pkgNames.map(pkgName => path.join(globalPkgPath, 'node_modules', pkgName)) + const linkFromPkgs = pkgNames.map((pkgName) => path.join(globalPkgPath, 'node_modules', pkgName)) await link(linkFromPkgs, path.join(linkTo, 'node_modules'), opts) if (reporter) { @@ -175,9 +175,9 @@ export async function linkFromGlobal ( export async function linkToGlobal ( linkFrom: string, maybeOpts: InstallOptions & { - globalPrefix: string, globalBin: string, - } + globalPrefix: string, + }, ) { const reporter = maybeOpts && maybeOpts.reporter if (reporter) { diff --git a/src/api/lock.ts b/src/api/lock.ts index b449565925..f23f4e316d 100644 --- a/src/api/lock.ts +++ b/src/api/lock.ts @@ -1,5 +1,5 @@ -import logger from '@pnpm/logger' import lock from '@pnpm/fs-locker' +import logger from '@pnpm/logger' export default async function withLock ( dir: string, @@ -7,14 +7,14 @@ export default async function withLock ( opts: { stale: number, locks: string, - } + }, ): Promise { const unlock = await lock(dir, { - stale: opts.stale, locks: opts.locks, + stale: opts.stale, whenLocked () { logger.warn('waiting for another installation to complete...') - } + }, }) try { const result = await fn() diff --git a/src/api/prune.ts b/src/api/prune.ts index 0ff1e34eff..a6d3761854 100644 --- a/src/api/prune.ts +++ b/src/api/prune.ts @@ -1,14 +1,14 @@ +import {streamParser} from '@pnpm/logger' import {PackageJson} from '@pnpm/types' -import getContext from './getContext' -import extendOptions, { - PruneOptions, -} from './extendPruneOptions' -import removeOrphanPkgs from './removeOrphanPkgs' import { prune as pruneShrinkwrap, } from 'pnpm-shrinkwrap' -import {streamParser} from '@pnpm/logger' +import extendOptions, { + PruneOptions, +} from './extendPruneOptions' +import getContext from './getContext' import {installPkgs} from './install' +import removeOrphanPkgs from './removeOrphanPkgs' export async function prune ( maybeOpts: PruneOptions, @@ -35,14 +35,14 @@ export async function prune ( const prunedShr = pruneShrinkwrap(ctx.wantedShrinkwrap, pkg) await removeOrphanPkgs({ - oldShrinkwrap: ctx.currentShrinkwrap, - newShrinkwrap: prunedShr, - prefix: ctx.root, - shamefullyFlatten: opts.shamefullyFlatten, - storeController: opts.storeController, - pruneStore: true, bin: opts.bin, hoistedAliases: ctx.hoistedAliases, + newShrinkwrap: prunedShr, + oldShrinkwrap: ctx.currentShrinkwrap, + prefix: ctx.root, + pruneStore: true, + shamefullyFlatten: opts.shamefullyFlatten, + storeController: opts.storeController, }) if (opts.shamefullyFlatten) { diff --git a/src/api/rebuild.ts b/src/api/rebuild.ts index e6d732a5c0..ab3d2a7069 100644 --- a/src/api/rebuild.ts +++ b/src/api/rebuild.ts @@ -1,25 +1,25 @@ +import logger, {streamParser} from '@pnpm/logger' +import npa = require('@zkochan/npm-package-arg') +import * as dp from 'dependency-path' +import pSeries = require('p-series') +import path = require('path') +import { + DependencyShrinkwrap, + ResolvedPackages, +} from 'pnpm-shrinkwrap' +import R = require('ramda') +import semver = require('semver') +import {LAYOUT_VERSION, save as saveModules} from '../fs/modulesController'; +import realNodeModulesDir from '../fs/realNodeModulesDir'; +import getPkgInfoFromShr from '../getPkgInfoFromShr' +import postInstall from '../install/postInstall' import extendOptions, { RebuildOptions, StrictRebuildOptions, } from './extendRebuildOptions' import getContext from './getContext' -import logger, {streamParser} from '@pnpm/logger' -import R = require('ramda') -import * as dp from 'dependency-path' -import postInstall from '../install/postInstall' -import path = require('path') -import pSeries = require('p-series') -import { - ResolvedPackages, - DependencyShrinkwrap, -} from 'pnpm-shrinkwrap' -import npa = require('@zkochan/npm-package-arg') -import semver = require('semver') -import getPkgInfoFromShr from '../getPkgInfoFromShr' -import {save as saveModules, LAYOUT_VERSION} from '../fs/modulesController'; -import realNodeModulesDir from '../fs/realNodeModulesDir'; -type PackageToRebuild = { +interface PackageToRebuild { relativeDepPath: string, name: string, version?: string, @@ -28,17 +28,17 @@ type PackageToRebuild = { function getPackagesInfo (packages: ResolvedPackages, idsToRebuild: string[]): PackageToRebuild[] { return idsToRebuild - .map(relativeDepPath => { + .map((relativeDepPath) => { const pkgShr = packages[relativeDepPath] const pkgInfo = getPkgInfoFromShr(relativeDepPath, pkgShr) return { - relativeDepPath, - name: pkgInfo['name'], - version: pkgInfo['version'], + name: pkgInfo.name, pkgShr, + relativeDepPath, + version: pkgInfo.version, } }) - .filter(pkgInfo => { + .filter((pkgInfo) => { if (!pkgInfo.name) { logger.warn(`Skipping ${pkgInfo.relativeDepPath} because cannot get the package name from shrinkwrap.yaml. Try to run run \`pnpm update --depth 100\` to create a new shrinkwrap.yaml with all the necessary info.`) @@ -68,7 +68,7 @@ export async function rebuildPkgs ( if (!ctx.currentShrinkwrap || !ctx.currentShrinkwrap.packages) return const packages = ctx.currentShrinkwrap.packages - const searched: PackageSelector[] = pkgSpecs.map(arg => { + const searched: PackageSelector[] = pkgSpecs.map((arg) => { const parsed = npa(arg) if (parsed.raw === parsed.name) { return parsed.name @@ -83,7 +83,7 @@ export async function rebuildPkgs ( }) const pkgs = getPackagesInfo(packages, R.keys(packages)) - .filter(pkg => matches(searched, pkg)) + .filter((pkg) => matches(searched, pkg)) await _rebuild(pkgs, modules, ctx.currentShrinkwrap.registry, opts) } @@ -91,9 +91,9 @@ export async function rebuildPkgs ( // TODO: move this logic to separate package as this is also used in dependencies-hierarchy function matches ( searched: PackageSelector[], - pkg: {name: string, version?: string} + pkg: {name: string, version?: string}, ) { - return searched.some(searchedPkg => { + return searched.some((searchedPkg) => { if (typeof searchedPkg === 'string') { return pkg.name === searchedPkg } @@ -126,14 +126,14 @@ export async function rebuild (maybeOpts: RebuildOptions) { await _rebuild(pkgs, modules, ctx.currentShrinkwrap.registry, opts) await saveModules(path.join(ctx.root, 'node_modules'), { - packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, - store: ctx.storePath, - skipped: Array.from(ctx.skipped), - layoutVersion: LAYOUT_VERSION, + hoistedAliases: ctx.hoistedAliases, independentLeaves: opts.independentLeaves, + layoutVersion: LAYOUT_VERSION, + packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, pendingBuilds: [], shamefullyFlatten: opts.shamefullyFlatten, - hoistedAliases: ctx.hoistedAliases, + skipped: Array.from(ctx.skipped), + store: ctx.storePath, }) } @@ -145,27 +145,27 @@ async function _rebuild ( ) { await pSeries( pkgs - .map(pkgToRebuild => async () => { + .map((pkgToRebuild) => async () => { const depAbsolutePath = dp.resolve(registry, pkgToRebuild.relativeDepPath) const pkgId = pkgToRebuild.pkgShr.id || depAbsolutePath try { await postInstall(path.join(modules, `.${depAbsolutePath}`, 'node_modules', pkgToRebuild.name), { - rawNpmConfig: opts.rawNpmConfig, initialWD: opts.prefix, - userAgent: opts.userAgent, pkgId, + rawNpmConfig: opts.rawNpmConfig, unsafePerm: opts.unsafePerm || false, + userAgent: opts.userAgent, }) } catch (err) { if (pkgToRebuild.pkgShr.optional) { logger.warn({ - message: `Skipping failed optional dependency ${pkgId}`, err, + message: `Skipping failed optional dependency ${pkgId}`, }) return } throw err } - }) + }), ) } diff --git a/src/api/removeOrphanPkgs.ts b/src/api/removeOrphanPkgs.ts index bb16fd9128..5622e39e37 100644 --- a/src/api/removeOrphanPkgs.ts +++ b/src/api/removeOrphanPkgs.ts @@ -1,41 +1,41 @@ -import rimraf = require('rimraf-then') -import path = require('path') import * as dp from 'dependency-path' -import {Shrinkwrap, ResolvedPackages} from 'pnpm-shrinkwrap' import {StoreController} from 'package-store' +import path = require('path') +import {ResolvedPackages, Shrinkwrap} from 'pnpm-shrinkwrap' import R = require('ramda') -import removeTopDependency from '../removeTopDependency' +import rimraf = require('rimraf-then') import {dependenciesTypes} from '../getSaveType' import {statsLogger} from '../loggers' +import removeTopDependency from '../removeTopDependency' export default async function removeOrphanPkgs ( opts: { - dryRun?: boolean, - oldShrinkwrap: Shrinkwrap, - newShrinkwrap: Shrinkwrap, bin: string, + dryRun?: boolean, + hoistedAliases: {[pkgId: string]: string[]}, + newShrinkwrap: Shrinkwrap, + oldShrinkwrap: Shrinkwrap, prefix: string, + pruneStore?: boolean, shamefullyFlatten: boolean, storeController: StoreController, - pruneStore?: boolean, - hoistedAliases: {[pkgId: string]: string[]}, - } + }, ): Promise> { - const oldPkgs = R.toPairs(R.mergeAll(R.map(depType => opts.oldShrinkwrap[depType], dependenciesTypes))) - const newPkgs = R.toPairs(R.mergeAll(R.map(depType => opts.newShrinkwrap[depType], dependenciesTypes))) + const oldPkgs = R.toPairs(R.mergeAll(R.map((depType) => opts.oldShrinkwrap[depType], dependenciesTypes))) + const newPkgs = R.toPairs(R.mergeAll(R.map((depType) => opts.newShrinkwrap[depType], dependenciesTypes))) - const removedTopDeps: [string, string][] = R.difference(oldPkgs, newPkgs) as [string, string][] + const removedTopDeps: Array<[string, string]> = R.difference(oldPkgs, newPkgs) as Array<[string, string]> const rootModules = path.join(opts.prefix, 'node_modules') - await Promise.all(removedTopDeps.map(depName => { + await Promise.all(removedTopDeps.map((depName) => { return removeTopDependency({ - name: depName[0], dev: Boolean(opts.oldShrinkwrap.devDependencies && opts.oldShrinkwrap.devDependencies[depName[0]]), + name: depName[0], optional: Boolean(opts.oldShrinkwrap.optionalDependencies && opts.oldShrinkwrap.optionalDependencies[depName[0]]), }, { + bin: opts.bin, dryRun: opts.dryRun, modules: rootModules, - bin: opts.bin, }) })) @@ -50,17 +50,17 @@ export default async function removeOrphanPkgs ( if (notDependents.length) { if (opts.shamefullyFlatten && opts.oldShrinkwrap.packages) { - await Promise.all(notDependents.map(async notDependent => { + await Promise.all(notDependents.map(async (notDependent) => { if (opts.hoistedAliases[notDependent]) { - await Promise.all(opts.hoistedAliases[notDependent].map(async alias => { + await Promise.all(opts.hoistedAliases[notDependent].map(async (alias) => { await removeTopDependency({ - name: alias, dev: false, + name: alias, optional: false, }, { - modules: rootModules, bin: opts.bin, - muteLogs: true + modules: rootModules, + muteLogs: true, }) })) } @@ -68,7 +68,7 @@ export default async function removeOrphanPkgs ( })) } - await Promise.all(notDependents.map(async notDependent => { + await Promise.all(notDependents.map(async (notDependent) => { await rimraf(path.join(rootModules, `.${notDependent}`)) })) } @@ -76,9 +76,9 @@ export default async function removeOrphanPkgs ( const newDependents = R.difference(newPkgIds, oldPkgIds) await opts.storeController.updateConnections(opts.prefix, { + addDependencies: newDependents, prune: opts.pruneStore || false, removeDependencies: notDependents, - addDependencies: newDependents, }) await opts.storeController.saveState() @@ -89,15 +89,15 @@ export default async function removeOrphanPkgs ( function getPackageIds ( registry: string, - packages: ResolvedPackages + packages: ResolvedPackages, ): string[] { return R.uniq( R.keys(packages) - .map(depPath => { + .map((depPath) => { if (packages[depPath].id) { return packages[depPath].id } return dp.resolve(registry, depPath) - }) + }), ) as string[] } diff --git a/src/api/shrinkwrapsEqual.ts b/src/api/shrinkwrapsEqual.ts index d3b495ae9f..e1968a7310 100644 --- a/src/api/shrinkwrapsEqual.ts +++ b/src/api/shrinkwrapsEqual.ts @@ -1,5 +1,5 @@ -import R = require('ramda') import {Shrinkwrap} from 'pnpm-shrinkwrap' +import R = require('ramda') export default function shrinkwrapsEqual (shr1: Shrinkwrap, shr2: Shrinkwrap) { const specs1 = R.keys(shr1.specifiers) diff --git a/src/api/storePrune.ts b/src/api/storePrune.ts index a61edde5b7..f7e81c9fd1 100644 --- a/src/api/storePrune.ts +++ b/src/api/storePrune.ts @@ -1,5 +1,5 @@ -import {StoreController} from 'package-store' import {streamParser} from '@pnpm/logger' +import {StoreController} from 'package-store' import {ReporterFunction} from '../types' export default async function ( diff --git a/src/api/storeStatus.ts b/src/api/storeStatus.ts index 2bd2cbdd52..62850da288 100644 --- a/src/api/storeStatus.ts +++ b/src/api/storeStatus.ts @@ -1,12 +1,12 @@ -import path = require('path') +import checkPackage from '@pnpm/check-package' +import {streamParser} from '@pnpm/logger' +import * as dp from 'dependency-path' import pFilter = require('p-filter') +import path = require('path') import extendOptions, { StoreStatusOptions, } from './extendStoreStatusOptions' import getContext from './getContext' -import checkPackage from '@pnpm/check-package' -import * as dp from 'dependency-path' -import {streamParser} from '@pnpm/logger' export default async function (maybeOpts: StoreStatusOptions) { const reporter = maybeOpts && maybeOpts.reporter @@ -18,11 +18,11 @@ export default async function (maybeOpts: StoreStatusOptions) { if (!ctx.wantedShrinkwrap) return [] const pkgPaths = Object.keys(ctx.wantedShrinkwrap.packages || {}) - .map(id => { + .map((id) => { if (id === '/') return null return dp.resolve(ctx.wantedShrinkwrap.registry, id) }) - .filter(pkgId => pkgId && !ctx.skipped.has(pkgId)) + .filter((pkgId) => pkgId && !ctx.skipped.has(pkgId)) .map((pkgPath: string) => path.join(ctx.storePath, pkgPath)) const modified = await pFilter(pkgPaths, async (pkgPath: string) => !await checkPackage(path.join(pkgPath, 'package'))) diff --git a/src/api/uninstall.ts b/src/api/uninstall.ts index 78f9c249f0..02611e9d61 100644 --- a/src/api/uninstall.ts +++ b/src/api/uninstall.ts @@ -1,29 +1,29 @@ -import path = require('path') +import logger, {streamParser} from '@pnpm/logger' import * as dp from 'dependency-path' -import R = require('ramda') -import getContext, {PnpmContext} from './getContext' -import getSaveType from '../getSaveType' -import removeDeps from '../removeDeps' -import extendOptions, { - UninstallOptions, - StrictUninstallOptions, -} from './extendUninstallOptions' -import lock from './lock' +import path = require('path') import { + prune as pruneShrinkwrap, write as saveShrinkwrap, writeCurrentOnly as saveCurrentShrinkwrapOnly, - prune as pruneShrinkwrap, } from 'pnpm-shrinkwrap' -import logger, {streamParser} from '@pnpm/logger' +import R = require('ramda') import { - save as saveModules, LAYOUT_VERSION, + save as saveModules, } from '../fs/modulesController' -import removeOrphanPkgs from './removeOrphanPkgs' -import safeIsInnerLink from '../safeIsInnerLink' +import getSaveType from '../getSaveType' +import removeDeps from '../removeDeps' import removeTopDependency from '../removeTopDependency' -import shrinkwrapsEqual from './shrinkwrapsEqual' +import safeIsInnerLink from '../safeIsInnerLink' +import extendOptions, { + StrictUninstallOptions, + UninstallOptions, +} from './extendUninstallOptions' +import getContext, {PnpmContext} from './getContext' import {installPkgs} from './install' +import lock from './lock' +import removeOrphanPkgs from './removeOrphanPkgs' +import shrinkwrapsEqual from './shrinkwrapsEqual' export default async function uninstall ( pkgsToUninstall: string[], @@ -69,15 +69,15 @@ export async function uninstallInContext ( const pkg = await removeDeps(pkgJsonPath, pkgsToUninstall, saveType) const newShr = pruneShrinkwrap(ctx.wantedShrinkwrap, pkg) const removedPkgIds = await removeOrphanPkgs({ - oldShrinkwrap: ctx.currentShrinkwrap, + bin: opts.bin, + hoistedAliases: ctx.hoistedAliases, newShrinkwrap: newShr, + oldShrinkwrap: ctx.currentShrinkwrap, prefix: ctx.root, shamefullyFlatten: opts.shamefullyFlatten, storeController: opts.storeController, - bin: opts.bin, - hoistedAliases: ctx.hoistedAliases, }) - ctx.pendingBuilds = ctx.pendingBuilds.filter(pkgId => !removedPkgIds.has(dp.resolve(newShr.registry, pkgId))) + ctx.pendingBuilds = ctx.pendingBuilds.filter((pkgId) => !removedPkgIds.has(dp.resolve(newShr.registry, pkgId))) await opts.storeController.close() const currentShrinkwrap = makePartialCurrentShrinkwrap ? pruneShrinkwrap(ctx.currentShrinkwrap, pkg) @@ -88,18 +88,18 @@ export async function uninstallInContext ( await saveCurrentShrinkwrapOnly(ctx.root, currentShrinkwrap) } await saveModules(path.join(ctx.root, 'node_modules'), { - packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, - store: ctx.storePath, - skipped: Array.from(ctx.skipped).filter(pkgId => !removedPkgIds.has(pkgId)), - layoutVersion: LAYOUT_VERSION, + hoistedAliases: ctx.hoistedAliases, independentLeaves: opts.independentLeaves, + layoutVersion: LAYOUT_VERSION, + packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`, pendingBuilds: ctx.pendingBuilds, shamefullyFlatten: opts.shamefullyFlatten, - hoistedAliases: ctx.hoistedAliases, + skipped: Array.from(ctx.skipped).filter((pkgId) => !removedPkgIds.has(pkgId)), + store: ctx.storePath, }) await removeOuterLinks(pkgsToUninstall, path.join(ctx.root, 'node_modules'), { - storePath: ctx.storePath, bin: opts.bin, + storePath: ctx.storePath, }) if (opts.shamefullyFlatten) { @@ -113,20 +113,20 @@ async function removeOuterLinks ( pkgsToUninstall: string[], modules: string, opts: { - storePath: string, bin: string, - } + storePath: string, + }, ) { // These packages are not in package.json, they were just linked in not installed for (const pkgToUninstall of pkgsToUninstall) { if (await safeIsInnerLink(modules, pkgToUninstall, opts) !== true) { await removeTopDependency({ - name: pkgToUninstall, dev: false, + name: pkgToUninstall, optional: false, }, { - modules, bin: opts.bin, + modules, }) } } diff --git a/src/api/unlink.ts b/src/api/unlink.ts index bb8cf886fa..48be7b8eef 100644 --- a/src/api/unlink.ts +++ b/src/api/unlink.ts @@ -1,24 +1,24 @@ +import logger, {streamParser} from '@pnpm/logger' +import isInnerLink = require('is-inner-link') +import isSubdir = require('is-subdir') +import fs = require('mz/fs') import path = require('path') +import rimraf = require('rimraf-then') +import depsFromPackage from '../depsFromPackage' +import { + read as readModules, +} from '../fs/modulesController' +import {fromDir as readPkgFromDir} from '../fs/readPkg' +import realNodeModulesDir from '../fs/realNodeModulesDir' import extendOptions, { InstallOptions, StrictInstallOptions, } from './extendInstallOptions' -import isInnerLink = require('is-inner-link') -import logger, {streamParser} from '@pnpm/logger' -import rimraf = require('rimraf-then') import {install} from './install' -import {fromDir as readPkgFromDir} from '../fs/readPkg' -import depsFromPackage from '../depsFromPackage' -import fs = require('mz/fs') -import { - read as readModules, -} from '../fs/modulesController' -import isSubdir = require('is-subdir') -import realNodeModulesDir from '../fs/realNodeModulesDir' export async function unlinkPkgs ( pkgNames: string[], - maybeOpts: InstallOptions + maybeOpts: InstallOptions, ) { const reporter = maybeOpts && maybeOpts.reporter if (reporter) { @@ -37,7 +37,7 @@ export async function unlinkPkgs ( export async function _unlinkPkgs ( pkgNames: string[], - opts: StrictInstallOptions + opts: StrictInstallOptions, ) { const modules = await realNodeModulesDir(opts.prefix) const pkg = await readPkgFromDir(opts.prefix) @@ -85,7 +85,7 @@ export async function unlink (maybeOpts: InstallOptions) { async function getExternalPackages ( modules: string, store: string, - scope?: string + scope?: string, ): Promise { let externalLinks: string[] = [] const parentDir = scope ? path.join(modules, scope) : modules diff --git a/src/binify.ts b/src/binify.ts index 063f864d42..3c8975e3b8 100644 --- a/src/binify.ts +++ b/src/binify.ts @@ -1,10 +1,10 @@ -import {PackageJson, PackageBin} from '@pnpm/types' -import path = require('path') +import {PackageBin, PackageJson} from '@pnpm/types' import {Stats} from 'fs' import fs = require('mz/fs') import pFilter = require('p-filter') +import path = require('path') -export type Command = { +export interface Command { name: string, path: string, } @@ -28,11 +28,11 @@ export default async function binify (pkg: PackageJson, pkgPath: string): Promis const binDir = path.join(pkgPath, pkg.directories.bin) const files = await findFiles(binDir) return pFilter( - files.map(file => ({ + files.map((file) => ({ name: file, - path: path.join(binDir, file) + path: path.join(binDir, file), })), - async (cmd: Command) => (await fs.stat(cmd.path)).isFile() + async (cmd: Command) => (await fs.stat(cmd.path)).isFile(), ) } return [] @@ -42,7 +42,7 @@ async function findFiles (dir: string): Promise { try { return await fs.readdir(dir) } catch (err) { - if ((err).code !== 'ENOENT') { + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err } return [] @@ -59,8 +59,8 @@ function commandsFromBin (bin: PackageBin, pkgName: string, pkgPath: string) { ] } return Object.keys(bin) - .map(commandName => ({ + .map((commandName) => ({ name: commandName, - path: path.join(pkgPath, bin[commandName]) + path: path.join(pkgPath, bin[commandName]), })) } diff --git a/src/depsFromPackage.ts b/src/depsFromPackage.ts index a12ddc805c..02058f670b 100644 --- a/src/depsFromPackage.ts +++ b/src/depsFromPackage.ts @@ -1,18 +1,18 @@ -import {PackageJson, Dependencies} from '@pnpm/types' +import {Dependencies, PackageJson} from '@pnpm/types' import getVerSelType = require('version-selector-type') export default function depsFromPackage (pkg: PackageJson): Dependencies { return { ...pkg.devDependencies, ...pkg.dependencies, - ...pkg.optionalDependencies + ...pkg.optionalDependencies, } as Dependencies } export function getPreferredVersionsFromPackage (pkg: PackageJson): { [packageName: string]: { - type: 'version' | 'range' | 'tag', selector: string, + type: 'version' | 'range' | 'tag', }, } { return getVersionSpecsByRealNames(depsFromPackage(pkg)) @@ -28,16 +28,16 @@ function getVersionSpecsByRealNames (deps: Dependencies) { const selector = getVerSelType(spec) if (selector) { acc[pref.substr(0, index)] = { - type: selector.type, selector: selector.normalized, + type: selector.type, } } } else if (deps[depName].indexOf(':') === -1) { // we really care only about semver specs const selector = getVerSelType(deps[depName]) if (selector) { acc[depName] = { - type: selector.type, selector: selector.normalized, + type: selector.type, } } } diff --git a/src/depsToSpecs.ts b/src/depsToSpecs.ts index 9b39280c7a..1f8475af1a 100644 --- a/src/depsToSpecs.ts +++ b/src/depsToSpecs.ts @@ -4,16 +4,16 @@ import {WantedDependency} from './types' export default function ( deps: Dependencies, opts: { - optionalDependencies: Dependencies, devDependencies: Dependencies, - } + optionalDependencies: Dependencies, + }, ): WantedDependency[] { if (!deps) return [] - return Object.keys(deps).map(alias => ({ + return Object.keys(deps).map((alias) => ({ alias, - pref: deps[alias], dev: !!opts.devDependencies[alias], optional: !!opts.optionalDependencies[alias], + pref: deps[alias], raw: `${alias}@${deps[alias]}`, })) } @@ -21,19 +21,19 @@ export default function ( export function similarDepsToSpecs ( deps: Dependencies, opts: { + currentPrefs: Dependencies, dev: boolean, + devDependencies: Dependencies, optional: boolean, optionalDependencies: Dependencies, - devDependencies: Dependencies, - currentPrefs: Dependencies, - } + }, ): WantedDependency[] { if (!deps) return [] - return Object.keys(deps).map(alias => ({ + return Object.keys(deps).map((alias) => ({ alias, - pref: deps[alias] || opts.currentPrefs[alias], dev: opts.dev || !!opts.devDependencies[alias], optional: opts.optional || !!opts.optionalDependencies[alias], + pref: deps[alias] || opts.currentPrefs[alias], raw: `${alias}@${deps[alias]}`, })) } diff --git a/src/errorTypes.ts b/src/errorTypes.ts index 4102c9c167..9b0ff27de7 100644 --- a/src/errorTypes.ts +++ b/src/errorTypes.ts @@ -7,9 +7,9 @@ export type PnpmErrorCode = 'UNEXPECTED_STORE' | 'NO_OFFLINE_TARBALL' export class PnpmError extends Error { + public code: PnpmErrorCode constructor (code: PnpmErrorCode, message: string) { super(message) this.code = code } - code: PnpmErrorCode } diff --git a/src/fs/getPkgDirs.ts b/src/fs/getPkgDirs.ts index be096ea94c..cfe3da952b 100644 --- a/src/fs/getPkgDirs.ts +++ b/src/fs/getPkgDirs.ts @@ -1,15 +1,15 @@ -import fs = require('mz/fs') -import path = require('path') -import flatten = require('arr-flatten') -import pFilter = require('p-filter') import logger from '@pnpm/logger' +import flatten = require('arr-flatten') +import fs = require('mz/fs') +import pFilter = require('p-filter') +import path = require('path') export default async function (modules: string): Promise { const dirs = await getDirectories(modules) const subdirs = await Promise.all( dirs.map((dir: string): Promise => { return isScopedPkgsDir(dir) ? getDirectories(dir) : Promise.resolve([dir]) - }) + }), ) return flatten(subdirs) } @@ -19,15 +19,15 @@ async function getDirectories (srcPath: string): Promise { try { dirs = await fs.readdir(srcPath) } catch (err) { - if ((err).code !== 'ENOENT') { + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err } dirs = [] } return pFilter( dirs - .filter(relativePath => relativePath[0] !== '.') // ignore directories like .bin, .store, etc - .map(relativePath => path.join(srcPath, relativePath)), + .filter((relativePath) => relativePath[0] !== '.') // ignore directories like .bin, .store, etc + .map((relativePath) => path.join(srcPath, relativePath)), async (absolutePath: string) => { try { const stats = await fs.stat(absolutePath) @@ -37,7 +37,7 @@ async function getDirectories (srcPath: string): Promise { logger.warn(`Cannot find file at ${absolutePath} although it was listed by readdir`) return false } - } + }, ) } diff --git a/src/fs/modulesController.ts b/src/fs/modulesController.ts index 7459e5f619..fc42140600 100644 --- a/src/fs/modulesController.ts +++ b/src/fs/modulesController.ts @@ -1,5 +1,5 @@ -import path = require('path') import loadYamlFile = require('load-yaml-file') +import path = require('path') import writeYamlFile = require('write-yaml-file') // The dot prefix is needed because otherwise `npm shrinkwrap` @@ -8,7 +8,7 @@ const modulesFileName = '.modules.yaml' export const LAYOUT_VERSION = 1 -export type Modules = { +export interface Modules { packageManager: string, store: string, skipped: string[], @@ -24,13 +24,15 @@ export async function read (modulesPath: string): Promise { try { const m = await loadYamlFile(modulesYamlPath) // for backward compatibility + // tslint:disable:no-string-literal if (m['storePath']) { m.store = m['storePath'] delete m['storePath'] } + // tslint:enable:no-string-literal return m } catch (err) { - if ((err).code !== 'ENOENT') { + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err } return null diff --git a/src/fs/readPkg.ts b/src/fs/readPkg.ts index fe4e913eef..f8610ad5b9 100644 --- a/src/fs/readPkg.ts +++ b/src/fs/readPkg.ts @@ -1,5 +1,5 @@ -import path = require('path') import {PackageJson} from '@pnpm/types' +import path = require('path') import readPackageJsonCB = require('read-package-json') import promisify = require('util.promisify') diff --git a/src/fs/realNodeModulesDir.ts b/src/fs/realNodeModulesDir.ts index 948dff393c..673102ba2c 100644 --- a/src/fs/realNodeModulesDir.ts +++ b/src/fs/realNodeModulesDir.ts @@ -6,7 +6,7 @@ export default async function realNodeModulesDir (prefix: string): Promise { try { return await readPkg(pkgPath) } catch (err) { - if ((err).code !== 'ENOENT') throw err + if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err return null } } diff --git a/src/fs/shrinkwrap.ts b/src/fs/shrinkwrap.ts index 8251ed48d8..e3bdbd7603 100644 --- a/src/fs/shrinkwrap.ts +++ b/src/fs/shrinkwrap.ts @@ -8,7 +8,7 @@ export function absolutePathToRef ( realName: string, resolution: Resolution, standardRegistry: string, - } + }, ) { if (opts.resolution.type) return absolutePath diff --git a/src/getPkgInfoFromShr.ts b/src/getPkgInfoFromShr.ts index 50064a71ea..dd9fb8133c 100644 --- a/src/getPkgInfoFromShr.ts +++ b/src/getPkgInfoFromShr.ts @@ -3,13 +3,15 @@ import {DependencyShrinkwrap} from 'pnpm-shrinkwrap' export default function getPkgInfoFromShr ( relativeDepPath: string, - pkgShr: DependencyShrinkwrap + pkgShr: DependencyShrinkwrap, ) { if (!pkgShr.name) { const pkgInfo = dp.parse(relativeDepPath) return { + // tslint:disable:no-string-literal name: pkgInfo['name'], version: pkgInfo['version'], + // tslint:enable:no-string-literal } } return { diff --git a/src/index.ts b/src/index.ts index 88b730bba7..7fd63c25a6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,8 +20,8 @@ export {PruneOptions} from './api/extendPruneOptions' export {RebuildOptions} from './api/extendRebuildOptions' export {UninstallOptions} from './api/extendUninstallOptions' -import * as supiLogs from './loggers' import * as packageRequesterLogs from '@pnpm/package-requester' +import * as supiLogs from './loggers' export type ProgressLog = supiLogs.ProgressLog | packageRequesterLogs.ProgressLog export type Log = supiLogs.Log | packageRequesterLogs.Log diff --git a/src/install/getIsInstallable.ts b/src/install/getIsInstallable.ts index e760715383..143ed0c351 100644 --- a/src/install/getIsInstallable.ts +++ b/src/install/getIsInstallable.ts @@ -1,26 +1,26 @@ -import R = require('ramda') -import installChecks = require('pnpm-install-checks') import logger from '@pnpm/logger' import {PackageManifest} from '@pnpm/types' -import {installCheckLogger} from '../loggers' +import installChecks = require('pnpm-install-checks') +import R = require('ramda') import {InstalledPackages} from '../api/install' +import {installCheckLogger} from '../loggers' import {splitNodeId} from '../nodeIdUtils' export default async function getIsInstallable ( pkgId: string, pkg: PackageManifest, options: { - nodeId: string, - installs: InstalledPackages, - optional: boolean, engineStrict: boolean, + installs: InstalledPackages, + nodeId: string, nodeVersion: string, + optional: boolean, pnpmVersion: string, - } + }, ): Promise { const warn = await installChecks.checkPlatform(pkg) || await installChecks.checkEngine(pkg, { + nodeVersion: options.nodeVersion, pnpmVersion: options.pnpmVersion, - nodeVersion: options.nodeVersion }) if (!warn) return true @@ -48,6 +48,6 @@ function nodeIdToFriendlyPath ( ) { const pkgIds = splitNodeId(nodeId).slice(2, -2) return pkgIds - .map(pkgId => installs[pkgId].name) + .map((pkgId) => installs[pkgId].name) .join(' > ') } diff --git a/src/install/postInstall.ts b/src/install/postInstall.ts index 25776387e2..eeea8c1b25 100644 --- a/src/install/postInstall.ts +++ b/src/install/postInstall.ts @@ -1,90 +1,90 @@ -import path = require('path') -import fs = require('mz/fs') import {PackageJson} from '@pnpm/types' -import {fromDir as readPkgFromDir} from '../fs/readPkg' +import fs = require('mz/fs') import lifecycle = require('npm-lifecycle') +import path = require('path') +import {fromDir as readPkgFromDir} from '../fs/readPkg' import {lifecycleLogger} from '../loggers' -function noop () {} +function noop () {} // tslint:disable-line:no-empty export default async function postInstall ( root: string, opts: { - rawNpmConfig: Object, initialWD: string, - userAgent: string, pkgId: string, + rawNpmConfig: object, unsafePerm: boolean, - } + userAgent: string, + }, ): Promise { const pkg = await readPkgFromDir(root) const scripts = pkg && pkg.scripts || {} - if (!scripts['install']) { + if (!scripts['install']) { // tslint:disable-line:no-string-literal await checkBindingGyp(root, scripts) } const modulesDir = path.join(opts.initialWD, 'node_modules') const scriptsOpts = { - rawNpmConfig: opts.rawNpmConfig, - pkgId: opts.pkgId, - unsafePerm: opts.unsafePerm, modulesDir, + pkgId: opts.pkgId, + rawNpmConfig: opts.rawNpmConfig, root, + unsafePerm: opts.unsafePerm, } await npmRunScript('preinstall', pkg, scriptsOpts) await npmRunScript('install', pkg, scriptsOpts) await npmRunScript('postinstall', pkg, scriptsOpts) - return !!scripts['preinstall'] || !!scripts['install'] || !!scripts['postinstall'] + return !!scripts['preinstall'] || !!scripts['install'] || !!scripts['postinstall'] // tslint:disable-line:no-string-literal } export async function npmRunScript ( stage: string, pkg: PackageJson, opts: { - rawNpmConfig: Object, - pkgId: string, modulesDir: string, + pkgId: string, + rawNpmConfig: object, root: string, stdio?: string, - unsafePerm: boolean - } + unsafePerm: boolean, + }, ) { if (!pkg.scripts || !pkg.scripts[stage]) return return lifecycle(pkg, stage, opts.root, { - dir: opts.modulesDir, config: opts.rawNpmConfig, - stdio: opts.stdio || 'pipe', + dir: opts.modulesDir, log: { - level: opts.stdio === 'inherit' ? undefined : 'silent', + clearProgress: noop, info: noop, - warn: noop, - silly: npmLog, - verbose: npmLog, + level: opts.stdio === 'inherit' ? undefined : 'silent', pause: noop, resume: noop, - clearProgress: noop, showProgress: noop, + silly: npmLog, + verbose: npmLog, + warn: noop, }, - unsafePerm: opts.unsafePerm + stdio: opts.stdio || 'pipe', + unsafePerm: opts.unsafePerm, }) function npmLog (prefix: string, logid: string, stdtype: string, line: string) { switch (stdtype) { case 'stdout': lifecycleLogger.info({ - script: stage, line: line.toString(), pkgId: opts.pkgId, + script: stage, }) return case 'stderr': lifecycleLogger.error({ - script: stage, line: line.toString(), pkgId: opts.pkgId, + script: stage, }) return case 'Returned: code:': @@ -94,9 +94,9 @@ export async function npmRunScript ( } const code = arguments[3] lifecycleLogger[code === 0 ? 'info' : 'error']({ + exitCode: code, pkgId: opts.pkgId, script: stage, - exitCode: code, }) return } @@ -114,6 +114,6 @@ async function checkBindingGyp ( try { await fs.stat(path.join(root, 'binding.gyp')) // if fs.stat didn't throw, it means that binding.gyp exists: the default install script is: - scripts['install'] = 'node-gyp rebuild' - } catch {} + scripts['install'] = 'node-gyp rebuild' // tslint:disable-line:no-string-literal + } catch {} // tslint:disable-line:no-empty } diff --git a/src/link/index.ts b/src/link/index.ts index 0583bba089..969adf9335 100644 --- a/src/link/index.ts +++ b/src/link/index.ts @@ -1,22 +1,22 @@ -import path = require('path') -import symlinkDir = require('symlink-dir') -import R = require('ramda') -import pLimit = require('p-limit') -import {TreeNode} from '../api/install' -import linkBins, {linkPkgBins} from './linkBins' import {PackageJson} from '@pnpm/types' -import {StoreController} from 'package-store' -import resolvePeers, {DependencyTreeNode, DependencyTreeNodeMap} from './resolvePeers' -import logStatus from '../logging/logInstallStatus' -import updateShrinkwrap from './updateShrinkwrap' import * as dp from 'dependency-path' -import {Shrinkwrap, DependencyShrinkwrap} from 'pnpm-shrinkwrap' +import pLimit = require('p-limit') +import {StoreController} from 'package-store' +import path = require('path') +import {DependencyShrinkwrap, Shrinkwrap} from 'pnpm-shrinkwrap' +import R = require('ramda') +import symlinkDir = require('symlink-dir') +import {TreeNode} from '../api/install' import removeOrphanPkgs from '../api/removeOrphanPkgs' import { rootLogger, - statsLogger, stageLogger, + statsLogger, } from '../loggers' +import logStatus from '../logging/logInstallStatus' +import linkBins, {linkPkgBins} from './linkBins' +import resolvePeers, {DependencyTreeNode, DependencyTreeNodeMap} from './resolvePeers' +import updateShrinkwrap from './updateShrinkwrap' export default async function linkPackages ( rootNodeIdsByAlias: {[alias: string]: string}, @@ -27,7 +27,7 @@ export default async function linkPackages ( global: boolean, baseNodeModules: string, bin: string, - topParents: {name: string, version: string}[], + topParents: Array<{name: string, version: string}>, wantedShrinkwrap: Shrinkwrap, currentShrinkwrap: Shrinkwrap, makePartialCurrentShrinkwrap: boolean, @@ -46,7 +46,7 @@ export default async function linkPackages ( shamefullyFlatten: boolean, reinstallForFlatten: boolean, hoistedAliases: {[pkgId: string]: string[]}, - } + }, ): Promise<{ linkedPkgsMap: DependencyTreeNodeMap, wantedShrinkwrap: Shrinkwrap, @@ -64,31 +64,31 @@ export default async function linkPackages ( const newShr = updateShrinkwrap(pkgsToLink, opts.wantedShrinkwrap, opts.pkg) const removedPkgIds = await removeOrphanPkgs({ + bin: opts.bin, dryRun: opts.dryRun, - oldShrinkwrap: opts.currentShrinkwrap, + hoistedAliases: opts.hoistedAliases, newShrinkwrap: newShr, + oldShrinkwrap: opts.currentShrinkwrap, prefix: opts.root, shamefullyFlatten: opts.shamefullyFlatten, storeController: opts.storeController, - bin: opts.bin, - hoistedAliases: opts.hoistedAliases, }) - let flatResolvedDeps = R.values(pkgsToLink).filter(dep => !opts.skipped.has(dep.id)) + let flatResolvedDeps = R.values(pkgsToLink).filter((dep) => !opts.skipped.has(dep.id)) if (!opts.production) { - flatResolvedDeps = flatResolvedDeps.filter(dep => dep.dev !== false || dep.optional) + flatResolvedDeps = flatResolvedDeps.filter((dep) => dep.dev !== false || dep.optional) } if (!opts.development) { - flatResolvedDeps = flatResolvedDeps.filter(dep => dep.dev !== true) + flatResolvedDeps = flatResolvedDeps.filter((dep) => dep.dev !== true) } if (!opts.optional) { - flatResolvedDeps = flatResolvedDeps.filter(dep => !dep.optional) + flatResolvedDeps = flatResolvedDeps.filter((dep) => !dep.optional) } const filterOpts = { - noProd: !opts.production, noDev: !opts.development, noOptional: !opts.optional, + noProd: !opts.production, skipped: opts.skipped, } const newCurrentShrinkwrap = filterShrinkwrap(newShr, filterOpts) @@ -97,17 +97,17 @@ export default async function linkPackages ( filterShrinkwrap(opts.currentShrinkwrap, filterOpts), newCurrentShrinkwrap, pkgsToLink, - opts + opts, ) stageLogger.debug('importing_done') const rootPkgsToLinkByAbsolutePath = flatResolvedDeps - .filter(pkg => pkg.depth === 0) + .filter((pkg) => pkg.depth === 0) .reduce((rootPkgsToLink, pkg) => { rootPkgsToLink[pkg.absolutePath] = pkg return rootPkgsToLink }, {}) - for (let rootAlias of R.keys(resolvePeersResult.rootAbsolutePathsByAlias)) { + for (const rootAlias of R.keys(resolvePeersResult.rootAbsolutePathsByAlias)) { const pkg = rootPkgsToLinkByAbsolutePath[resolvePeersResult.rootAbsolutePathsByAlias[rootAlias]] if (!pkg) continue if (opts.dryRun || !(await symlinkDependencyTo(rootAlias, pkg, opts.baseNodeModules)).reused) { @@ -115,18 +115,18 @@ export default async function linkPackages ( const isOptional = opts.pkg.optionalDependencies && opts.pkg.optionalDependencies[pkg.name] rootLogger.info({ added: { + dependencyType: isDev && 'dev' || isOptional && 'optional' || 'prod', id: pkg.id, + latest: opts.outdatedPkgs[pkg.id], name: rootAlias, realName: pkg.name, version: pkg.version, - latest: opts.outdatedPkgs[pkg.id], - dependencyType: isDev && 'dev' || isOptional && 'optional' || 'prod', }, }) } logStatus({ - status: 'installed', pkgId: pkg.id, + status: 'installed', }) } @@ -145,7 +145,7 @@ export default async function linkPackages ( if (opts.makePartialCurrentShrinkwrap) { const packages = opts.currentShrinkwrap.packages || {} if (newShr.packages) { - for (const relDepPath in newShr.packages) { + for (const relDepPath in newShr.packages) { // tslint:disable-line:forin const depPath = dp.resolve(newShr.registry, relDepPath) if (pkgsToLink[depPath]) { packages[relDepPath] = newShr.packages[relDepPath] @@ -165,25 +165,25 @@ export default async function linkPackages ( } return { - linkedPkgsMap: pkgsToLink, - wantedShrinkwrap: newShr, currentShrinkwrap, + hoistedAliases: opts.hoistedAliases, + linkedPkgsMap: pkgsToLink, newDepPaths, removedPkgIds, - hoistedAliases: opts.hoistedAliases, + wantedShrinkwrap: newShr, } } -async function shamefullyFlattenTree( +async function shamefullyFlattenTree ( flatResolvedDeps: DependencyTreeNode[], currentShrinkwrap: Shrinkwrap, opts: { - force: boolean, - dryRun: boolean, baseNodeModules: string, bin: string, - pkg: PackageJson, + dryRun: boolean, + force: boolean, outdatedPkgs: {[pkgId: string]: string}, + pkg: PackageJson, }, ): Promise<{[alias: string]: string[]}> { const dependencyPathByAlias = {} @@ -196,8 +196,8 @@ async function shamefullyFlattenTree( return depthDiff === 0 ? a.name.localeCompare(b.name) : depthDiff }) // build the alias map and the id map - .map(pkg => { - for (let childAlias of R.keys(pkg.children)) { + .map((pkg) => { + for (const childAlias of R.keys(pkg.children)) { // if this alias is in the root dependencies, skip it if (currentShrinkwrap.specifiers[childAlias]) { continue @@ -215,7 +215,7 @@ async function shamefullyFlattenTree( } return pkg }) - .map(async pkg => { + .map(async (pkg) => { const pkgAliases = aliasesByDependencyPath[pkg.absolutePath] if (!pkgAliases) { return @@ -223,7 +223,7 @@ async function shamefullyFlattenTree( // TODO when putting logs back in for hoisted packages, you've to put back the condition inside the map, // TODO look how it is done in linkPackages if (!opts.dryRun) { - await Promise.all(pkgAliases.map(async pkgAlias => { + await Promise.all(pkgAliases.map(async (pkgAlias) => { await symlinkDependencyTo(pkgAlias, pkg, opts.baseNodeModules) })) } @@ -235,31 +235,31 @@ async function shamefullyFlattenTree( function filterShrinkwrap ( shr: Shrinkwrap, opts: { - noProd: boolean, noDev: boolean, noOptional: boolean, + noProd: boolean, skipped: Set, - } + }, ): Shrinkwrap { let pairs = R.toPairs(shr.packages || {}) - .filter(pair => !opts.skipped.has(pair[1].id || dp.resolve(shr.registry, pair[0]))) + .filter((pair) => !opts.skipped.has(pair[1].id || dp.resolve(shr.registry, pair[0]))) if (opts.noProd) { - pairs = pairs.filter(pair => pair[1].dev !== false || pair[1].optional) + pairs = pairs.filter((pair) => pair[1].dev !== false || pair[1].optional) } if (opts.noDev) { - pairs = pairs.filter(pair => pair[1].dev !== true) + pairs = pairs.filter((pair) => pair[1].dev !== true) } if (opts.noOptional) { - pairs = pairs.filter(pair => !pair[1].optional) + pairs = pairs.filter((pair) => !pair[1].optional) } return { - shrinkwrapVersion: shr.shrinkwrapVersion, - registry: shr.registry, - specifiers: shr.specifiers, - packages: R.fromPairs(pairs), dependencies: opts.noProd ? {} : shr.dependencies || {}, devDependencies: opts.noDev ? {} : shr.devDependencies || {}, optionalDependencies: opts.noOptional ? {} : shr.optionalDependencies || {}, + packages: R.fromPairs(pairs), + registry: shr.registry, + shrinkwrapVersion: shr.shrinkwrapVersion, + specifiers: shr.specifiers, } as Shrinkwrap } @@ -268,14 +268,14 @@ async function linkNewPackages ( wantedShrinkwrap: Shrinkwrap, pkgsToLink: DependencyTreeNodeMap, opts: { + baseNodeModules: string, dryRun: boolean, force: boolean, global: boolean, - baseNodeModules: string, optional: boolean, - storeController: StoreController, sideEffectsCache: boolean, - } + storeController: StoreController, + }, ): Promise { const wantedRelDepPaths = R.keys(wantedShrinkwrap.packages) const prevRelDepPaths = R.keys(currentShrinkwrap.packages) @@ -287,10 +287,10 @@ async function linkNewPackages ( ? wantedRelDepPaths : R.difference(wantedRelDepPaths, prevRelDepPaths) ) - .map(relDepPath => dp.resolve(wantedShrinkwrap.registry, relDepPath)) + .map((relDepPath) => dp.resolve(wantedShrinkwrap.registry, relDepPath)) // when installing a new package, not all the nodes are analyzed // just skip the ones that are in the lockfile but were not analyzed - .filter(depPath => pkgsToLink[depPath]) + .filter((depPath) => pkgsToLink[depPath]), ) statsLogger.debug({added: newDepPathsSet.size}) @@ -340,18 +340,18 @@ async function linkAllPkgs ( opts: { force: boolean, sideEffectsCache: boolean, - } + }, ) { return Promise.all( - alldeps.map(async pkg => { + alldeps.map(async (pkg) => { const filesResponse = await pkg.fetchingFiles if (pkg.independent) return return storeController.importPackage(pkg.centralLocation, pkg.peripheralLocation, { - force: opts.force, filesResponse, + force: opts.force, }) - }) + }), ) } @@ -360,10 +360,10 @@ async function linkAllBins ( pkgMap: DependencyTreeNodeMap, opts: { optional: boolean, - } + }, ) { return Promise.all( - pkgs.map(dependency => limitLinking(async () => { + pkgs.map((dependency) => limitLinking(async () => { const binPath = path.join(dependency.peripheralLocation, 'node_modules', '.bin') const childrenToLink = opts.optional @@ -378,13 +378,13 @@ async function linkAllBins ( await Promise.all( R.keys(childrenToLink) - .map(async alias => { + .map(async (alias) => { const childToLink = childrenToLink[alias] const child = pkgMap[childToLink] if (child.installable) { await linkPkgBins(path.join(dependency.modules, alias), binPath) } - }) + }), ) // link also the bundled dependencies` bins @@ -392,7 +392,7 @@ async function linkAllBins ( const bundledModules = path.join(dependency.peripheralLocation, 'node_modules') await linkBins(bundledModules, binPath) } - })) + })), ) } @@ -401,12 +401,12 @@ async function linkAllModules ( pkgMap: DependencyTreeNodeMap, opts: { optional: boolean, - } + }, ) { return Promise.all( pkgs - .filter(dependency => !dependency.independent) - .map(dependency => limitLinking(async () => { + .filter((dependency) => !dependency.independent) + .map((dependency) => limitLinking(async () => { const childrenToLink = opts.optional ? dependency.children : R.keys(dependency.children) @@ -419,13 +419,13 @@ async function linkAllModules ( await Promise.all( R.keys(childrenToLink) - .map(async alias => { + .map(async (alias) => { const pkg = pkgMap[childrenToLink[alias]] if (!pkg.installable) return await symlinkDependencyTo(alias, pkg, dependency.modules) - }) + }), ) - })) + })), ) } diff --git a/src/link/linkBins.ts b/src/link/linkBins.ts index f749168dfe..c657a33f7f 100644 --- a/src/link/linkBins.ts +++ b/src/link/linkBins.ts @@ -1,15 +1,15 @@ -import path = require('path') -import normalizePath = require('normalize-path') -import fs = require('mz/fs') -import mkdirp = require('mkdirp-promise') -import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' -import getPkgDirs from '../fs/getPkgDirs' -import binify from '../binify' -import isWindows = require('is-windows') -import cmdShim = require('@zkochan/cmd-shim') import logger from '@pnpm/logger' +import cmdShim = require('@zkochan/cmd-shim') +import isWindows = require('is-windows') +import mkdirp = require('mkdirp-promise') import Module = require('module') +import fs = require('mz/fs') +import normalizePath = require('normalize-path') +import path = require('path') import R = require('ramda') +import binify from '../binify' +import getPkgDirs from '../fs/getPkgDirs' +import {fromDir as safeReadPkgFromDir} from '../fs/safeReadPkg' const IS_WINDOWS = isWindows() @@ -17,9 +17,9 @@ export default async function linkAllBins (modules: string, binPath: string, exc const pkgDirs = await getPkgDirs(modules) return Promise.all( pkgDirs - .map(pkgDir => normalizePath(pkgDir)) - .filter(pkgDir => !exceptPkgName || !pkgDir.endsWith(`/${exceptPkgName}`)) - .map((pkgDir: string) => linkPkgBins(pkgDir, binPath)) + .map((pkgDir) => normalizePath(pkgDir)) + .filter((pkgDir) => !exceptPkgName || !pkgDir.endsWith(`/${exceptPkgName}`)) + .map((pkgDir: string) => linkPkgBins(pkgDir, binPath)), ) } @@ -39,7 +39,7 @@ export async function linkPkgBins (target: string, binPath: string) { if (!cmds.length) return await mkdirp(binPath) - await Promise.all(cmds.map(async cmd => { + await Promise.all(cmds.map(async (cmd) => { const externalBinPath = path.join(binPath, cmd.name) const nodePath = (await getBinNodePaths(target)).join(path.delimiter) @@ -51,7 +51,7 @@ async function getBinNodePaths (target: string) { const targetRealPath = await fs.realpath(target) return R.union( - Module['_nodeModulePaths'](targetRealPath), - Module['_nodeModulePaths'](target) + Module['_nodeModulePaths'](targetRealPath), // tslint:disable-line:no-string-literal + Module['_nodeModulePaths'](target), // tslint:disable-line:no-string-literal ) } diff --git a/src/link/resolvePeers.ts b/src/link/resolvePeers.ts index 344d3a7751..8b6a68cf85 100644 --- a/src/link/resolvePeers.ts +++ b/src/link/resolvePeers.ts @@ -1,23 +1,23 @@ -import pkgIdToFilename from '@pnpm/pkgid-to-filename' -import {PackageFilesResponse} from '@pnpm/package-requester' -import {Resolution} from '@pnpm/resolver-base' -import {Dependencies} from '@pnpm/types' -import R = require('ramda') -import semver = require('semver') import logger from '@pnpm/logger' +import {PackageFilesResponse} from '@pnpm/package-requester' +import pkgIdToFilename from '@pnpm/pkgid-to-filename' +import {Resolution} from '@pnpm/resolver-base' import {PackageManifest} from '@pnpm/types' -import path = require('path') +import {Dependencies} from '@pnpm/types' import {oneLine} from 'common-tags' import crypto = require('crypto') -import {InstalledPackage} from '../resolveDependencies' +import path = require('path') +import R = require('ramda') +import semver = require('semver') import {TreeNode, TreeNodeMap} from '../api/install' import { - splitNodeId, createNodeId, ROOT_NODE_ID, + splitNodeId, } from '../nodeIdUtils' +import {InstalledPackage} from '../resolveDependencies' -export type DependencyTreeNode = { +export interface DependencyTreeNode { name: string, // at this point the version is really needed only for logging version: string, @@ -54,7 +54,7 @@ export type DependencyTreeNode = { isBuilt?: boolean, } -export type DependencyTreeNodeMap = { +export interface DependencyTreeNodeMap { // a node ID is the join of the package's keypath with a colon // E.g., a subdeps node ID which parent is `foo` will be // registry.npmjs.org/foo/1.0.0:registry.npmjs.org/bar/1.0.0 @@ -66,9 +66,9 @@ export default function ( rootNodeIdsByAlias: {[alias: string]: string}, // only the top dependencies that were already installed // to avoid warnings about unresolved peer dependencies - topParents: {name: string, version: string}[], + topParents: Array<{name: string, version: string}>, independentLeaves: boolean, - nodeModules: string + nodeModules: string, ): { resolvedTree: DependencyTreeNodeMap, rootAbsolutePathsByAlias: {[alias: string]: string}, @@ -78,26 +78,26 @@ export default function ( topParents.map((parent: {name: string, version: string}): R.KeyValuePair => [ parent.name, { + depth: 0, version: parent.version, - depth: 0 - } - ]) + }, + ]), ), - toPkgByName(R.keys(rootNodeIdsByAlias).map(alias => ({alias, nodeId: rootNodeIdsByAlias[alias], node: tree[rootNodeIdsByAlias[alias]]}))) + toPkgByName(R.keys(rootNodeIdsByAlias).map((alias) => ({alias, nodeId: rootNodeIdsByAlias[alias], node: tree[rootNodeIdsByAlias[alias]]}))), ) const absolutePathsByNodeId = {} const resolvedTree: DependencyTreeNodeMap = {} resolvePeersOfChildren(rootNodeIdsByAlias, pkgsByName, { - tree, absolutePathsByNodeId, - resolvedTree, independentLeaves, nodeModules, purePkgs: new Set(), + resolvedTree, + tree, }) - R.values(resolvedTree).forEach(node => { + R.values(resolvedTree).forEach((node) => { node.children = R.keys(node.children).reduce((acc, alias) => { acc[alias] = absolutePathsByNodeId[node.children[alias]] return acc @@ -108,7 +108,7 @@ export default function ( rootAbsolutePathsByAlias: R.keys(rootNodeIdsByAlias).reduce((rootAbsolutePathsByAlias, alias) => { rootAbsolutePathsByAlias[alias] = absolutePathsByNodeId[rootNodeIdsByAlias[alias]] return rootAbsolutePathsByAlias - }, {}) + }, {}), } } @@ -122,7 +122,7 @@ function resolvePeersOfNode ( independentLeaves: boolean, nodeModules: string, purePkgs: Set, // pure packages are those that don't rely on externally resolved peers - } + }, ): {[alias: string]: string} { const node = ctx.tree[nodeId] if (ctx.purePkgs.has(node.pkg.id) && ctx.resolvedTree[node.pkg.id].depth <= node.depth) { @@ -135,7 +135,7 @@ function resolvePeersOfNode ( ? parentParentPkgs : { ...parentParentPkgs, - ...toPkgByName(R.keys(children).map(alias => ({alias, nodeId: children[alias], node: ctx.tree[children[alias]]}))) + ...toPkgByName(R.keys(children).map((alias) => ({alias, nodeId: children[alias], node: ctx.tree[children[alias]]}))), } const unknownResolvedPeersOfChildren = resolvePeersOfChildren(children, parentPkgs, ctx, nodeId) @@ -156,7 +156,7 @@ function resolvePeersOfNode ( } } else { const peersFolder = createPeersFolderName( - R.keys(allResolvedPeers).map(alias => ({ + R.keys(allResolvedPeers).map((alias) => ({ name: alias, version: ctx.tree[allResolvedPeers[alias]].pkg.version, }))) @@ -172,26 +172,26 @@ function resolvePeersOfNode ( ? path.join(modules, node.pkg.name) : centralLocation ctx.resolvedTree[absolutePath] = { - name: node.pkg.name, - version: node.pkg.version, - hasBundledDependencies: node.pkg.hasBundledDependencies, - fetchingFiles: node.pkg.fetchingFiles, - resolution: node.pkg.resolution, + absolutePath, + additionalInfo: node.pkg.additionalInfo, centralLocation, - isBuilt: !!node.pkg.engineCache, - modules, - peripheralLocation, - independent, - optionalDependencies: node.pkg.optionalDependencies, children: Object.assign(children, resolvedPeers), depth: node.depth, - absolutePath, - prod: node.pkg.prod, dev: node.pkg.dev, - optional: node.pkg.optional, + fetchingFiles: node.pkg.fetchingFiles, + hasBundledDependencies: node.pkg.hasBundledDependencies, id: node.pkg.id, + independent, installable: node.installable, - additionalInfo: node.pkg.additionalInfo, + isBuilt: !!node.pkg.engineCache, + modules, + name: node.pkg.name, + optional: node.pkg.optional, + optionalDependencies: node.pkg.optionalDependencies, + peripheralLocation, + prod: node.pkg.prod, + resolution: node.pkg.resolution, + version: node.pkg.version, } } return allResolvedPeers @@ -203,26 +203,26 @@ function resolvePeersOfChildren ( }, parentPkgs: ParentRefs, ctx: { - tree: {[nodeId: string]: TreeNode}, absolutePathsByNodeId: {[nodeId: string]: string}, - resolvedTree: DependencyTreeNodeMap, independentLeaves: boolean, nodeModules: string, purePkgs: Set, + resolvedTree: DependencyTreeNodeMap, + tree: {[nodeId: string]: TreeNode}, }, exceptNodeId?: string, ): {[alias: string]: string} { - let allResolvedPeers: {[alias: string]: string} = {} + const allResolvedPeers: {[alias: string]: string} = {} for (const childNodeId of R.values(children)) { Object.assign(allResolvedPeers, resolvePeersOfNode(childNodeId, parentPkgs, ctx)) } const unknownResolvedPeersOfChildren = R.keys(allResolvedPeers) - .filter(alias => !children[alias] && allResolvedPeers[alias] !== exceptNodeId) - .reduce((unknownResolvedPeersOfChildren, peer) => { - unknownResolvedPeersOfChildren[peer] = allResolvedPeers[peer] - return unknownResolvedPeersOfChildren + .filter((alias) => !children[alias] && allResolvedPeers[alias] !== exceptNodeId) + .reduce((acc, peer) => { + acc[peer] = allResolvedPeers[peer] + return acc }, {}) return unknownResolvedPeersOfChildren @@ -232,12 +232,12 @@ function resolvePeers ( nodeId: string, node: TreeNode, parentPkgs: ParentRefs, - tree: TreeNodeMap + tree: TreeNodeMap, ): { - [alias: string]: string + [alias: string]: string, } { const resolvedPeers: {[alias: string]: string} = {} - for (const peerName in node.pkg.peerDependencies) { + for (const peerName in node.pkg.peerDependencies) { // tslint:disable-line:forin const peerVersionRange = node.pkg.peerDependencies[peerName] const resolved = parentPkgs[peerName] @@ -246,7 +246,7 @@ function resolvePeers ( const friendlyPath = nodeIdToFriendlyPath(nodeId, tree) logger.warn(oneLine` ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(node.pkg)} - requires a peer of ${peerName}@${peerVersionRange} but none was installed.` + requires a peer of ${peerName}@${peerVersionRange} but none was installed.`, ) continue } @@ -255,7 +255,7 @@ function resolvePeers ( const friendlyPath = nodeIdToFriendlyPath(nodeId, tree) logger.warn(oneLine` ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(node.pkg)} - requires a peer of ${peerName}@${peerVersionRange} but version ${resolved.version} was installed.` + requires a peer of ${peerName}@${peerVersionRange} but version ${resolved.version} was installed.`, ) } @@ -278,35 +278,35 @@ function packageFriendlyId (pkg: {name: string, version: string}) { function nodeIdToFriendlyPath (nodeId: string, tree: TreeNodeMap) { const parts = splitNodeId(nodeId).slice(2, -2) return R.tail(R.scan((prevNodeId, pkgId) => createNodeId(prevNodeId, pkgId), ROOT_NODE_ID, parts)) - .map(nodeId => tree[nodeId].pkg.name) + .map((nid) => tree[nid].pkg.name) .join(' > ') } -type ParentRefs = { +interface ParentRefs { [name: string]: ParentRef } -type ParentRef = { +interface ParentRef { version: string, depth: number, // this is null only for already installed top dependencies nodeId?: string, } -function toPkgByName (nodes: {alias: string, nodeId: string, node: TreeNode}[]): ParentRefs { +function toPkgByName (nodes: Array<{alias: string, nodeId: string, node: TreeNode}>): ParentRefs { const pkgsByName: ParentRefs = {} for (const node of nodes) { pkgsByName[node.alias] = { - version: node.node.pkg.version, - nodeId: node.nodeId, depth: node.node.depth, + nodeId: node.nodeId, + version: node.node.pkg.version, } } return pkgsByName } -function createPeersFolderName(peers: {name: string, version: string}[]) { - const folderName = peers.map(peer => `${peer.name.replace('/', '!')}@${peer.version}`).sort().join('+') +function createPeersFolderName (peers: Array<{name: string, version: string}>) { + const folderName = peers.map((peer) => `${peer.name.replace('/', '!')}@${peer.version}`).sort().join('+') // We don't want the folder name to get too long. // Otherwise, an ENAMETOOLONG error might happen. diff --git a/src/link/updateShrinkwrap.ts b/src/link/updateShrinkwrap.ts index 73a062f79d..237be342ea 100644 --- a/src/link/updateShrinkwrap.ts +++ b/src/link/updateShrinkwrap.ts @@ -1,45 +1,45 @@ -import * as dp from 'dependency-path' -import {absolutePathToRef} from '../fs/shrinkwrap' -import { - Shrinkwrap, - DependencyShrinkwrap, - ShrinkwrapResolution, - ResolvedDependencies, - prune as pruneShrinkwrap, -} from 'pnpm-shrinkwrap' -import {DependencyTreeNodeMap, DependencyTreeNode} from './resolvePeers' import {Resolution} from '@pnpm/resolver-base' +import {Dependencies, PackageJson} from '@pnpm/types' +import * as dp from 'dependency-path' +import { + DependencyShrinkwrap, + prune as pruneShrinkwrap, + ResolvedDependencies, + Shrinkwrap, + ShrinkwrapResolution, +} from 'pnpm-shrinkwrap' import R = require('ramda') -import {PackageJson, Dependencies} from '@pnpm/types' +import {absolutePathToRef} from '../fs/shrinkwrap' +import {DependencyTreeNode, DependencyTreeNodeMap} from './resolvePeers' export default function ( pkgsToLink: DependencyTreeNodeMap, shrinkwrap: Shrinkwrap, - pkg: PackageJson + pkg: PackageJson, ): Shrinkwrap { shrinkwrap.packages = shrinkwrap.packages || {} for (const depPath of R.keys(pkgsToLink)) { const relDepPath = dp.relative(shrinkwrap.registry, depPath) const result = R.partition( (child) => pkgsToLink[depPath].optionalDependencies.has(pkgsToLink[child.nodeId].name), - R.keys(pkgsToLink[depPath].children).map(alias => ({alias, nodeId: pkgsToLink[depPath].children[alias]})) + R.keys(pkgsToLink[depPath].children).map((alias) => ({alias, nodeId: pkgsToLink[depPath].children[alias]})), ) shrinkwrap.packages[relDepPath] = toShrDependency(pkgsToLink[depPath].additionalInfo, { depPath, - name: pkgsToLink[depPath].name, - version: pkgsToLink[depPath].version, + dev: pkgsToLink[depPath].dev, id: pkgsToLink[depPath].id, - relDepPath, - resolution: pkgsToLink[depPath].resolution, - updatedOptionalDeps: result[0], - updatedDeps: result[1], - registry: shrinkwrap.registry, + name: pkgsToLink[depPath].name, + optional: pkgsToLink[depPath].optional, pkgsToLink, prevResolvedDeps: shrinkwrap.packages[relDepPath] && shrinkwrap.packages[relDepPath].dependencies || {}, prevResolvedOptionalDeps: shrinkwrap.packages[relDepPath] && shrinkwrap.packages[relDepPath].optionalDependencies || {}, prod: pkgsToLink[depPath].prod, - dev: pkgsToLink[depPath].dev, - optional: pkgsToLink[depPath].optional, + registry: shrinkwrap.registry, + relDepPath, + resolution: pkgsToLink[depPath].resolution, + updatedDeps: result[1], + updatedOptionalDeps: result[0], + version: pkgsToLink[depPath].version, }) } return pruneShrinkwrap(shrinkwrap, pkg) @@ -66,22 +66,23 @@ function toShrDependency ( relDepPath: string, resolution: Resolution, registry: string, - updatedDeps: {alias: string, nodeId: string}[], - updatedOptionalDeps: {alias: string, nodeId: string}[], + updatedDeps: Array<{alias: string, nodeId: string}>, + updatedOptionalDeps: Array<{alias: string, nodeId: string}>, pkgsToLink: DependencyTreeNodeMap, prevResolvedDeps: ResolvedDependencies, prevResolvedOptionalDeps: ResolvedDependencies, prod: boolean, dev: boolean, optional: boolean, - } + }, ): DependencyShrinkwrap { const shrResolution = toShrResolution(opts.relDepPath, opts.resolution, opts.registry) const newResolvedDeps = updateResolvedDeps(opts.prevResolvedDeps, opts.updatedDeps, opts.registry, opts.pkgsToLink) const newResolvedOptionalDeps = updateResolvedDeps(opts.prevResolvedOptionalDeps, opts.updatedOptionalDeps, opts.registry, opts.pkgsToLink) const result = { - resolution: shrResolution + resolution: shrResolution, } + // tslint:disable:no-string-literal if (dp.isAbsolute(opts.relDepPath)) { result['name'] = opts.name @@ -112,7 +113,7 @@ function toShrDependency ( result['peerDependencies'] = pkg.peerDependencies } if (pkg.engines) { - for (let engine of R.keys(pkg.engines)) { + for (const engine of R.keys(pkg.engines)) { if (pkg.engines[engine] === '*') continue result['engines'] = result['engines'] || {} result['engines'][engine] = pkg.engines[engine] @@ -130,6 +131,7 @@ function toShrDependency ( if (pkg.deprecated) { result['deprecated'] = pkg.deprecated } + // tslint:enable:no-string-literal return result } @@ -138,9 +140,9 @@ function toShrDependency ( // the `depth` property defines how deep should dependencies be checked function updateResolvedDeps ( prevResolvedDeps: ResolvedDependencies, - updatedDeps: {alias: string, nodeId: string}[], + updatedDeps: Array<{alias: string, nodeId: string}>, registry: string, - pkgsToLink: DependencyTreeNodeMap + pkgsToLink: DependencyTreeNodeMap, ) { const newResolvedDeps = R.fromPairs( updatedDeps @@ -153,21 +155,22 @@ function updateResolvedDeps ( realName: pkgToLink.name, resolution: pkgToLink.resolution, standardRegistry: registry, - }) + }), ] - }) + }), ) return R.merge( prevResolvedDeps, - newResolvedDeps + newResolvedDeps, ) } function toShrResolution ( relDepPath: string, resolution: Resolution, - registry: string + registry: string, ): ShrinkwrapResolution { + // tslint:disable:no-string-literal if (dp.isAbsolute(relDepPath) || resolution.type !== undefined || !resolution['integrity']) { return resolution as ShrinkwrapResolution } @@ -182,6 +185,7 @@ function toShrResolution ( return { integrity: resolution['integrity'], } + // tslint:enable:no-string-literal } function relativeTarball (tarball: string, registry: string) { diff --git a/src/loggers.ts b/src/loggers.ts index 87c030cba5..e22dbc0808 100644 --- a/src/loggers.ts +++ b/src/loggers.ts @@ -15,9 +15,9 @@ export const progressLogger = baseLogger('progress') as Logger export const statsLogger = baseLogger('stats') as Logger export type PackageJsonMessage = { - initial: PackageJson + initial: PackageJson, } | { - updated: object + updated: object, } export type PackageJsonLog = {name: 'pnpm:package-json'} & LogBase & PackageJsonMessage @@ -71,7 +71,7 @@ export type RootMessage = { from: string, to: string, dependencyType?: DependencyType, - } + }, } export type RootLog = {name: 'pnpm:root'} & LogBase & RootMessage @@ -84,7 +84,7 @@ export interface LoggedPkg { export type ProgressMessage = { pkgId: string, - status: 'installed' | 'dependencies_installed' + status: 'installed' | 'dependencies_installed', } | { pkg: LoggedPkg, status: 'installing', diff --git a/src/logging/logInstallStatus.ts b/src/logging/logInstallStatus.ts index 0f2c7c4329..bd2193864d 100644 --- a/src/logging/logInstallStatus.ts +++ b/src/logging/logInstallStatus.ts @@ -1,6 +1,6 @@ import { - ProgressMessage, progressLogger, + ProgressMessage, } from '../loggers' export default (loginfo: ProgressMessage) => progressLogger.debug(loginfo) diff --git a/src/memoize.ts b/src/memoize.ts index 307a3a8c91..2964c7ad39 100644 --- a/src/memoize.ts +++ b/src/memoize.ts @@ -1,6 +1,6 @@ import pLimit = require('p-limit') -type CachedPromises = { +interface CachedPromises { [name: string]: Promise } @@ -9,11 +9,11 @@ export type MemoizedFunc = (key: string, fn: () => Promise) => Promise /** * Save promises for later */ -export default function memoize (concurrency?: number): MemoizedFunc { +export default function memoize (concurrency?: number): MemoizedFunc { const locks: CachedPromises = {} const limit = concurrency && pLimit(concurrency) - return function (key: string, fn: () => Promise): Promise { + return (key: string, fn: () => Promise): Promise => { if (locks[key]) return locks[key] locks[key] = limit && limit(fn) || fn() return locks[key] diff --git a/src/parseWantedDependencies.ts b/src/parseWantedDependencies.ts index e4e2db1f06..07b6a58937 100644 --- a/src/parseWantedDependencies.ts +++ b/src/parseWantedDependencies.ts @@ -9,25 +9,27 @@ import { export default function parseWantedDependencies ( rawWantedDependencies: string[], opts: { + currentPrefs: Dependencies, defaultTag: string, dev: boolean, - optional: boolean, - currentPrefs: Dependencies, - optionalDependencies: Dependencies, devDependencies: Dependencies, - } + optional: boolean, + optionalDependencies: Dependencies, + }, ): WantedDependency[] { return rawWantedDependencies - .map(rawWantedDependency => { + .map((rawWantedDependency) => { const parsed = parseWantedDependency(rawWantedDependency) + // tslint:disable:no-string-literal const alias = parsed['alias'] as (string | undefined) const pref = parsed['pref'] as (string | undefined) + // tslint:enable:no-string-literal return { alias, - raw: rawWantedDependency, - pref: pref || alias && opts.currentPrefs[alias] || opts.defaultTag, dev: Boolean(opts.dev || alias && !!opts.devDependencies[alias]), optional: Boolean(opts.optional || alias && !!opts.optionalDependencies[alias]), + pref: pref || alias && opts.currentPrefs[alias] || opts.defaultTag, + raw: rawWantedDependency, } }) } diff --git a/src/readShrinkwrapFiles.ts b/src/readShrinkwrapFiles.ts index 18315405f0..80cbb8be7f 100644 --- a/src/readShrinkwrapFiles.ts +++ b/src/readShrinkwrapFiles.ts @@ -1,32 +1,32 @@ -import { - existsWanted as existsWantedShrinkwrap, - readWanted as readWantedShrinkwrap, - readCurrent as readCurrentShrinkwrap, - Shrinkwrap, - create as createShrinkwrap, -} from 'pnpm-shrinkwrap' import logger from '@pnpm/logger' -import R = require('ramda') import isCI = require('is-ci') +import { + create as createShrinkwrap, + existsWanted as existsWantedShrinkwrap, + readCurrent as readCurrentShrinkwrap, + readWanted as readWantedShrinkwrap, + Shrinkwrap, +} from 'pnpm-shrinkwrap' +import R = require('ramda') -export type PnpmContext = { - existsWantedShrinkwrap: boolean, - existsCurrentShrinkwrap: boolean, +export interface PnpmContext { currentShrinkwrap: Shrinkwrap, + existsCurrentShrinkwrap: boolean, + existsWantedShrinkwrap: boolean, wantedShrinkwrap: Shrinkwrap, } export default async function getContext ( opts: { - prefix: string, - shrinkwrap: boolean, force: boolean, + prefix: string, registry: string, + shrinkwrap: boolean, }, ): Promise<{ - existsWantedShrinkwrap: boolean, - existsCurrentShrinkwrap: boolean, currentShrinkwrap: Shrinkwrap, + existsCurrentShrinkwrap: boolean, + existsWantedShrinkwrap: boolean, wantedShrinkwrap: Shrinkwrap, }> { // ignore `shrinkwrap.yaml` on CI servers @@ -40,9 +40,9 @@ export default async function getContext ( ]) const currentShrinkwrap = files[1] || createShrinkwrap(opts.registry) return { - wantedShrinkwrap: files[0] || !opts.shrinkwrap && currentShrinkwrap && R.clone(currentShrinkwrap) || createShrinkwrap(opts.registry), currentShrinkwrap, - existsWantedShrinkwrap: !!files[0], existsCurrentShrinkwrap: !!files[1], + existsWantedShrinkwrap: !!files[0], + wantedShrinkwrap: files[0] || !opts.shrinkwrap && currentShrinkwrap && R.clone(currentShrinkwrap) || createShrinkwrap(opts.registry), } } diff --git a/src/removeDeps.ts b/src/removeDeps.ts index 59318b1484..96d9ea029b 100644 --- a/src/removeDeps.ts +++ b/src/removeDeps.ts @@ -1,13 +1,13 @@ +import {PackageJson} from '@pnpm/types' import loadJsonFile = require('load-json-file') import writePkg = require('write-pkg') import {DependenciesType, dependenciesTypes} from './getSaveType' -import {PackageJson} from '@pnpm/types' import {packageJsonLogger} from './loggers' export default async function ( pkgJsonPath: string, removedPackages: string[], - saveType?: DependenciesType + saveType?: DependenciesType, ): Promise { const packageJson = await loadJsonFile(pkgJsonPath) @@ -16,14 +16,14 @@ export default async function ( if (!packageJson[saveType]) return packageJson - removedPackages.forEach(dependency => { + removedPackages.forEach((dependency) => { delete packageJson[saveType][dependency] }) } else { dependenciesTypes - .filter(deptype => packageJson[deptype]) - .forEach(deptype => { - removedPackages.forEach(dependency => { + .filter((deptype) => packageJson[deptype]) + .forEach((deptype) => { + removedPackages.forEach((dependency) => { delete packageJson[deptype][dependency] }) }) diff --git a/src/removeTopDependency.ts b/src/removeTopDependency.ts index d1d587f010..842c6a513f 100644 --- a/src/removeTopDependency.ts +++ b/src/removeTopDependency.ts @@ -1,21 +1,21 @@ -import rimraf = require('rimraf-then') import path = require('path') +import rimraf = require('rimraf-then') import binify from './binify' import {fromDir as safeReadPkgFromDir} from './fs/safeReadPkg' import {rootLogger} from './loggers' export default async function removeTopDependency ( dependency: { - name: string, dev: boolean, + name: string, optional: boolean, }, opts: { + bin: string, dryRun?: boolean, modules: string, - bin: string, muteLogs?: boolean, - } + }, ) { const results = await Promise.all([ removeBins(dependency.name, opts), @@ -26,9 +26,9 @@ export default async function removeTopDependency ( if (!opts.muteLogs) { rootLogger.info({ removed: { + dependencyType: dependency.dev && 'dev' || dependency.optional && 'optional' || 'prod', name: dependency.name, version: uninstalledPkg && uninstalledPkg.version, - dependencyType: dependency.dev && 'dev' || dependency.optional && 'optional' || 'prod' }, }) } @@ -40,7 +40,7 @@ async function removeBins ( dryRun?: boolean, modules: string, bin: string, - } + }, ) { const uninstalledPkgPath = path.join(opts.modules, uninstalledPkg) const uninstalledPkgJson = await safeReadPkgFromDir(uninstalledPkgPath) @@ -50,7 +50,7 @@ async function removeBins ( if (!opts.dryRun) { await Promise.all( - cmds.map(cmd => path.join(opts.bin, cmd.name)).map(rimraf) + cmds.map((cmd) => path.join(opts.bin, cmd.name)).map(rimraf), ) } diff --git a/src/resolveDependencies.ts b/src/resolveDependencies.ts index aa77e7ef9a..817551c26c 100644 --- a/src/resolveDependencies.ts +++ b/src/resolveDependencies.ts @@ -1,53 +1,53 @@ -import path = require('path') import logger from '@pnpm/logger' -import {deprecationLogger} from './loggers' -import R = require('ramda') -import getNpmTarballUrl from 'get-npm-tarball-url' -import exists = require('path-exists') -import url = require('url') import { PackageFilesResponse, PackageResponse, } from '@pnpm/package-requester' import {Resolution} from '@pnpm/resolver-base' +import { + Dependencies, + PackageManifest, + ReadPackageHook, +} from '@pnpm/types' +import * as dp from 'dependency-path' +import getNpmTarballUrl from 'get-npm-tarball-url' +import fs = require('mz/fs') +import path = require('path') +import exists = require('path-exists') +import { + DependencyShrinkwrap, + ResolvedDependencies, + Shrinkwrap, +} from 'pnpm-shrinkwrap' +import R = require('ramda') +import semver = require('semver') +import url = require('url') import {InstallContext, InstalledPackages} from './api/install' +import depsToSpecs from './depsToSpecs' +import encodePkgId from './encodePkgId' +import getPkgInfoFromShr from './getPkgInfoFromShr' +import getIsInstallable from './install/getIsInstallable' +import {deprecationLogger} from './loggers' +import logStatus from './logging/logInstallStatus' +import memoize from './memoize' +import { + createNodeId, + nodeIdContainsSequence, +} from './nodeIdUtils' import { WantedDependency, } from './types' -import { - ReadPackageHook, - Dependencies, - PackageManifest, -} from '@pnpm/types' -import memoize from './memoize' -import logStatus from './logging/logInstallStatus' -import fs = require('mz/fs') -import * as dp from 'dependency-path' -import { - Shrinkwrap, - DependencyShrinkwrap, - ResolvedDependencies, -} from 'pnpm-shrinkwrap' -import depsToSpecs from './depsToSpecs' -import getIsInstallable from './install/getIsInstallable' -import getPkgInfoFromShr from './getPkgInfoFromShr' -import { - nodeIdContainsSequence, - createNodeId, -} from './nodeIdUtils' -import encodePkgId from './encodePkgId' -import semver = require('semver') const ENGINE_NAME = `${process.platform}-${process.arch}-node-${process.version.split('.')[0]}` -export type PkgAddress = { +export interface PkgAddress { alias: string, nodeId: string, pkgId: string, normalizedPref?: string, // is returned only for root dependencies } -export type InstalledPackage = { +export interface InstalledPackage { id: string, resolution: Resolution, prod: boolean, @@ -96,12 +96,12 @@ export default async function resolveDependencies ( sideEffectsCache: boolean, reinstallForFlatten?: boolean, shamefullyFlatten?: boolean, - } + }, ): Promise { const resolvedDependencies = options.resolvedDependencies || {} const preferedDependencies = options.preferedDependencies || {} const update = options.update && options.currentDepth <= ctx.depth - const pkgAddresses = ( + const pkgAddresses = ( await Promise.all( wantedDependencies .map(async (wantedDependency: WantedDependency) => { @@ -122,23 +122,23 @@ export default async function resolveDependencies ( } return await install(wantedDependency, ctx, { - keypath: options.keypath, - parentNodeId: options.parentNodeId, currentDepth: options.currentDepth, - parentIsInstallable: options.parentIsInstallable, - readPackageHook: options.readPackageHook, hasManifestInShrinkwrap: options.hasManifestInShrinkwrap, - update, + keypath: options.keypath, + parentIsInstallable: options.parentIsInstallable, + parentNodeId: options.parentNodeId, proceed, + readPackageHook: options.readPackageHook, reinstallForFlatten: options.reinstallForFlatten, shamefullyFlatten: options.shamefullyFlatten, sideEffectsCache: options.sideEffectsCache, + update, ...getInfoFromShrinkwrap(ctx.wantedShrinkwrap, reference, wantedDependency.alias, ctx.registry), }) - }) + }), ) ) - .filter(Boolean) + .filter(Boolean) as PkgAddress[] return pkgAddresses } @@ -176,21 +176,21 @@ function getInfoFromShrinkwrap ( if (dependencyShrinkwrap) { const depPath = dp.resolve(shrinkwrap.registry, relDepPath) return { - relDepPath, depPath, dependencyShrinkwrap, + optionalDependencyNames: R.keys(dependencyShrinkwrap.optionalDependencies), pkgId: dependencyShrinkwrap.id || depPath, - shrinkwrapResolution: dependencyShrToResolution(relDepPath, dependencyShrinkwrap, shrinkwrap.registry), + relDepPath, resolvedDependencies: { ...dependencyShrinkwrap.dependencies, ...dependencyShrinkwrap.optionalDependencies, }, - optionalDependencyNames: R.keys(dependencyShrinkwrap.optionalDependencies), + shrinkwrapResolution: dependencyShrToResolution(relDepPath, dependencyShrinkwrap, shrinkwrap.registry), } } else { return { - relDepPath, pkgId: dp.resolve(shrinkwrap.registry, relDepPath), + relDepPath, } } } @@ -198,16 +198,17 @@ function getInfoFromShrinkwrap ( function dependencyShrToResolution ( relDepPath: string, depShr: DependencyShrinkwrap, - registry: string + registry: string, ): Resolution { + // tslint:disable:no-string-literal if (depShr.resolution['type']) { return depShr.resolution as Resolution } if (!depShr.resolution['tarball']) { return { ...depShr.resolution, - tarball: getTarball(), registry: depShr.resolution['registry'] || registry, + tarball: getTarball(), } as Resolution } if (depShr.resolution['tarball'].startsWith('file:')) { @@ -225,6 +226,7 @@ function dependencyShrToResolution ( } return getNpmTarballUrl(parsed['name'], parsed['version'], {registry}) } + // tslint:enable:no-string-literal } async function install ( @@ -249,7 +251,7 @@ async function install ( sideEffectsCache: boolean, reinstallForFlatten?: boolean, shamefullyFlatten?: boolean, - } + }, ): Promise { const keypath = options.keypath || [] const proceed = options.proceed || !options.shrinkwrapResolution || ctx.force || keypath.length <= ctx.depth @@ -271,36 +273,36 @@ async function install ( const dependentId = keypath[keypath.length - 1] const loggedPkg = { - rawSpec: wantedDependency.raw, - name: wantedDependency.alias, dependentId, + name: wantedDependency.alias, + rawSpec: wantedDependency.raw, } logStatus({ - status: 'installing', pkg: loggedPkg, + status: 'installing', }) let pkgResponse!: PackageResponse try { pkgResponse = await ctx.storeController.requestPackage(wantedDependency, { - defaultTag: ctx.defaultTag, - loggedPkg, - update: options.update, - registry, - prefix: ctx.prefix, - shrinkwrapResolution: options.shrinkwrapResolution, currentPkgId: options.pkgId, - verifyStoreIntegrity: ctx.verifyStoreInegrity, + defaultTag: ctx.defaultTag, downloadPriority: -options.currentDepth, + loggedPkg, preferredVersions: ctx.preferredVersions, + prefix: ctx.prefix, + registry, + shrinkwrapResolution: options.shrinkwrapResolution, + sideEffectsCache: options.sideEffectsCache, skipFetch: ctx.dryRun, - sideEffectsCache: options.sideEffectsCache + update: options.update, + verifyStoreIntegrity: ctx.verifyStoreInegrity, }) } catch (err) { if (wantedDependency.optional) { logger.warn({ - message: `Skipping optional dependency ${wantedDependency.raw}. ${err.toString()}`, err, + message: `Skipping optional dependency ${wantedDependency.raw}. ${err.toString()}`, }) return null } @@ -310,23 +312,23 @@ async function install ( pkgResponse.body.id = encodePkgId(pkgResponse.body.id) if (pkgResponse.body.isLocal) { - const pkg = pkgResponse.body.manifest || await pkgResponse['fetchingManifest'] + const manifest = pkgResponse.body.manifest || await pkgResponse['fetchingManifest'] // tslint:disable-line:no-string-literal if (options.currentDepth > 0) { logger.warn(`Ignoring file dependency because it is not a root dependency ${wantedDependency}`) } else { ctx.localPackages.push({ - alias: wantedDependency.alias || pkg.name, - id: pkgResponse.body.id, - specRaw: wantedDependency.raw, - name: pkg.name, - version: pkg.version, + alias: wantedDependency.alias || manifest.name, dev: wantedDependency.dev, + id: pkgResponse.body.id, + name: manifest.name, + normalizedPref: pkgResponse.body.normalizedPref, optional: wantedDependency.optional, resolution: pkgResponse.body.resolution, - normalizedPref: pkgResponse.body.normalizedPref, + specRaw: wantedDependency.raw, + version: manifest.version, }) } - logStatus({status: 'downloaded_manifest', pkgId: pkgResponse.body.id, pkgVersion: pkg.version}) + logStatus({status: 'downloaded_manifest', pkgId: pkgResponse.body.id, pkgVersion: manifest.version}) return null } @@ -343,11 +345,11 @@ async function install ( useManifestInfoFromShrinkwrap = true pkg = Object.assign( getPkgInfoFromShr(options.relDepPath, options.dependencyShrinkwrap), - options.dependencyShrinkwrap + options.dependencyShrinkwrap, ) if (pkg.peerDependencies) { const deps = pkg.dependencies || {} - R.keys(pkg.peerDependencies).forEach(peer => { + R.keys(pkg.peerDependencies).forEach((peer) => { delete deps[peer] if (options.resolvedDependencies) { delete options.resolvedDependencies[peer] @@ -355,27 +357,31 @@ async function install ( }) } } else { + // tslint:disable:no-string-literal try { pkg = options.readPackageHook ? options.readPackageHook(pkgResponse.body['manifest'] || await pkgResponse['fetchingManifest']) : pkgResponse.body['manifest'] || await pkgResponse['fetchingManifest'] } catch (err) { + // tslint:disable:no-empty // avoiding unhandled promise rejections if (pkgResponse['finishing']) pkgResponse['finishing'].catch((err: Error) => {}) if (pkgResponse['fetchingFiles']) pkgResponse['fetchingFiles'].catch((err: Error) => {}) + // tslint:enable:no-empty throw err } + // tslint:enable:no-string-literal } if (options.currentDepth === 0 && pkgResponse.body.latest && pkgResponse.body.latest !== pkg.version) { ctx.outdatedPkgs[pkgResponse.body.id] = pkgResponse.body.latest } if (pkg.deprecated) { deprecationLogger.warn({ - pkgName: pkg.name, - pkgVersion: pkg.version, - pkgId: pkgResponse.body.id, deprecated: pkg.deprecated, depth: options.currentDepth, + pkgId: pkgResponse.body.id, + pkgName: pkg.name, + pkgVersion: pkg.version, }) } @@ -387,11 +393,11 @@ async function install ( const currentIsInstallable = ( ctx.force || await getIsInstallable(pkgResponse.body.id, pkg, { - nodeId, - installs: ctx.installs, - optional: wantedDependency.optional, engineStrict: ctx.engineStrict, + installs: ctx.installs, + nodeId, nodeVersion: ctx.nodeVersion, + optional: wantedDependency.optional, pnpmVersion: ctx.pnpmVersion, }) ) @@ -410,67 +416,67 @@ async function install ( const peerDependencies = peerDependenciesWithoutOwn(pkg) ctx.installs[pkgResponse.body.id] = { - id: pkgResponse.body.id, - resolution: pkgResponse.body.resolution, - optional: wantedDependency.optional, - name: pkg.name, - version: pkg.version, - prod: !wantedDependency.dev && !wantedDependency.optional, - dev: wantedDependency.dev, - fetchingFiles: pkgResponse['fetchingFiles'], - finishing: pkgResponse['finishing'], - path: pkgResponse.body.inStoreLocation, - specRaw: wantedDependency.raw, - peerDependencies: peerDependencies || {}, - optionalDependencies: new Set(R.keys(pkg.optionalDependencies)), - hasBundledDependencies: !!(pkg.bundledDependencies || pkg.bundleDependencies), additionalInfo: { - deprecated: pkg.deprecated, - peerDependencies, bundleDependencies: pkg.bundleDependencies, bundledDependencies: pkg.bundledDependencies, - engines: pkg.engines, cpu: pkg.cpu, + deprecated: pkg.deprecated, + engines: pkg.engines, os: pkg.os, + peerDependencies, }, + dev: wantedDependency.dev, engineCache: !ctx.force && pkgResponse.body.cacheByEngine && pkgResponse.body.cacheByEngine[ENGINE_NAME], + fetchingFiles: pkgResponse['fetchingFiles'], // tslint:disable-line:no-string-literal + finishing: pkgResponse['finishing'], // tslint:disable-line:no-string-literal + hasBundledDependencies: !!(pkg.bundledDependencies || pkg.bundleDependencies), + id: pkgResponse.body.id, + name: pkg.name, + optional: wantedDependency.optional, + optionalDependencies: new Set(R.keys(pkg.optionalDependencies)), + path: pkgResponse.body.inStoreLocation, + peerDependencies: peerDependencies || {}, + prod: !wantedDependency.dev && !wantedDependency.optional, + resolution: pkgResponse.body.resolution, + specRaw: wantedDependency.raw, + version: pkg.version, } const children = await resolveDependenciesOfPackage( pkg, ctx, { - parentIsInstallable: installable, currentDepth: options.currentDepth + 1, - parentNodeId: nodeId, + hasManifestInShrinkwrap: options.hasManifestInShrinkwrap, keypath: options.keypath.concat([ pkgResponse.body.id ]), - resolvedDependencies: pkgResponse.body.updated - ? undefined - : options.resolvedDependencies, + optionalDependencyNames: options.optionalDependencyNames, + parentIsInstallable: installable, + parentNodeId: nodeId, preferedDependencies: pkgResponse.body.updated ? options.resolvedDependencies : undefined, - optionalDependencyNames: options.optionalDependencyNames, - update: options.update, readPackageHook: options.readPackageHook, - hasManifestInShrinkwrap: options.hasManifestInShrinkwrap, - useManifestInfoFromShrinkwrap, - sideEffectsCache: options.sideEffectsCache, reinstallForFlatten: options.reinstallForFlatten, + resolvedDependencies: pkgResponse.body.updated + ? undefined + : options.resolvedDependencies, shamefullyFlatten: options.shamefullyFlatten, - } + sideEffectsCache: options.sideEffectsCache, + update: options.update, + useManifestInfoFromShrinkwrap, + }, ) - ctx.childrenByParentId[pkgResponse.body.id] = children.map(child => ({ + ctx.childrenByParentId[pkgResponse.body.id] = children.map((child) => ({ alias: child.alias, pkgId: child.pkgId, })) ctx.tree[nodeId] = { - pkg: ctx.installs[pkgResponse.body.id], - children: children.reduce((children, child) => { - children[child.alias] = child.nodeId - return children + children: children.reduce((chn, child) => { + chn[child.alias] = child.nodeId + return chn }, {}), depth: options.currentDepth, installable, + pkg: ctx.installs[pkgResponse.body.id], } } else { ctx.installs[pkgResponse.body.id].prod = ctx.installs[pkgResponse.body.id].prod || !wantedDependency.dev && !wantedDependency.optional @@ -479,10 +485,10 @@ async function install ( ctx.nodesToBuild.push({ alias: wantedDependency.alias || pkg.name, - nodeId, - pkg: ctx.installs[pkgResponse.body.id], depth: options.currentDepth, installable, + nodeId, + pkg: ctx.installs[pkgResponse.body.id], }) } // we need this for saving to package.json @@ -495,8 +501,8 @@ async function install ( return { alias: wantedDependency.alias || pkg.name, nodeId, - pkgId: pkgResponse.body.id, normalizedPref: options.currentDepth === 0 ? pkgResponse.body.normalizedPref : undefined, + pkgId: pkgResponse.body.id, } } @@ -510,10 +516,10 @@ function getScope (pkgName: string): string | null { function peerDependenciesWithoutOwn (pkg: PackageManifest) { if (!pkg.peerDependencies) return pkg.peerDependencies const ownDeps = new Set( - R.keys(pkg.dependencies).concat(R.keys(pkg.optionalDependencies)) + R.keys(pkg.dependencies).concat(R.keys(pkg.optionalDependencies)), ) const result = {} - for (let peer of R.keys(pkg.peerDependencies)) { + for (const peer of R.keys(pkg.peerDependencies)) { if (ownDeps.has(peer)) continue result[peer] = pkg.peerDependencies[peer] } @@ -544,7 +550,7 @@ async function resolveDependenciesOfPackage ( sideEffectsCache: boolean, reinstallForFlatten?: boolean, shamefullyFlatten?: boolean, - } + }, ): Promise { const bundledDeps = pkg.bundleDependencies || pkg.bundledDependencies || [] @@ -554,15 +560,15 @@ async function resolveDependenciesOfPackage ( { devDependencies: {}, optionalDependencies: pkg.optionalDependencies || {}, - } + }, ) if (opts.hasManifestInShrinkwrap && !deps.length && opts.resolvedDependencies && opts.useManifestInfoFromShrinkwrap) { const optionalDependencyNames = opts.optionalDependencyNames || [] deps = R.keys(opts.resolvedDependencies) - .map(depName => ({ + .map((depName) => ({ alias: depName, optional: optionalDependencyNames.indexOf(depName) !== -1, - })) + } as WantedDependency)) } return await resolveDependencies(ctx, deps, opts) @@ -570,7 +576,7 @@ async function resolveDependenciesOfPackage ( function getNotBundledDeps (bundledDeps: string[], deps: Dependencies) { return Object.keys(deps) - .filter(depName => bundledDeps.indexOf(depName) === -1) + .filter((depName) => bundledDeps.indexOf(depName) === -1) .reduce((notBundledDeps, depName) => { notBundledDeps[depName] = deps[depName] return notBundledDeps diff --git a/src/runScript.ts b/src/runScript.ts index 9c707183b6..821f1f4597 100644 --- a/src/runScript.ts +++ b/src/runScript.ts @@ -1,7 +1,7 @@ import logger from '@pnpm/logger' -import path = require('path') import byline = require('byline') import spawn = require('cross-spawn') +import path = require('path') import PATH = require('path-name') import {lifecycleLogger} from './loggers' @@ -14,9 +14,9 @@ export default function runScript ( cwd: string, pkgId: string, userAgent: string, - } + }, ) { - opts = Object.assign({log: (() => {})}, opts) + opts = Object.assign({log: (() => {})}, opts) // tslint:disable-line:no-empty args = args || [] const script = `${command}${args.length ? ' ' + args.join(' ') : ''}` if (script) scriptLogger.debug(`runscript ${script}`) @@ -24,36 +24,36 @@ export default function runScript ( return new Promise((resolve, reject) => { const proc = spawn(command, args, { cwd: opts.cwd, - env: createEnv(opts) + env: createEnv(opts), }) const scriptName = args[args.length - 1] proc.on('error', reject) byline(proc.stdout).on('data', (line: Buffer) => lifecycleLogger.info({ - script: scriptName, line: line.toString(), pkgId: opts.pkgId, + script: scriptName, })) byline(proc.stderr).on('data', (line: Buffer) => lifecycleLogger.error({ - script: scriptName, line: line.toString(), pkgId: opts.pkgId, + script: scriptName, })) proc.on('close', (code: number) => { if (code > 0) { lifecycleLogger.error({ + exitCode: code, pkgId: opts.pkgId, script: scriptName, - exitCode: code, }) return reject(new Error('Exit code ' + code)) } lifecycleLogger.info({ + exitCode: code, pkgId: opts.pkgId, script: scriptName, - exitCode: code, }) return resolve() }) @@ -64,18 +64,18 @@ function createEnv ( opts: { cwd: string, userAgent?: string, - } + }, ) { const env = Object.create(process.env) env[PATH] = [ path.join(opts.cwd, 'node_modules', '.bin'), path.dirname(process.execPath), - process.env[PATH] + process.env[PATH], ].join(path.delimiter) if (opts.userAgent) { - env['npm_config_user_agent'] = opts.userAgent + env['npm_config_user_agent'] = opts.userAgent // tslint:disable-line:no-string-literal } return env diff --git a/src/safeIsInnerLink.ts b/src/safeIsInnerLink.ts index bb0ea86037..9a98ab7405 100644 --- a/src/safeIsInnerLink.ts +++ b/src/safeIsInnerLink.ts @@ -1,16 +1,16 @@ import logger from '@pnpm/logger' -import path = require('path') import isInnerLink = require('is-inner-link') -import fs = require('mz/fs') -import mkdirp = require('mkdirp-promise') import isSubdir = require('is-subdir') +import mkdirp = require('mkdirp-promise') +import fs = require('mz/fs') +import path = require('path') export default async function safeIsInnerLink ( modules: string, depName: string, opts: { storePath: string, - } + }, ): Promise { try { const link = await isInnerLink(modules, depName) diff --git a/src/save.ts b/src/save.ts index a9eb2de0a9..d64aed74c2 100644 --- a/src/save.ts +++ b/src/save.ts @@ -1,37 +1,37 @@ +import {PackageJson} from '@pnpm/types' import loadJsonFile = require('load-json-file') import writePkg = require('write-pkg') import {DependenciesType, dependenciesTypes} from './getSaveType' -import {PackageJson} from '@pnpm/types' import {packageJsonLogger} from './loggers' export default async function save ( pkgJsonPath: string, - packageSpecs: ({ + packageSpecs: Array<{ name: string, pref: string, - })[], - saveType?: DependenciesType + }>, + saveType?: DependenciesType, ): Promise { // Read the latest version of package.json to avoid accidental overwriting let packageJson: object try { packageJson = await loadJsonFile(pkgJsonPath) } catch (err) { - if (err['code'] !== 'ENOENT') throw err + if (err['code'] !== 'ENOENT') throw err // tslint:disable-line:no-string-literal packageJson = {} } if (saveType) { packageJson[saveType] = packageJson[saveType] || {} - packageSpecs.forEach(dependency => { + packageSpecs.forEach((dependency) => { packageJson[saveType][dependency.name] = dependency.pref - dependenciesTypes.filter(deptype => deptype !== saveType).forEach(deptype => { + dependenciesTypes.filter((deptype) => deptype !== saveType).forEach((deptype) => { if (packageJson[deptype]) { delete packageJson[deptype][dependency.name] } }) }) } else { - packageSpecs.forEach(dependency => { + packageSpecs.forEach((dependency) => { const usedDepType = guessDependencyType(dependency.name, packageJson as PackageJson) || 'dependencies' packageJson[usedDepType] = packageJson[usedDepType] || {} packageJson[usedDepType][dependency.name] = dependency.pref @@ -45,5 +45,5 @@ export default async function save ( function guessDependencyType (depName: string, pkg: PackageJson): DependenciesType | undefined { return dependenciesTypes - .find(deptype => Boolean(pkg[deptype] && pkg[deptype]![depName])) + .find((deptype) => Boolean(pkg[deptype] && pkg[deptype]![depName])) } diff --git a/src/types.ts b/src/types.ts index 8afb143e2b..198556670d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,4 @@ +import {LogBase} from '@pnpm/logger' import { Dependencies, PackageBin, @@ -5,10 +6,9 @@ import { PnpmOptions, StrictPnpmOptions, } from '@pnpm/types' -import {LogBase} from '@pnpm/logger' import {StoreController} from 'package-store' -export type WantedDependency = { +export interface WantedDependency { alias?: string, pref: string, // package reference dev: boolean, @@ -17,12 +17,12 @@ export type WantedDependency = { } export type SupiOptions = PnpmOptions & { - storeController: StoreController + storeController: StoreController, } export type StrictSupiOptions = StrictPnpmOptions & { storeController: StoreController - pending?: boolean + pending?: boolean, } export type ReporterFunction = (logObj: LogBase) => void diff --git a/test/api.ts b/test/api.ts index f64a32c881..c0cc3e7eed 100644 --- a/test/api.ts +++ b/test/api.ts @@ -1,8 +1,8 @@ -import test = require('tape') import * as pnpm from 'supi' +import test = require('tape') import {testDefaults} from './utils' -test('API', t => { +test('API', (t) => { t.equal(typeof pnpm.install, 'function', 'exports install()') t.equal(typeof pnpm.installPkgs, 'function', 'exports installPkgs()') t.equal(typeof pnpm.uninstall, 'function', 'exports uninstall()') diff --git a/test/breakingChanges.ts b/test/breakingChanges.ts index c39cc24ed3..1db756a0a2 100644 --- a/test/breakingChanges.ts +++ b/test/breakingChanges.ts @@ -1,14 +1,14 @@ +import isCI = require('is-ci') +import mkdirp = require('mkdirp-promise') +import fs = require('mz/fs') +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import fs = require('mz/fs') -import mkdirp = require('mkdirp-promise') -import isCI = require('is-ci') import {prepare, testDefaults} from './utils' -import {installPkgs, install} from 'supi' const test = promisifyTape(tape) -test('fail on non-compatible node_modules', async t => { +test('fail on non-compatible node_modules', async (t) => { const project = prepare(t) const opts = await testDefaults() @@ -22,7 +22,7 @@ test('fail on non-compatible node_modules', async t => { } }) -test("don't fail on non-compatible node_modules when forced", async t => { +test("don't fail on non-compatible node_modules when forced", async (t) => { const project = prepare(t) const opts = await testDefaults({force: true}) @@ -33,7 +33,7 @@ test("don't fail on non-compatible node_modules when forced", async t => { t.pass('install did not fail') }) -test('fail on non-compatible node_modules when forced with a named installation', async t => { +test('fail on non-compatible node_modules when forced with a named installation', async (t) => { const project = prepare(t) const opts = await testDefaults({force: true}) @@ -47,7 +47,7 @@ test('fail on non-compatible node_modules when forced with a named installation' } }) -test("don't fail on non-compatible store when forced", async t => { +test("don't fail on non-compatible store when forced", async (t) => { const project = prepare(t) const opts = await testDefaults({force: true}) @@ -58,7 +58,7 @@ test("don't fail on non-compatible store when forced", async t => { t.pass('install did not fail') }) -test('fail on non-compatible store when forced during named installation', async t => { +test('fail on non-compatible store when forced during named installation', async (t) => { const project = prepare(t) const opts = await testDefaults({force: true}) @@ -77,7 +77,7 @@ async function saveModulesYaml (pnpmVersion: string, storePath: string) { await fs.writeFile('node_modules/.modules.yaml', `packageManager: pnpm@${pnpmVersion}\nstore: ${storePath}\nindependentLeaves: false`) } -test('fail on non-compatible shrinkwrap.yaml', async t => { +test('fail on non-compatible shrinkwrap.yaml', async (t) => { if (isCI) { t.skip('this test will always fail on CI servers') return @@ -94,7 +94,7 @@ test('fail on non-compatible shrinkwrap.yaml', async t => { } }) -test("don't fail on non-compatible shrinkwrap.yaml when forced", async t => { +test("don't fail on non-compatible shrinkwrap.yaml when forced", async (t) => { const project = prepare(t) await fs.writeFile('shrinkwrap.yaml', '') diff --git a/test/cache.ts b/test/cache.ts index 33166371ae..c24d5ea5fd 100644 --- a/test/cache.ts +++ b/test/cache.ts @@ -1,17 +1,17 @@ -import {installPkgs, install} from 'supi' -import { - prepare, - addDistTag, - testDefaults, -} from './utils' +import path = require('path') +import exists = require('path-exists') +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import exists = require('path-exists') -import path = require('path') +import { + addDistTag, + prepare, + testDefaults, +} from './utils' const test = promisifyTape(tape) -test('should fail to update when requests are cached', async function (t) { +test('should fail to update when requests are cached', async (t) => { const project = prepare(t) const metaCache = new Map() diff --git a/test/index.ts b/test/index.ts index 30f8a728c6..694a184f0d 100644 --- a/test/index.ts +++ b/test/index.ts @@ -1,14 +1,14 @@ import './api' -import './install' -import './uninstall' -import './link' -import './prune' -import './cache' import './breakingChanges' -import './storeStatus' -import './shrinkwrap' +import './cache' +import './install' +import './link' import './offline' -import './unlink' -import './storePrune' -import './rebuild' import './packageImportMethods' +import './prune' +import './rebuild' +import './shrinkwrap' +import './storePrune' +import './storeStatus' +import './uninstall' +import './unlink' diff --git a/test/install/aliases.ts b/test/install/aliases.ts index fbb6da381c..a5826045b6 100644 --- a/test/install/aliases.ts +++ b/test/install/aliases.ts @@ -1,15 +1,15 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' -import { - prepare, - addDistTag, - testDefaults, -} from '../utils' import { install, installPkgs, uninstall, } from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import { + addDistTag, + prepare, + testDefaults, +} from '../utils' const test = promisifyTape(tape) test.only = promisifyTape(tape.only) @@ -57,7 +57,7 @@ test('installing aliased dependency', async (t: tape.Test) => { }, 'correct shrinkwrap.yaml') }) -test('aliased dependency w/o version spec, with custom tag config', async function (t) { +test('aliased dependency w/o version spec, with custom tag config', async (t) => { const project = prepare(t) const tag = 'beta' diff --git a/test/install/auth.ts b/test/install/auth.ts index d827d2c86e..554eb25a70 100644 --- a/test/install/auth.ts +++ b/test/install/auth.ts @@ -1,18 +1,18 @@ +import RegClient = require('anonymous-npm-registry-client') +import path = require('path') +import registryMock = require('pnpm-registry-mock') +import rimraf = require('rimraf-then') +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import path = require('path') import { prepare, testDefaults, } from '../utils' -import {installPkgs, install} from 'supi' -import registryMock = require('pnpm-registry-mock') -import RegClient = require('anonymous-npm-registry-client') -import rimraf = require('rimraf-then') const test = promisifyTape(tape) -test('a package that need authentication', async function (t: tape.Test) { +test('a package that need authentication', async (t: tape.Test) => { const project = prepare(t) const client = new RegClient() @@ -20,16 +20,16 @@ test('a package that need authentication', async function (t: tape.Test) { const data = await new Promise((resolve, reject) => { client.adduser('http://localhost:4873', { auth: { - username: 'foo', - password: 'bar', email: 'foo@bar.com', - } - }, (err: Error, data: Object) => err ? reject(err) : resolve(data)) + password: 'bar', + username: 'foo', + }, + }, (err: Error, d: object) => err ? reject(err) : resolve(d)) }) let rawNpmConfig = { - registry: 'http://localhost:4873/', - '//localhost:4873/:_authToken': data['token'], + '//localhost:4873/:_authToken': data.token, + 'registry': 'http://localhost:4873/', } await installPkgs(['needs-auth'], await testDefaults({}, { rawNpmConfig, @@ -47,12 +47,12 @@ test('a package that need authentication', async function (t: tape.Test) { await rimraf(path.join('..', '.store')) rawNpmConfig = { - registry: 'https://registry.npmjs.org/', - '//localhost:4873/:_authToken': data['token'], + '//localhost:4873/:_authToken': data.token, + 'registry': 'https://registry.npmjs.org/', } await installPkgs(['needs-auth'], await testDefaults({}, { - registry: 'https://registry.npmjs.org/', rawNpmConfig, + registry: 'https://registry.npmjs.org/', }, { rawNpmConfig, })) @@ -60,7 +60,7 @@ test('a package that need authentication', async function (t: tape.Test) { await project.has('needs-auth') }) -test('a package that need authentication, legacy way', async function (t: tape.Test) { +test('a package that need authentication, legacy way', async (t: tape.Test) => { const project = prepare(t) const client = new RegClient() @@ -68,17 +68,17 @@ test('a package that need authentication, legacy way', async function (t: tape.T const data = await new Promise((resolve, reject) => { client.adduser('http://localhost:4873', { auth: { - username: 'foo', - password: 'bar', email: 'foo@bar.com', - } - }, (err: Error, data: Object) => err ? reject(err) : resolve(data)) + password: 'bar', + username: 'foo', + }, + }, (err: Error, d: object) => err ? reject(err) : resolve(d)) }) const rawNpmConfig = { '_auth': 'Zm9vOmJhcg==', // base64 encoded foo:bar 'always-auth': true, - registry: 'http://localhost:4873', + 'registry': 'http://localhost:4873', } await installPkgs(['needs-auth'], await testDefaults({}, { rawNpmConfig, @@ -91,7 +91,7 @@ test('a package that need authentication, legacy way', async function (t: tape.T t.ok(typeof m === 'function', 'needs-auth() is available') }) -test('a scoped package that need authentication specific to scope', async function (t: tape.Test) { +test('a scoped package that need authentication specific to scope', async (t: tape.Test) => { const project = prepare(t) const client = new RegClient() @@ -99,21 +99,21 @@ test('a scoped package that need authentication specific to scope', async functi const data = await new Promise((resolve, reject) => { client.adduser('http://localhost:4873', { auth: { - username: 'foo', - password: 'bar', email: 'foo@bar.com', - } - }, (err: Error, data: Object) => err ? reject(err) : resolve(data)) + password: 'bar', + username: 'foo', + }, + }, (err: Error, d: object) => err ? reject(err) : resolve(d)) }) const rawNpmConfig = { - registry: 'https://registry.npmjs.org/', + '//localhost:4873/:_authToken': data.token, '@private:registry': 'http://localhost:4873/', - '//localhost:4873/:_authToken': data['token'], + 'registry': 'https://registry.npmjs.org/', } let opts = await testDefaults({}, { - registry: 'https://registry.npmjs.org/', rawNpmConfig, + registry: 'https://registry.npmjs.org/', }, { rawNpmConfig, }) @@ -127,8 +127,8 @@ test('a scoped package that need authentication specific to scope', async functi // Recreating options to have a new storeController with clean cache opts = await testDefaults({}, { - registry: 'https://registry.npmjs.org/', rawNpmConfig, + registry: 'https://registry.npmjs.org/', }, { rawNpmConfig, }) @@ -137,7 +137,7 @@ test('a scoped package that need authentication specific to scope', async functi await project.has('@private/foo') }) -test('a package that need authentication reuses authorization tokens for tarball fetching', async function (t: tape.Test) { +test('a package that need authentication reuses authorization tokens for tarball fetching', async (t: tape.Test) => { const project = prepare(t) const client = new RegClient() @@ -145,23 +145,23 @@ test('a package that need authentication reuses authorization tokens for tarball const data = await new Promise((resolve, reject) => { client.adduser('http://localhost:4873', { auth: { - username: 'foo', - password: 'bar', email: 'foo@bar.com', - } - }, (err: Error, data: Object) => err ? reject(err) : resolve(data)) + password: 'bar', + username: 'foo', + }, + }, (err: Error, d: object) => err ? reject(err) : resolve(d)) }) const rawNpmConfig = { - registry: 'http://127.0.0.1:4873', - '//127.0.0.1:4873/:_authToken': data['token'], + '//127.0.0.1:4873/:_authToken': data.token, '//127.0.0.1:4873/:always-auth': true, + 'registry': 'http://127.0.0.1:4873', } await installPkgs(['needs-auth'], await testDefaults({ registry: 'http://127.0.0.1:4873', }, { - registry: 'http://127.0.0.1:4873', rawNpmConfig, + registry: 'http://127.0.0.1:4873', }, { rawNpmConfig, })) @@ -171,7 +171,7 @@ test('a package that need authentication reuses authorization tokens for tarball t.ok(typeof m === 'function', 'needs-auth() is available') }) -test('a package that need authentication reuses authorization tokens for tarball fetching when meta info is cached', async function (t: tape.Test) { +test('a package that need authentication reuses authorization tokens for tarball fetching when meta info is cached', async (t: tape.Test) => { const project = prepare(t) const client = new RegClient() @@ -179,23 +179,23 @@ test('a package that need authentication reuses authorization tokens for tarball const data = await new Promise((resolve, reject) => { client.adduser('http://localhost:4873', { auth: { - username: 'foo', - password: 'bar', email: 'foo@bar.com', - } - }, (err: Error, data: Object) => err ? reject(err) : resolve(data)) + password: 'bar', + username: 'foo', + }, + }, (err: Error, d: object) => err ? reject(err) : resolve(d)) }) const rawNpmConfig = { - registry: 'http://127.0.0.1:4873', - '//127.0.0.1:4873/:_authToken': data['token'], + '//127.0.0.1:4873/:_authToken': data.token, '//127.0.0.1:4873/:always-auth': true, + 'registry': 'http://127.0.0.1:4873', } let opts = await testDefaults({ registry: 'http://127.0.0.1:4873', }, { - registry: 'http://127.0.0.1:4873', rawNpmConfig, + registry: 'http://127.0.0.1:4873', }, { rawNpmConfig, }) @@ -210,8 +210,8 @@ test('a package that need authentication reuses authorization tokens for tarball opts = await testDefaults({ registry: 'http://127.0.0.1:4873', }, { - registry: 'http://127.0.0.1:4873', rawNpmConfig, + registry: 'http://127.0.0.1:4873', }, { rawNpmConfig, }) diff --git a/test/install/dedupe.ts b/test/install/dedupe.ts index bd2babc572..abecea8c01 100644 --- a/test/install/dedupe.ts +++ b/test/install/dedupe.ts @@ -1,7 +1,7 @@ +import {addDistTag} from 'pnpm-registry-mock' +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import {install, installPkgs} from 'supi' -import {addDistTag} from 'pnpm-registry-mock' import { prepare, testDefaults, diff --git a/test/install/fromRepo.ts b/test/install/fromRepo.ts index f8cbd40c90..d26b03c08d 100644 --- a/test/install/fromRepo.ts +++ b/test/install/fromRepo.ts @@ -1,15 +1,15 @@ -import path = require('path') -import tape = require('tape') -import promisifyTape from 'tape-promise' import isCI = require('is-ci') -import readPkg = require('read-pkg') +import path = require('path') import exists = require('path-exists') +import readPkg = require('read-pkg') import sinon = require('sinon') import { install, installPkgs, RootLog, } from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { prepare, testDefaults, @@ -29,7 +29,7 @@ test('from a github repo', async (t: tape.Test) => { t.deepEqual(pkgJson.dependencies, {'is-negative': 'github:kevva/is-negative'}, 'has been added to dependencies in package.json') }) -test('from a github repo with different name via named installation', async function (t: tape.Test) { +test('from a github repo with different name via named installation', async (t: tape.Test) => { const project = prepare(t) const reporter = sinon.spy() @@ -38,16 +38,16 @@ test('from a github repo with different name via named installation', async func const m = project.requireModule('say-hi') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'prod', name: 'say-hi', realName: 'hi', version: '1.0.0', - dependencyType: 'prod', }, - }), 'adding to root logged with real name and alias name') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'adding to root logged with real name and alias name') t.equal(m, 'Hi', 'dep is available') @@ -64,11 +64,11 @@ test('from a github repo with different name via named installation', async func }) // This used to fail. Maybe won't be needed once api/install.ts gets refactored and covered with dedicated unit tests -test('from a github repo with different name', async function (t: tape.Test) { +test('from a github repo with different name', async (t: tape.Test) => { const project = prepare(t, { dependencies: { - 'say-hi': 'github:zkochan/hi#4cdebec76b7b9d1f6e219e06c42d92a6b8ea60cd' - } + 'say-hi': 'github:zkochan/hi#4cdebec76b7b9d1f6e219e06c42d92a6b8ea60cd', + }, }) const reporter = sinon.spy() @@ -77,16 +77,16 @@ test('from a github repo with different name', async function (t: tape.Test) { const m = project.requireModule('say-hi') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'prod', name: 'say-hi', realName: 'hi', version: '1.0.0', - dependencyType: 'prod', }, - }), 'adding to root logged with real name and alias name') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'adding to root logged with real name and alias name') t.equal(m, 'Hi', 'dep is available') @@ -102,7 +102,7 @@ test('from a github repo with different name', async function (t: tape.Test) { await project.isExecutable('.bin/szia') }) -test('a subdependency is from a github repo with different name', async function (t: tape.Test) { +test('a subdependency is from a github repo with different name', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['has-aliased-git-dependency'], await testDefaults()) diff --git a/test/install/fromTarball.ts b/test/install/fromTarball.ts index 619d81ddc4..6e5af1948f 100644 --- a/test/install/fromTarball.ts +++ b/test/install/fromTarball.ts @@ -1,7 +1,7 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' import readPkg = require('read-pkg') import {installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { prepare, testDefaults, @@ -9,7 +9,7 @@ import { const test = promisifyTape(tape) -test('tarball from npm registry', async function (t) { +test('tarball from npm registry', async (t) => { const project = prepare(t) await installPkgs(['http://registry.npmjs.org/is-array/-/is-array-1.0.1.tgz'], await testDefaults()) @@ -23,7 +23,7 @@ test('tarball from npm registry', async function (t) { t.deepEqual(pkgJson.dependencies, {'is-array': 'http://registry.npmjs.org/is-array/-/is-array-1.0.1.tgz'}, 'has been added to dependencies in package.json') }) -test('tarball not from npm registry', async function (t) { +test('tarball not from npm registry', async (t) => { const project = prepare(t) await installPkgs(['https://github.com/hegemonic/taffydb/tarball/master'], await testDefaults()) @@ -34,7 +34,7 @@ test('tarball not from npm registry', async function (t) { await project.storeHas('github.com/hegemonic/taffydb/tarball/master') }) -test('tarballs from GitHub (is-negative)', async function (t) { +test('tarballs from GitHub (is-negative)', async (t) => { const project = prepare(t) await installPkgs(['is-negative@https://github.com/kevva/is-negative/archive/1d7e288222b53a0cab90a331f1865220ec29560c.tar.gz'], await testDefaults()) diff --git a/test/install/global.ts b/test/install/global.ts index 6f7bb9c4cf..903f9df1aa 100644 --- a/test/install/global.ts +++ b/test/install/global.ts @@ -1,19 +1,19 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' import path = require('path') import readPkg = require('read-pkg') +import {installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { + addDistTag, prepare, testDefaults, - addDistTag, } from '../utils' -import {installPkgs} from 'supi' const test = promisifyTape(tape) const LAYOUT_VERSION = '1' -test('global installation', async function (t) { +test('global installation', async (t) => { prepare(t) const globalPrefix = path.resolve('..', 'global') const opts = await testDefaults({global: true, prefix: globalPrefix}) @@ -30,7 +30,7 @@ test('global installation', async function (t) { t.ok(typeof isNegative === 'function', 'isNegative() is available') }) -test('always install latest when doing global installation without spec', async function (t: tape.Test) { +test('always install latest when doing global installation without spec', async (t: tape.Test) => { await addDistTag('peer-c', '2.0.0', 'latest') const project = prepare(t) diff --git a/test/install/hooks.ts b/test/install/hooks.ts index 0f7d3c6aff..2fb0ec6b30 100644 --- a/test/install/hooks.ts +++ b/test/install/hooks.ts @@ -1,11 +1,11 @@ +import {installPkgs, PackageManifest} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import { - prepare, addDistTag, + prepare, testDefaults, } from '../utils' -import {installPkgs, PackageManifest} from 'supi' const test = promisifyTape(tape) @@ -23,7 +23,7 @@ test('readPackage hook', async (t: tape.Test) => { } await installPkgs(['pkg-with-1-dep'], await testDefaults({ - hooks: {readPackage: readPackageHook} + hooks: {readPackage: readPackageHook}, })) await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0') diff --git a/test/install/independentLeaves.ts b/test/install/independentLeaves.ts index d74d6492b5..283e947148 100644 --- a/test/install/independentLeaves.ts +++ b/test/install/independentLeaves.ts @@ -1,15 +1,15 @@ -import tape = require('tape') import path = require('path') +import {installPkgs} from 'supi' +import tape = require('tape') import promisifyTape from 'tape-promise' import { prepare, testDefaults, } from '../utils' -import {installPkgs} from 'supi' const test = promisifyTape(tape) -test('install with --independent-leaves', async function (t: tape.Test) { +test('install with --independent-leaves', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['rimraf@2.5.1'], await testDefaults({independentLeaves: true})) @@ -18,7 +18,7 @@ test('install with --independent-leaves', async function (t: tape.Test) { await project.isExecutable('.bin/rimraf') }) -test('--independent-leaves throws exception when executed on node_modules installed w/o the option', async function (t: tape.Test) { +test('--independent-leaves throws exception when executed on node_modules installed w/o the option', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['is-positive'], await testDefaults({independentLeaves: false})) @@ -30,7 +30,7 @@ test('--independent-leaves throws exception when executed on node_modules instal } }) -test('--no-independent-leaves throws exception when executed on node_modules installed with --independent-leaves', async function (t: tape.Test) { +test('--no-independent-leaves throws exception when executed on node_modules installed with --independent-leaves', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['is-positive'], await testDefaults({independentLeaves: true})) @@ -42,7 +42,7 @@ test('--no-independent-leaves throws exception when executed on node_modules ins } }) -test('global installation with --independent-leaves', async function (t: tape.Test) { +test('global installation with --independent-leaves', async (t: tape.Test) => { prepare(t) const globalPrefix = path.resolve('..', 'global') const opts = await testDefaults({global: true, prefix: globalPrefix, independentLeaves: true}) diff --git a/test/install/index.ts b/test/install/index.ts index 07280102cc..85cda539a5 100644 --- a/test/install/index.ts +++ b/test/install/index.ts @@ -1,22 +1,22 @@ import './aliases' +import './auth' import './dedupe' +import './fromRepo' +import './fromTarball' +import './global' +import './hooks' +import './independentLeaves' +import './installationChecks' +import './lifecycleScripts' +import './local' import './misc' import './only' -import './lifecycleScripts' import './optionalDependencies' -import './installationChecks' -import './fromTarball' -import './fromRepo' import './peerDependencies' -import './auth' -import './local' -import './updatingPkgJson' -import './global' -import './independentLeaves' -import './store' import './reporting' -import './update' -import './hooks' +import './shamefullyFlatten' import './shrinkwrapOnly' import './sideEffects' -import './shamefullyFlatten' +import './store' +import './update' +import './updatingPkgJson' diff --git a/test/install/installationChecks.ts b/test/install/installationChecks.ts index cb1485f773..b17b02c749 100644 --- a/test/install/installationChecks.ts +++ b/test/install/installationChecks.ts @@ -1,16 +1,16 @@ +import {installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import {installPkgs} from 'supi' import {prepare, testDefaults} from '../utils' const test = promisifyTape(tape) -test('fail if installed package does not support the current engine and engine-strict = true', async function (t) { +test('fail if installed package does not support the current engine and engine-strict = true', async (t) => { const project = prepare(t) try { await installPkgs(['not-compatible-with-any-os'], await testDefaults({ - engineStrict: true + engineStrict: true, })) t.fail() } catch (err) { @@ -19,11 +19,11 @@ test('fail if installed package does not support the current engine and engine-s } }) -test('do not fail if installed package does not support the current engine and engine-strict = false', async function (t: tape.Test) { +test('do not fail if installed package does not support the current engine and engine-strict = false', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['not-compatible-with-any-os'], await testDefaults({ - engineStrict: false + engineStrict: false, })) await project.has('not-compatible-with-any-os') @@ -33,12 +33,12 @@ test('do not fail if installed package does not support the current engine and e t.deepEqual(shr.packages['/not-compatible-with-any-os/1.0.0'].os, ['this-os-does-not-exist'], 'os field added to shrinkwrap.yaml') }) -test('do not fail if installed package requires the node version that was passed in and engine-strict = true', async function (t: tape.Test) { +test('do not fail if installed package requires the node version that was passed in and engine-strict = true', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['for-legacy-node'], await testDefaults({ engineStrict: true, - nodeVersion: '0.10.0' + nodeVersion: '0.10.0', })) await project.has('for-legacy-node') @@ -48,7 +48,7 @@ test('do not fail if installed package requires the node version that was passed t.deepEqual(shr.packages['/for-legacy-node/1.0.0'].engines, { node: '0.10' }, 'engines field added to shrinkwrap.yaml') }) -test('save cpu field to shrinkwrap.yaml', async function (t: tape.Test) { +test('save cpu field to shrinkwrap.yaml', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['has-cpu-specified'], await testDefaults()) @@ -58,11 +58,11 @@ test('save cpu field to shrinkwrap.yaml', async function (t: tape.Test) { t.deepEqual( shr.packages['/has-cpu-specified/1.0.0'].cpu, ['x64', 'ia32'], - 'cpu field added to shrinkwrap.yaml' + 'cpu field added to shrinkwrap.yaml', ) }) -test('engines field is not added to shrinkwrap.yaml when "node": "*" is in "engines" field', async function (t: tape.Test) { +test('engines field is not added to shrinkwrap.yaml when "node": "*" is in "engines" field', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['jsonify@0.0.0'], await testDefaults()) @@ -71,6 +71,6 @@ test('engines field is not added to shrinkwrap.yaml when "node": "*" is in "engi t.notOk( shr.packages['/jsonify/0.0.0'].engines, - 'engines field is not added to shrinkwrap.yaml' + 'engines field is not added to shrinkwrap.yaml', ) }) diff --git a/test/install/lifecycleScripts.ts b/test/install/lifecycleScripts.ts index f650f309a4..1400a09f0c 100644 --- a/test/install/lifecycleScripts.ts +++ b/test/install/lifecycleScripts.ts @@ -1,35 +1,37 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' +import loadJsonFile = require('load-json-file') +import path = require('path') +import exists = require('path-exists') +import PATH = require('path-name') +import rimraf = require('rimraf-then') import sinon = require('sinon') import { - installPkgs, install, + installPkgs, LifecycleLog, } from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { prepare, testDefaults, } from '../utils' -import path = require('path') -import loadJsonFile = require('load-json-file') -import rimraf = require('rimraf-then') -import exists = require('path-exists') -import PATH = require('path-name') const pkgRoot = path.join(__dirname, '..', '..') const pnpmPkg = loadJsonFile.sync(path.join(pkgRoot, 'package.json')) const test = promisifyTape(tape) -test('run pre/postinstall scripts', async function (t: tape.Test) { +test('run pre/postinstall scripts', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pre-and-postinstall-scripts-example'], await testDefaults({saveDev: true})) - const generatedByPreinstall = project.requireModule('pre-and-postinstall-scripts-example/generated-by-preinstall') - t.ok(typeof generatedByPreinstall === 'function', 'generatedByPreinstall() is available') + { + const generatedByPreinstall = project.requireModule('pre-and-postinstall-scripts-example/generated-by-preinstall') + t.ok(typeof generatedByPreinstall === 'function', 'generatedByPreinstall() is available') - const generatedByPostinstall = project.requireModule('pre-and-postinstall-scripts-example/generated-by-postinstall') - t.ok(typeof generatedByPostinstall === 'function', 'generatedByPostinstall() is available') + const generatedByPostinstall = project.requireModule('pre-and-postinstall-scripts-example/generated-by-postinstall') + t.ok(typeof generatedByPostinstall === 'function', 'generatedByPostinstall() is available') + } await rimraf('node_modules') @@ -47,7 +49,7 @@ test('run pre/postinstall scripts', async function (t: tape.Test) { } }) -test('testing that the bins are linked when the package with the bins was already in node_modules', async function (t: tape.Test) { +test('testing that the bins are linked when the package with the bins was already in node_modules', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['hello-world-js-bin'], await testDefaults()) @@ -60,7 +62,7 @@ test('testing that the bins are linked when the package with the bins was alread t.ok(typeof generatedByPostinstall === 'function', 'generatedByPostinstall() is available') }) -test('run install scripts', async function (t) { +test('run install scripts', async (t) => { const project = prepare(t) await installPkgs(['install-script-example'], await testDefaults()) @@ -71,10 +73,10 @@ test('run install scripts', async function (t) { test('run install scripts in the current project', async (t: tape.Test) => { const project = prepare(t, { scripts: { - preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, install: `node -e "process.stdout.write('install')" | json-append output.json`, postinstall: `node -e "process.stdout.write('postinstall')" | json-append output.json`, - } + preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, + }, }) await installPkgs(['json-append@1.1.1'], await testDefaults()) await install(await testDefaults()) @@ -88,10 +90,10 @@ test('run install scripts in the current project when its name is different than const project = prepare(t, { name: 'different-name', scripts: { - preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, install: `node -e "process.stdout.write('install')" | json-append output.json`, postinstall: `node -e "process.stdout.write('postinstall')" | json-append output.json`, - } + preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, + }, }) await installPkgs(['json-append@1.1.1'], await testDefaults()) await install(await testDefaults()) @@ -105,16 +107,16 @@ test('do not run install scripts if unsafePerm is false', async (t: tape.Test) = const project = prepare(t, { name: 'different-name', scripts: { - preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, install: `node -e "process.stdout.write('install')" | json-append output.json`, postinstall: `node -e "process.stdout.write('postinstall')" | json-append output.json`, - } + preinstall: `node -e "process.stdout.write('preinstall')" | json-append output.json`, + }, }) const opts = await testDefaults({ unsafePerm: false }) await installPkgs(['json-append@1.1.1'], opts) await install(opts) - let outputExists = await exists('output.json') + const outputExists = await exists('output.json') t.false(outputExists, 'no output expected as install scripts should not run') }) @@ -122,7 +124,7 @@ test('do not run install scripts if unsafePerm is false', async (t: tape.Test) = test('installation fails if lifecycle script fails', async (t: tape.Test) => { const project = prepare(t, { scripts: { - preinstall: 'exit 1' + preinstall: 'exit 1', }, }) @@ -130,17 +132,17 @@ test('installation fails if lifecycle script fails', async (t: tape.Test) => { await install(await testDefaults()) t.fail('should have failed') } catch (err) { - t.equal(err['code'], 'ELIFECYCLE', 'failed with correct error code') + t.equal(err.code, 'ELIFECYCLE', 'failed with correct error code') } }) // TODO: unskip // For some reason this fails on CI environments -test['skip']('creates env for scripts', async (t: tape.Test) => { +test.skip('creates env for scripts', async (t: tape.Test) => { const project = prepare(t, { scripts: { install: `node -e "process.stdout.write(process.env.INIT_CWD)" | json-append output.json`, - } + }, }) await installPkgs(['json-append@1.1.1'], await testDefaults()) await install(await testDefaults()) @@ -156,7 +158,7 @@ test('INIT_CWD is set correctly', async (t: tape.Test) => { const childEnv = await loadJsonFile(path.resolve('node_modules', 'write-lifecycle-env', 'env.json')) - t.equal(childEnv['INIT_CWD'], process.cwd()) + t.equal(childEnv.INIT_CWD, process.cwd()) }) test("reports child's output", async (t: tape.Test) => { @@ -166,31 +168,31 @@ test("reports child's output", async (t: tape.Test) => { await installPkgs(['count-to-10'], await testDefaults({reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:lifecycle', + t.ok(reporter.calledWithMatch({ level: 'info', line: '1', - pkgId: 'localhost+4873/count-to-10/1.0.0', - })) - t.ok(reporter.calledWithMatch({ name: 'pnpm:lifecycle', + pkgId: 'localhost+4873/count-to-10/1.0.0', + } as LifecycleLog)) + t.ok(reporter.calledWithMatch({ level: 'info', line: '2', - pkgId: 'localhost+4873/count-to-10/1.0.0', - })) - t.ok(reporter.calledWithMatch({ name: 'pnpm:lifecycle', + pkgId: 'localhost+4873/count-to-10/1.0.0', + } as LifecycleLog)) + t.ok(reporter.calledWithMatch({ level: 'error', line: '6', - pkgId: 'localhost+4873/count-to-10/1.0.0', - })) - t.ok(reporter.calledWithMatch({ name: 'pnpm:lifecycle', + pkgId: 'localhost+4873/count-to-10/1.0.0', + } as LifecycleLog)) + t.ok(reporter.calledWithMatch({ exitCode: 0, level: 'info', - script: 'postinstall', + name: 'pnpm:lifecycle', pkgId: 'localhost+4873/count-to-10/1.0.0', - })) + script: 'postinstall', + } as LifecycleLog)) }) test("reports child's close event", async (t: tape.Test) => { @@ -202,13 +204,13 @@ test("reports child's close event", async (t: tape.Test) => { await installPkgs(['failing-postinstall'], await testDefaults({reporter})) t.fail() } catch (err) { - t.ok(reporter.calledWithMatch({ - name: 'pnpm:lifecycle', + t.ok(reporter.calledWithMatch({ exitCode: 1, level: 'error', - script: 'postinstall', + name: 'pnpm:lifecycle', pkgId: 'localhost+4873/failing-postinstall/1.0.0', - })) + script: 'postinstall', + } as LifecycleLog)) } }) diff --git a/test/install/local.ts b/test/install/local.ts index 9da669b4c2..47201c5e83 100644 --- a/test/install/local.ts +++ b/test/install/local.ts @@ -1,25 +1,25 @@ import fs = require('mz/fs') -import tape = require('tape') -import promisifyTape from 'tape-promise' -import normalizePath = require('normalize-path') -import readPkg = require('read-pkg') import ncpCB = require('ncp') -import promisify = require('util.promisify') +import normalizePath = require('normalize-path') import path = require('path') +import readPkg = require('read-pkg') import {install, installPkgs} from 'supi' import symlinkDir = require('symlink-dir') +import tape = require('tape') +import promisifyTape from 'tape-promise' +import promisify = require('util.promisify') import { + local, + pathToLocalPkg, prepare, testDefaults, - pathToLocalPkg, - local, } from '../utils' const ncp = promisify(ncpCB.ncp) const test = promisifyTape(tape) const testOnly = promisifyTape(tape.only) -test('scoped modules from a directory', async function (t: tape.Test) { +test('scoped modules from a directory', async (t: tape.Test) => { const project = prepare(t) await installPkgs([local('local-scoped-pkg')], await testDefaults()) @@ -28,7 +28,7 @@ test('scoped modules from a directory', async function (t: tape.Test) { t.equal(m(), '@scope/local-scoped-pkg', 'localScopedPkg() is available') }) -test('local file', async function (t: tape.Test) { +test('local file', async (t: tape.Test) => { const project = prepare(t) await ncp(pathToLocalPkg('local-pkg'), path.resolve('..', 'local-pkg')) @@ -45,17 +45,17 @@ test('local file', async function (t: tape.Test) { const shr = await project.loadShrinkwrap() t.deepEqual(shr, { - specifiers: expectedSpecs, dependencies: { 'local-pkg': 'file:../local-pkg', }, registry: 'http://localhost:4873/', - shrinkwrapVersion: 3, shrinkwrapMinorVersion: 4, + shrinkwrapVersion: 3, + specifiers: expectedSpecs, }) }) -test('local file via link:', async function (t: tape.Test) { +test('local file via link:', async (t: tape.Test) => { const project = prepare(t) await ncp(pathToLocalPkg('local-pkg'), path.resolve('..', 'local-pkg')) @@ -72,17 +72,17 @@ test('local file via link:', async function (t: tape.Test) { const shr = await project.loadShrinkwrap() t.deepEqual(shr, { - specifiers: expectedSpecs, dependencies: { 'local-pkg': 'link:../local-pkg', }, registry: 'http://localhost:4873/', - shrinkwrapVersion: 3, shrinkwrapMinorVersion: 4, + shrinkwrapVersion: 3, + specifiers: expectedSpecs, }) }) -test('local file with symlinked node_modules', async function (t: tape.Test) { +test('local file with symlinked node_modules', async (t: tape.Test) => { const project = prepare(t) await ncp(pathToLocalPkg('local-pkg'), path.resolve('..', 'local-pkg')) await fs.mkdir(path.join('..', 'node_modules')) @@ -101,17 +101,17 @@ test('local file with symlinked node_modules', async function (t: tape.Test) { const shr = await project.loadShrinkwrap() t.deepEqual(shr, { - specifiers: expectedSpecs, dependencies: { 'local-pkg': 'file:../local-pkg', }, registry: 'http://localhost:4873/', - shrinkwrapVersion: 3, shrinkwrapMinorVersion: 4, + shrinkwrapVersion: 3, + specifiers: expectedSpecs, }) }) -test('package with a broken symlink', async function (t) { +test('package with a broken symlink', async (t) => { const project = prepare(t) await installPkgs([pathToLocalPkg('has-broken-symlink/has-broken-symlink.tar.gz')], await testDefaults()) @@ -120,7 +120,7 @@ test('package with a broken symlink', async function (t) { t.ok(m, 'has-broken-symlink is available') }) -test('tarball local package', async function (t) { +test('tarball local package', async (t) => { const project = prepare(t) await installPkgs([pathToLocalPkg('tar-pkg/tar-pkg-1.0.0.tgz')], await testDefaults()) @@ -144,7 +144,7 @@ test('tarball local package', async function (t) { }, 'a snapshot of the local dep tarball added to shrinkwrap.yaml') }) -test('update tarball local package when its integrity changes', async function (t) { +test('update tarball local package when its integrity changes', async (t) => { const project = prepare(t) await ncp(pathToLocalPkg('tar-pkg-with-dep-1/tar-pkg-with-dep-1.0.0.tgz'), path.resolve('..', 'tar.tgz')) diff --git a/test/install/misc.ts b/test/install/misc.ts index c88bfd6bd8..8ce265990a 100644 --- a/test/install/misc.ts +++ b/test/install/misc.ts @@ -2,32 +2,32 @@ import 'sepia' import tape = require('tape') import promisifyTape from 'tape-promise' const test = promisifyTape(tape) -import path = require('path') -import fs = require('mz/fs') import caw = require('caw') -import semver = require('semver') import crossSpawn = require('cross-spawn') +import fs = require('mz/fs') +import path = require('path') +import semver = require('semver') const spawnSync = crossSpawn.sync import isCI = require('is-ci') -import rimraf = require('rimraf-then') +import loadJsonFile = require('load-json-file') import readPkg = require('read-pkg') +import rimraf = require('rimraf-then') import { - prepare, addDistTag, + prepare, testDefaults, } from '../utils' -import loadJsonFile = require('load-json-file') const basicPackageJson = loadJsonFile.sync(path.join(__dirname, '../utils/simple-package.json')) -import {install, installPkgs, uninstall} from 'supi' -import exists = require('path-exists') -import isWindows = require('is-windows') import deepRequireCwd = require('deep-require-cwd') +import isWindows = require('is-windows') +import exists = require('path-exists') import sinon = require('sinon') +import {install, installPkgs, uninstall} from 'supi' import { - StageLog, - RootLog, - ProgressLog, PackageJsonLog, + ProgressLog, + RootLog, + StageLog, StatsLog, } from 'supi' import writeJsonFile = require('write-json-file') @@ -65,75 +65,75 @@ test('no dependencies (lodash)', async (t: tape.Test) => { await installPkgs(['lodash@4.0.0'], await testDefaults({reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:package-json', - level: 'debug', + t.ok(reporter.calledWithMatch({ initial: {name: 'project', version: '0.0.0'}, - }), 'initial package.json logged') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:stage', + level: 'debug', + name: 'pnpm:package-json', + } as PackageJsonLog), 'initial package.json logged') + t.ok(reporter.calledWithMatch({ level: 'debug', message: 'resolution_started', - }), 'resolution stage start logged') - t.ok(reporter.calledWithMatch({ name: 'pnpm:stage', + } as StageLog), 'resolution stage start logged') + t.ok(reporter.calledWithMatch({ level: 'debug', message: 'resolution_done', - }), 'resolution stage done logged') - t.ok(reporter.calledWithMatch({ name: 'pnpm:stage', + } as StageLog), 'resolution stage done logged') + t.ok(reporter.calledWithMatch({ level: 'debug', message: 'importing_started', - }), 'importing stage start logged') - t.ok(reporter.calledWithMatch({ name: 'pnpm:stage', + } as StageLog), 'importing stage start logged') + t.ok(reporter.calledWithMatch({ level: 'debug', message: 'importing_done', - }), 'importing stage done logged') + name: 'pnpm:stage', + } as StageLog), 'importing stage done logged') // Not logged for now // t.ok(reporter.calledWithMatch({ // level: 'info', // message: 'Creating dependency tree', // }), 'informed about creating dependency tree') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:stats', - level: 'debug', + t.ok(reporter.calledWithMatch({ added: 1, - }), 'added stat') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:stats', level: 'debug', + name: 'pnpm:stats', + } as StatsLog), 'added stat') + t.ok(reporter.calledWithMatch({ + level: 'debug', + name: 'pnpm:stats', removed: 0, - }), 'removed stat') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + } as StatsLog), 'removed stat') + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'prod', + latest: '4.1.0', name: 'lodash', realName: 'lodash', version: '4.0.0', - dependencyType: 'prod', - latest: '4.1.0', }, - }), 'added to root') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:package-json', + level: 'info', + name: 'pnpm:root', + } as RootLog), 'added to root') + t.ok(reporter.calledWithMatch({ level: 'debug', + name: 'pnpm:package-json', updated: { - name: 'project', - version: '0.0.0', dependencies: { lodash: '^4.0.0', }, + name: 'project', + version: '0.0.0', }, - }), 'updated package.json logged') + } as PackageJsonLog), 'updated package.json logged') const m = project.requireModule('lodash') t.ok(typeof m === 'function', '_ is available') t.ok(typeof m.clone === 'function', '_.clone is available') }) -test('scoped modules without version spec (@rstacruz/tap-spec)', async function (t) { +test('scoped modules without version spec (@rstacruz/tap-spec)', async (t) => { const project = prepare(t) await installPkgs(['@rstacruz/tap-spec'], await testDefaults()) @@ -141,22 +141,22 @@ test('scoped modules without version spec (@rstacruz/tap-spec)', async function t.ok(typeof m === 'function', 'tap-spec is available') }) -test('scoped package with custom registry', async function (t) { +test('scoped package with custom registry', async (t) => { const project = prepare(t) await installPkgs(['@scoped/peer'], await testDefaults({ // setting an incorrect default registry URL - registry: 'http://localhost:9999/', rawNpmConfig: { '@scoped:registry': 'http://localhost:4873/', }, + registry: 'http://localhost:9999/', })) const m = project.requireModule('@scoped/peer/package.json') t.ok(m, 'is available') }) -test('modules without version spec, with custom tag config', async function (t) { +test('modules without version spec, with custom tag config', async (t) => { const project = prepare(t) const tag = 'beta' @@ -169,7 +169,7 @@ test('modules without version spec, with custom tag config', async function (t) await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0') }) -test('installing a package by specifying a specific dist-tag', async function (t) { +test('installing a package by specifying a specific dist-tag', async (t) => { const project = prepare(t) await addDistTag('dep-of-pkg-with-1-dep', '100.1.0', 'latest') @@ -180,7 +180,7 @@ test('installing a package by specifying a specific dist-tag', async function (t await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0') }) -test('update a package when installing with a dist-tag', async function (t: tape.Test) { +test('update a package when installing with a dist-tag', async (t: tape.Test) => { const project = prepare(t) await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest') @@ -192,25 +192,25 @@ test('update a package when installing with a dist-tag', async function (t: tape await installPkgs(['dep-of-pkg-with-1-dep@beta'], await testDefaults({saveDev: true, reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', + t.ok(reporter.calledWithMatch({ level: 'info', + name: 'pnpm:root', removed: { + dependencyType: 'dev', name: 'dep-of-pkg-with-1-dep', version: '100.0.0', - dependencyType: 'dev', }, - }), 'reported old version removed from the root') + } as RootLog), 'reported old version removed from the root') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'dev', name: 'dep-of-pkg-with-1-dep', version: '100.1.0', - dependencyType: 'dev', }, - }), 'reported new version added to the root') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'reported new version added to the root') await project.has('dep-of-pkg-with-1-dep') await project.storeHas('dep-of-pkg-with-1-dep', '100.1.0') @@ -219,7 +219,7 @@ test('update a package when installing with a dist-tag', async function (t: tape t.equal(pkg.devDependencies['dep-of-pkg-with-1-dep'], '^100.1.0') }) -test('scoped modules with versions (@rstacruz/tap-spec@4.1.1)', async function (t) { +test('scoped modules with versions (@rstacruz/tap-spec@4.1.1)', async (t) => { const project = prepare(t) await installPkgs(['@rstacruz/tap-spec@4.1.1'], await testDefaults()) @@ -227,7 +227,7 @@ test('scoped modules with versions (@rstacruz/tap-spec@4.1.1)', async function ( t.ok(typeof m === 'function', 'tap-spec is available') }) -test('scoped modules (@rstacruz/tap-spec@*)', async function (t) { +test('scoped modules (@rstacruz/tap-spec@*)', async (t) => { const project = prepare(t) await installPkgs(['@rstacruz/tap-spec@*'], await testDefaults()) @@ -235,7 +235,7 @@ test('scoped modules (@rstacruz/tap-spec@*)', async function (t) { t.ok(typeof m === 'function', 'tap-spec is available') }) -test('multiple scoped modules (@rstacruz/...)', async function (t) { +test('multiple scoped modules (@rstacruz/...)', async (t) => { const project = prepare(t) await installPkgs(['@rstacruz/tap-spec@*', '@rstacruz/travis-encrypt@*'], await testDefaults()) @@ -243,7 +243,7 @@ test('multiple scoped modules (@rstacruz/...)', async function (t) { t.equal(typeof project.requireModule('@rstacruz/travis-encrypt'), 'function', 'travis-encrypt is available') }) -test('nested scoped modules (test-pnpm-issue219 -> @zkochan/test-pnpm-issue219)', async function (t) { +test('nested scoped modules (test-pnpm-issue219 -> @zkochan/test-pnpm-issue219)', async (t) => { const project = prepare(t) await installPkgs(['test-pnpm-issue219@1.0.2'], await testDefaults()) @@ -258,29 +258,29 @@ test('idempotency (rimraf)', async (t: tape.Test) => { await installPkgs(['rimraf@2.5.1'], opts) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'prod', name: 'rimraf', version: '2.5.1', - dependencyType: 'prod', }, - }), 'reported that rimraf added to the root') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'reported that rimraf added to the root') reporter.reset() await installPkgs(['rimraf@2.5.1'], opts) - t.notOk(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.notOk(reporter.calledWithMatch({ added: { + dependencyType: 'prod', name: 'rimraf', version: '2.5.1', - dependencyType: 'prod', }, - }), 'did not reported that rimraf was added because it was already there') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'did not reported that rimraf was added because it was already there') const m = project.requireModule('rimraf') t.ok(typeof m === 'function', 'rimraf is available') @@ -296,15 +296,15 @@ test('reporting adding root package', async (t: tape.Test) => { await installPkgs(['flatten@1.0.2'], await testDefaults({reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'prod', name: 'flatten', version: '1.0.2', - dependencyType: 'prod', }, - }), 'reported that flatten added to the root') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'reported that flatten added to the root') }) test('overwriting (magic-hook@2.0.0 and @0.1.0)', async (t: tape.Test) => { @@ -323,7 +323,7 @@ test('overwriting (magic-hook@2.0.0 and @0.1.0)', async (t: tape.Test) => { t.ok(m.version === '0.1.0', 'magic-hook is 0.1.0') }) -test('overwriting (is-positive@3.0.0 with is-positive@latest)', async function (t) { +test('overwriting (is-positive@3.0.0 with is-positive@latest)', async (t) => { const project = prepare(t) await installPkgs(['is-positive@3.0.0'], await testDefaults({save: true})) @@ -334,7 +334,7 @@ test('overwriting (is-positive@3.0.0 with is-positive@latest)', async function ( await project.storeHas('is-positive', '3.1.0') }) -test('forcing', async function (t) { +test('forcing', async (t) => { const project = prepare(t) await installPkgs(['magic-hook@2.0.0'], await testDefaults()) @@ -347,7 +347,7 @@ test('forcing', async function (t) { t.ok(distPathExists, 'magic-hook@2.0.0 dist folder reinstalled') }) -test('argumentless forcing', async function (t: tape.Test) { +test('argumentless forcing', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['magic-hook@2.0.0'], await testDefaults()) @@ -360,7 +360,7 @@ test('argumentless forcing', async function (t: tape.Test) { t.ok(distPathExists, 'magic-hook@2.0.0 dist folder reinstalled') }) -test('no forcing', async function (t) { +test('no forcing', async (t) => { const project = prepare(t) await installPkgs(['magic-hook@2.0.0'], await testDefaults()) @@ -373,7 +373,7 @@ test('no forcing', async function (t) { t.notOk(distPathExists, 'magic-hook@2.0.0 dist folder not reinstalled') }) -test('refetch package to store if it has been modified', async function (t) { +test('refetch package to store if it has been modified', async (t) => { const project = prepare(t) await installPkgs(['magic-hook@2.0.0'], await testDefaults()) @@ -403,7 +403,7 @@ test("don't refetch package to store if it has been modified and verify-store-in }) // TODO: decide what to do with this case -test['skip']('relink package to project if the dependency is not linked from store', async function (t: tape.Test) { +test.skip('relink package to project if the dependency is not linked from store', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['magic-hook@2.0.0'], await testDefaults({save: true, saveExact: true})) @@ -427,7 +427,7 @@ test['skip']('relink package to project if the dependency is not linked from sto t.ok(storeInode === await getInode(), 'package.json inode matches the one that is in store') }) -test('circular deps', async function (t: tape.Test) { +test('circular deps', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['circular-deps-1-of-2'], await testDefaults()) @@ -456,7 +456,7 @@ test('concurrent circular deps', async (t: tape.Test) => { t.ok(await exists(path.join('node_modules', '.localhost+4873', 'es5-ext', '0.10.31', 'node_modules', 'es6-symbol'))) }) -test('concurrent installation of the same packages', async function (t) { +test('concurrent installation of the same packages', async (t) => { const project = prepare(t) // the same version of core-js is required by two different dependencies @@ -468,7 +468,7 @@ test('concurrent installation of the same packages', async function (t) { t.ok(m, 'babel-core is installed') }) -test('big with dependencies and circular deps (babel-preset-2015)', async function (t) { +test('big with dependencies and circular deps (babel-preset-2015)', async (t) => { const project = prepare(t) await installPkgs(['babel-preset-es2015@6.3.13'], await testDefaults()) @@ -476,7 +476,7 @@ test('big with dependencies and circular deps (babel-preset-2015)', async functi t.ok(typeof m === 'object', 'babel-preset-es2015 is available') }) -test('bundledDependencies (pkg-with-bundled-dependencies@1.0.0)', async function (t: tape.Test) { +test('bundledDependencies (pkg-with-bundled-dependencies@1.0.0)', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pkg-with-bundled-dependencies@1.0.0'], await testDefaults()) @@ -487,11 +487,11 @@ test('bundledDependencies (pkg-with-bundled-dependencies@1.0.0)', async function t.deepEqual( shr.packages['/pkg-with-bundled-dependencies/1.0.0'].bundledDependencies, ['hello-world-js-bin'], - 'bundledDependencies added to shrinkwrap.yaml' + 'bundledDependencies added to shrinkwrap.yaml', ) }) -test('bundleDependencies (pkg-with-bundle-dependencies@1.0.0)', async function (t: tape.Test) { +test('bundleDependencies (pkg-with-bundle-dependencies@1.0.0)', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pkg-with-bundle-dependencies@1.0.0'], await testDefaults()) @@ -502,11 +502,11 @@ test('bundleDependencies (pkg-with-bundle-dependencies@1.0.0)', async function ( t.deepEqual( shr.packages['/pkg-with-bundle-dependencies/1.0.0'].bundledDependencies, ['hello-world-js-bin'], - 'bundledDependencies added to shrinkwrap.yaml' + 'bundledDependencies added to shrinkwrap.yaml', ) }) -test('compiled modules (ursa@0.9.1)', async function (t) { +test('compiled modules (ursa@0.9.1)', async (t) => { // TODO: fix this for Node.js v7 if (!isCI || IS_WINDOWS || semver.satisfies(process.version, '>=7.0.0')) { t.skip('runs only on CI') @@ -520,7 +520,7 @@ test('compiled modules (ursa@0.9.1)', async function (t) { t.ok(typeof m === 'object', 'ursa() is available') }) -test('shrinkwrap compatibility', async function (t) { +test('shrinkwrap compatibility', async (t) => { if (semver.satisfies(process.version, '4')) { t.skip("don't run on Node.js 4") return @@ -544,9 +544,9 @@ test('shrinkwrap compatibility', async function (t) { }) }) -const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) -test('support installing into the same store simultaneously', async t => { +test('support installing into the same store simultaneously', async (t) => { const project = prepare(t) await Promise.all([ installPkgs(['pkg-that-installs-slowly'], await testDefaults()), @@ -559,11 +559,11 @@ test('support installing into the same store simultaneously', async t => { await project.has('pkg-that-installs-slowly') await project.has('rimraf') }) - .catch(err => t.notOk(err)) + .catch((err) => t.notOk(err)), ]) }) -test('support installing and uninstalling from the same store simultaneously', async t => { +test('support installing and uninstalling from the same store simultaneously', async (t) => { const project = prepare(t) await Promise.all([ installPkgs(['pkg-that-installs-slowly'], await testDefaults()), @@ -576,15 +576,15 @@ test('support installing and uninstalling from the same store simultaneously', a await project.has('pkg-that-installs-slowly') await project.hasNot('rimraf') }) - .catch(err => t.notOk(err)) + .catch((err) => t.notOk(err)), ]) }) -test('top-level packages should find the plugins they use', async function (t) { +test('top-level packages should find the plugins they use', async (t) => { const project = prepare(t, { scripts: { - test: 'pkg-that-uses-plugins' - } + test: 'pkg-that-uses-plugins', + }, }) await installPkgs(['pkg-that-uses-plugins', 'plugin-example'], await testDefaults({ save: true })) const result = spawnSync('npm', ['test']) @@ -592,19 +592,19 @@ test('top-level packages should find the plugins they use', async function (t) { t.equal(result.status, 0, 'executable exited with success') }) -test('not top-level packages should find the plugins they use', async function (t: tape.Test) { +test('not top-level packages should find the plugins they use', async (t: tape.Test) => { // standard depends on eslint and eslint plugins const project = prepare(t, { scripts: { - test: 'standard' - } + test: 'standard', + }, }) await installPkgs(['standard@8.6.0'], await testDefaults({ save: true })) const result = spawnSync('npm', ['test']) t.equal(result.status, 0, 'standard exited with success') }) -test('bin specified in the directories property linked to .bin folder', async function (t) { +test('bin specified in the directories property linked to .bin folder', async (t) => { const project = prepare(t) await installPkgs(['pkg-with-directories-bin'], await testDefaults()) @@ -612,11 +612,11 @@ test('bin specified in the directories property linked to .bin folder', async fu await project.isExecutable('.bin/pkg-with-directories-bin') }) -test('run js bin file', async function (t) { +test('run js bin file', async (t) => { const project = prepare(t, { scripts: { - test: 'hello-world-js-bin' - } + test: 'hello-world-js-bin', + }, }) await installPkgs(['hello-world-js-bin'], await testDefaults({ save: true })) @@ -625,7 +625,7 @@ test('run js bin file', async function (t) { t.equal(result.status, 0, 'executable exited with success') }) -test('building native addons', async function (t) { +test('building native addons', async (t) => { const project = prepare(t) await installPkgs(['runas@3.1.1'], await testDefaults()) @@ -652,11 +652,11 @@ test('should update subdep on second install', async (t: tape.Test) => { await install(await testDefaults({depth: 1, update: true, reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:stats', - level: 'debug', + t.ok(reporter.calledWithMatch({ added: 1, - }), 'added stat') + level: 'debug', + name: 'pnpm:stats', + } as StatsLog), 'added stat') await project.storeHas('dep-of-pkg-with-1-dep', '100.1.0') @@ -668,7 +668,7 @@ test('should update subdep on second install', async (t: tape.Test) => { t.equal(deepRequireCwd(['pkg-with-1-dep', 'dep-of-pkg-with-1-dep', './package.json']).version, '100.1.0', 'updated in node_modules') }) -test('should not update subdep when depth is smaller than depth of package', async function (t: tape.Test) { +test('should not update subdep when depth is smaller than depth of package', async (t: tape.Test) => { const project = prepare(t) await addDistTag('dep-of-pkg-with-1-dep', '100.0.0', 'latest') @@ -695,7 +695,7 @@ test('should not update subdep when depth is smaller than depth of package', asy t.equal(deepRequireCwd(['pkg-with-1-dep', 'dep-of-pkg-with-1-dep', './package.json']).version, '100.0.0', 'not updated in node_modules') }) -test('should install dependency in second project', async function (t) { +test('should install dependency in second project', async (t) => { const project1 = prepare(t) await installPkgs(['pkg-with-1-dep'], await testDefaults({save: true, store: '../store'})) @@ -708,7 +708,7 @@ test('should install dependency in second project', async function (t) { t.equal(project2.requireModule('pkg-with-1-dep')().name, 'dep-of-pkg-with-1-dep', 'can require in 2nd pkg') }) -test('should throw error when trying to install using a different store then the previous one', async function(t) { +test('should throw error when trying to install using a different store then the previous one', async (t) => { const project = prepare(t) await installPkgs(['rimraf@2.5.1'], await testDefaults({store: 'node_modules/.store1'})) @@ -735,11 +735,11 @@ test('ignores drive case in store path', async (t: tape.Test) => { t.pass('Install did not fail') }) -test('should not throw error if using a different store after all the packages were uninstalled', async function(t) { +test('should not throw error if using a different store after all the packages were uninstalled', async (t) => { // TODO: implement }) -test('shrinkwrap locks npm dependencies', async function (t: tape.Test) { +test('shrinkwrap locks npm dependencies', async (t: tape.Test) => { const project = prepare(t) const reporter = sinon.spy() @@ -747,17 +747,17 @@ test('shrinkwrap locks npm dependencies', async function (t: tape.Test) { await installPkgs(['pkg-with-1-dep'], await testDefaults({save: true, reporter})) - t.ok(reporter.calledWithMatch({ + t.ok(reporter.calledWithMatch({ + level: 'debug', name: 'pnpm:progress', - level: 'debug', + pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', status: 'resolving_content', - pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', - }), 'logs that package is being resolved') - t.ok(reporter.calledWithMatch({ + } as ProgressLog), 'logs that package is being resolved') + t.ok(reporter.calledWithMatch({ level: 'debug', - status: 'fetched', pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', - }), 'logged that package was fetched from registry') + status: 'fetched', + } as ProgressLog), 'logged that package was fetched from registry') await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0') @@ -768,23 +768,23 @@ test('shrinkwrap locks npm dependencies', async function (t: tape.Test) { reporter.reset() await install(await testDefaults({reporter})) - t.ok(reporter.calledWithMatch({ + t.ok(reporter.calledWithMatch({ level: 'debug', + pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', status: 'resolving_content', - pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', - }), 'logs that package is being resolved') - t.ok(reporter.calledWithMatch({ + } as ProgressLog), 'logs that package is being resolved') + t.ok(reporter.calledWithMatch({ level: 'debug', - status: 'found_in_store', pkgId: 'localhost+4873/pkg-with-1-dep/100.0.0', - }), 'logged that package was found in store') + status: 'found_in_store', + } as ProgressLog), 'logged that package was found in store') const m = project.requireModule('.localhost+4873/pkg-with-1-dep/100.0.0/node_modules/dep-of-pkg-with-1-dep/package.json') t.equal(m.version, '100.0.0', 'dependency specified in shrinkwrap.yaml is installed') }) -test('self-require should work', async function (t) { +test('self-require should work', async (t) => { const project = prepare(t) await installPkgs(['uses-pkg-with-self-usage'], await testDefaults()) @@ -818,17 +818,17 @@ test('install a dependency with * range', async (t: tape.Test) => { await project.has('has-beta-only') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:package-json', + t.ok(reporter.calledWithMatch({ level: 'debug', + name: 'pnpm:package-json', updated: { - name: 'project', - version: '0.0.0', dependencies: { 'has-beta-only': '*', }, + name: 'project', + version: '0.0.0', }, - }), 'should log package-json updated even when package.json was not changed') + } as PackageJsonLog), 'should log package-json updated even when package.json was not changed') }) test('create a package.json if there is none', async (t: tape.Test) => { diff --git a/test/install/only.ts b/test/install/only.ts index 4ee87d9252..ea06f6618a 100644 --- a/test/install/only.ts +++ b/test/install/only.ts @@ -1,12 +1,12 @@ -import path = require('path') import fs = require('mz/fs') +import path = require('path') +import {install} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import { prepare, testDefaults, } from '../utils' -import {install} from 'supi' const test = promisifyTape(tape) @@ -16,8 +16,8 @@ test('production install (with --production flag)', async (t: tape.Test) => { rimraf: '2.6.2', }, devDependencies: { - once: '^1.4.0', // once is also a transitive dependency of rimraf '@rstacruz/tap-spec': '4.1.1', + 'once': '^1.4.0', // once is also a transitive dependency of rimraf }, }) @@ -39,8 +39,8 @@ test('production install (with --production flag)', async (t: tape.Test) => { test('install dev dependencies only', async (t: tape.Test) => { const project = prepare(t, { dependencies: { - once: '^1.4.0', 'is-positive': '1.0.0', + 'once': '^1.4.0', }, devDependencies: { inflight: '1.0.6', diff --git a/test/install/optionalDependencies.ts b/test/install/optionalDependencies.ts index e71b4352c0..0e95df7600 100644 --- a/test/install/optionalDependencies.ts +++ b/test/install/optionalDependencies.ts @@ -1,22 +1,22 @@ -import path = require('path') -import tape = require('tape') -import promisifyTape from 'tape-promise' -import loadYamlFile = require('load-yaml-file') -import exists = require('path-exists') import deepRequireCwd = require('deep-require-cwd') +import loadYamlFile = require('load-yaml-file') +import path = require('path') +import exists = require('path-exists') import sinon = require('sinon') import {install, installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { - prepare, addDistTag, - testDefaults, - pathToLocalPkg, local, + pathToLocalPkg, + prepare, + testDefaults, } from '../utils' const test = promisifyTape(tape) -test('successfully install optional dependency with subdependencies', async function (t) { +test('successfully install optional dependency with subdependencies', async (t) => { const project = prepare(t) await installPkgs(['fsevents@1.0.14'], await testDefaults({saveOptional: true})) @@ -44,9 +44,9 @@ test('skip non-existing optional dependency', async (t: tape.Test) => { await install(await testDefaults({reporter})) t.ok(reporter.calledWithMatch({ - name: 'pnpm', level: 'warn', message: 'Skipping optional dependency i-do-not-exist@1000. Error: 404 Not Found: i-do-not-exist', + name: 'pnpm', }), 'warning reported') const m = project.requireModule('is-positive') @@ -56,8 +56,8 @@ test('skip non-existing optional dependency', async (t: tape.Test) => { test('skip optional dependency that does not support the current OS', async (t: tape.Test) => { const project = prepare(t, { optionalDependencies: { - 'not-compatible-with-any-os': '*' - } + 'not-compatible-with-any-os': '*', + }, }) const reporter = sinon.spy() @@ -88,8 +88,8 @@ test('skip optional dependency that does not support the current OS', async (t: test('skip optional dependency that does not support the current Node version', async (t: tape.Test) => { const project = prepare(t, { optionalDependencies: { - 'for-legacy-node': '*' - } + 'for-legacy-node': '*', + }, }) const reporter = sinon.spy() @@ -109,8 +109,8 @@ test('skip optional dependency that does not support the current Node version', test('skip optional dependency that does not support the current pnpm version', async (t: tape.Test) => { const project = prepare(t, { optionalDependencies: { - 'for-legacy-pnpm': '*' - } + 'for-legacy-pnpm': '*', + }, }) const reporter = sinon.spy() @@ -127,15 +127,15 @@ test('skip optional dependency that does not support the current pnpm version', t.equal(reportedTimes, 1, 'skipping optional dependency is logged') }) -test('don\'t skip optional dependency that does not support the current OS when forcing', async function (t) { +test('don\'t skip optional dependency that does not support the current OS when forcing', async (t) => { const project = prepare(t, { optionalDependencies: { - 'not-compatible-with-any-os': '*' - } + 'not-compatible-with-any-os': '*', + }, }) await install(await testDefaults({ - force: true + force: true, })) await project.has('not-compatible-with-any-os') diff --git a/test/install/peerDependencies.ts b/test/install/peerDependencies.ts index c9e33e58fc..1a45bde269 100644 --- a/test/install/peerDependencies.ts +++ b/test/install/peerDependencies.ts @@ -1,21 +1,21 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' +import deepRequireCwd = require('deep-require-cwd') +import loadJsonFile = require('load-json-file') import path = require('path') import exists = require('path-exists') -import {installPkgs, install} from 'supi' +import rimraf = require('rimraf-then') +import sinon = require('sinon') +import {install, installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { prepare, testDefaults, } from '../utils' -import deepRequireCwd = require('deep-require-cwd') -import rimraf = require('rimraf-then') -import sinon = require('sinon') -import loadJsonFile = require('load-json-file') const test = promisifyTape(tape) const NM = 'node_modules' -test("don't fail when peer dependency is fetched from GitHub", async t => { +test("don't fail when peer dependency is fetched from GitHub", async (t) => { const project = prepare(t) await installPkgs(['test-pnpm-peer-deps'], await testDefaults()) }) @@ -164,7 +164,7 @@ test('peer dependencies are linked when running two separate named installations t.equal(deepRequireCwd(['abc-grand-parent-with-c', 'abc-parent-with-ab', 'abc', 'peer-c', './package.json']).version, '1.0.0') }) -test['skip']('peer dependencies are linked', async (t: tape.Test) => { +test.skip('peer dependencies are linked', async (t: tape.Test) => { const project = prepare(t, { dependencies: { 'abc-grand-parent-with-c': '*', @@ -251,7 +251,7 @@ test('package that resolves its own peer dependency', async (t: tape.Test) => { t.ok(shr.packages['/pkg-with-resolved-peer/1.0.0'].optionalDependencies['peer-b']) }) -test('own peer installed in root as well is linked to root', async function (t: tape.Test) { +test('own peer installed in root as well is linked to root', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['is-negative@kevva/is-negative#2.1.0', 'peer-deps-in-child-pkg'], await testDefaults()) diff --git a/test/install/reporting.ts b/test/install/reporting.ts index 522de6e58b..3a0bc68fe5 100644 --- a/test/install/reporting.ts +++ b/test/install/reporting.ts @@ -1,11 +1,11 @@ +import sinon = require('sinon') +import { + DeprecationLog, + installPkgs, +} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import {prepare, testDefaults} from '../utils' -import { - installPkgs, - DeprecationLog, -} from 'supi' -import sinon = require('sinon') const test = promisifyTape(tape) @@ -17,17 +17,17 @@ test('reports warning when installing deprecated packages', async (t: tape.Test) await installPkgs(['jade@1.11.0'], await testDefaults({reporter})) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:deprecation', - level: 'warn', - pkgId: 'localhost+4873/jade/1.11.0', + t.ok(reporter.calledWithMatch({ deprecated: 'Jade has been renamed to pug, please install the latest version of pug instead of jade', - }), 'deprecation warning reported') + level: 'warn', + name: 'pnpm:deprecation', + pkgId: 'localhost+4873/jade/1.11.0', + } as DeprecationLog), 'deprecation warning reported') const shr = await project.loadShrinkwrap() t.equal( shr.packages['/jade/1.11.0'].deprecated, 'Jade has been renamed to pug, please install the latest version of pug instead of jade', - 'deprecated field added to shrinkwrap.yaml' + 'deprecated field added to shrinkwrap.yaml', ) }) diff --git a/test/install/shamefullyFlatten.ts b/test/install/shamefullyFlatten.ts index d288f77c04..b7d84a52a0 100644 --- a/test/install/shamefullyFlatten.ts +++ b/test/install/shamefullyFlatten.ts @@ -1,13 +1,13 @@ import resolveLinkTarget = require('resolve-link-target') +import {install, installPkgs, prune, uninstall} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import {install, installPkgs, uninstall, prune} from 'supi' import {prepare, testDefaults} from '../utils' const test = promisifyTape(tape) const testOnly = promisifyTape(tape.only) -test('should flatten dependencies', async function (t) { +test('should flatten dependencies', async (t) => { const project = prepare(t) await installPkgs(['express'], await testDefaults({shamefullyFlatten: true})) @@ -17,7 +17,7 @@ test('should flatten dependencies', async function (t) { await project.has('cookie') }) -test('should remove flattened dependencies', async function (t) { +test('should remove flattened dependencies', async (t) => { const project = prepare(t) await installPkgs(['express'], await testDefaults({shamefullyFlatten: true})) @@ -28,7 +28,7 @@ test('should remove flattened dependencies', async function (t) { await project.hasNot('cookie') }) -test('should not override root packages with flattened dependencies', async function (t) { +test('should not override root packages with flattened dependencies', async (t) => { const project = prepare(t) // this installs debug@3.1.0 @@ -39,7 +39,7 @@ test('should not override root packages with flattened dependencies', async func t.equal(project.requireModule('debug/package.json').version, '3.1.0', 'debug did not get overridden by flattening') }) -test('should reflatten when uninstalling a package', async function (t) { +test('should reflatten when uninstalling a package', async (t) => { const project = prepare(t) // this installs debug@3.1.0 and express@4.16.0 @@ -51,12 +51,12 @@ test('should reflatten when uninstalling a package', async function (t) { t.equal(project.requireModule('express/package.json').version, '4.16.0', 'express did not get updated by flattening') }) -test('should reflatten after running a general install', async function (t) { +test('should reflatten after running a general install', async (t) => { const project = prepare(t, { dependencies: { debug: '3.1.0', - express: '4.16.0' - } + express: '4.16.0', + }, }) await install(await testDefaults({shamefullyFlatten: true})) @@ -71,7 +71,7 @@ test('should reflatten after running a general install', async function (t) { // now remove debug@3.1.0 from package.json, run install again, check that debug@2.6.9 has been flattened // and that express stays at the same version await project.rewriteDependencies({ - express: '4.16.0' + express: '4.16.0', }) await install(await testDefaults({shamefullyFlatten: true})) @@ -90,7 +90,7 @@ test('should not override aliased dependencies', async (t: tape.Test) => { t.equal(project.requireModule('debug/package.json').version, '1.0.0', 'alias respected by flattening') }) -test('--shamefully-flatten throws exception when executed on node_modules installed w/o the option', async function (t: tape.Test) { +test('--shamefully-flatten throws exception when executed on node_modules installed w/o the option', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['is-positive'], await testDefaults({shamefullyFlatten: false})) @@ -102,7 +102,7 @@ test('--shamefully-flatten throws exception when executed on node_modules instal } }) -test('--no-shamefully-flatten throws exception when executed on node_modules installed with --shamefully-flatten', async function (t: tape.Test) { +test('--no-shamefully-flatten throws exception when executed on node_modules installed with --shamefully-flatten', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['is-positive'], await testDefaults({shamefullyFlatten: true})) @@ -128,7 +128,7 @@ test('flatten by alias', async (t: tape.Test) => { t.deepEqual(modules.hoistedAliases, {'localhost+4873/dep-of-pkg-with-1-dep/100.1.0': [ 'dep' ]}, '.modules.yaml updated correctly') }) -test('should remove aliased flattened dependencies', async function (t) { +test('should remove aliased flattened dependencies', async (t) => { const project = prepare(t) await installPkgs(['pkg-with-1-aliased-dep'], await testDefaults({shamefullyFlatten: true})) @@ -148,11 +148,11 @@ test('should remove aliased flattened dependencies', async function (t) { t.deepEqual(modules.hoistedAliases, {}, '.modules.yaml updated correctly') }) -test('should update .modules.yaml when pruning if we are flattening', async function (t) { +test('should update .modules.yaml when pruning if we are flattening', async (t) => { const project = prepare(t, { dependencies: { - 'pkg-with-1-aliased-dep': '*' - } + 'pkg-with-1-aliased-dep': '*', + }, }) await install(await testDefaults({shamefullyFlatten: true})) @@ -165,12 +165,12 @@ test('should update .modules.yaml when pruning if we are flattening', async func t.deepEqual(modules.hoistedAliases, {}, '.modules.yaml updated correctly') }) -test('should reflatten after pruning', async function (t) { +test('should reflatten after pruning', async (t) => { const project = prepare(t, { dependencies: { debug: '3.1.0', - express: '4.16.0' - } + express: '4.16.0', + }, }) await install(await testDefaults({shamefullyFlatten: true})) @@ -185,7 +185,7 @@ test('should reflatten after pruning', async function (t) { // now remove debug@3.1.0 from package.json, run install again, check that debug@2.6.9 has been flattened // and that ms is still there, and that is-positive is not installed await project.rewriteDependencies({ - express: '4.16.0', + 'express': '4.16.0', 'is-positive': '1.0.0', }) @@ -199,7 +199,7 @@ test('should reflatten after pruning', async function (t) { await project.hasNot('is-positive') }) -test('should flatten correctly peer dependencies', async function (t) { +test('should flatten correctly peer dependencies', async (t) => { const project = prepare(t) await installPkgs(['using-ajv'], await testDefaults({shamefullyFlatten: true})) diff --git a/test/install/shrinkwrapOnly.ts b/test/install/shrinkwrapOnly.ts index 7235d02583..58e6c11b14 100644 --- a/test/install/shrinkwrapOnly.ts +++ b/test/install/shrinkwrapOnly.ts @@ -1,18 +1,18 @@ +import loadJsonFile = require('load-json-file') +import fs = require('mz/fs') +import path = require('path') +import sinon = require('sinon') import { install, installPkgs, uninstall, } from 'supi' -import loadJsonFile = require('load-json-file') import tape = require('tape') import promisifyTape from 'tape-promise' -import sinon = require('sinon') import { prepare, testDefaults, } from '../utils' -import path = require('path') -import fs = require('mz/fs') const test = promisifyTape(tape) @@ -53,21 +53,21 @@ test('warn when installing with shrinkwrapOnly = true and node_modules exists', await installPkgs(['is-positive'], await testDefaults()) await installPkgs(['rimraf@2.5.1'], await testDefaults({ - shrinkwrapOnly: true, reporter, + shrinkwrapOnly: true, })) t.ok(reporter.calledWithMatch({ - name: 'pnpm', level: 'warn', message: '`node_modules` is present. Shrinkwrap only installation will make it out-of-date', + name: 'pnpm', }), 'log warning') await project.storeHasNot('rimraf', '2.5.1') await project.hasNot('rimraf') const pkg = await loadJsonFile('package.json') - t.ok(pkg.dependencies['rimraf'], 'the new dependency added to package.json') + t.ok(pkg.dependencies.rimraf, 'the new dependency added to package.json') const shr = await project.loadShrinkwrap() t.ok(shr.dependencies.rimraf) diff --git a/test/install/sideEffects.ts b/test/install/sideEffects.ts index 78df4ea72d..d95c896758 100644 --- a/test/install/sideEffects.ts +++ b/test/install/sideEffects.ts @@ -1,11 +1,11 @@ import fs = require('mz/fs') import rimraf = require('rimraf-then') -import tape = require('tape') -import promisifyTape from 'tape-promise' -import {installPkgs} from 'supi' import path = require('path') import exists = require('path-exists') +import {installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' import { prepare, testDefaults, @@ -14,7 +14,7 @@ import { const test = promisifyTape(tape) test.only = promisifyTape(tape.only) -test('caching side effects of native package', async function (t) { +test('caching side effects of native package', async (t) => { const project = prepare(t) const opts = await testDefaults({sideEffectsCache: true}) @@ -35,7 +35,7 @@ test('caching side effects of native package', async function (t) { t.notEqual(stat1.ino, stat3.ino, 'cache is overridden when force is true') }) -test('using side effects cache', async function (t) { +test('using side effects cache', async (t) => { const project = prepare(t) // Right now, hardlink does not work with side effects, so we specify copy as the packageImportMethod @@ -52,7 +52,7 @@ test('using side effects cache', async function (t) { t.ok(await exists(path.join('node_modules', 'runas', 'build', 'new-file.txt')), 'side effects cache correctly used') }) -test('readonly side effects cache', async function (t) { +test('readonly side effects cache', async (t) => { const project = prepare(t) const opts1 = await testDefaults({sideEffectsCache: true, verifyStoreIntegrity: false}) @@ -76,7 +76,7 @@ test('readonly side effects cache', async function (t) { t.notOk(await exists(path.join(opts2.store, 'localhost+4873', 'runas', '3.1.0', 'side_effects', `${process.platform}-${process.arch}-node-${process.version.split('.')[0]}`, 'package', 'build')), 'cache folder not created') }) -test('uploading errors do not interrupt installation', async function (t) { +test('uploading errors do not interrupt installation', async (t) => { const project = prepare(t) const opts = await testDefaults({sideEffectsCache: true}) diff --git a/test/install/store.ts b/test/install/store.ts index 1b5b26eed2..6bdd3f72f3 100644 --- a/test/install/store.ts +++ b/test/install/store.ts @@ -1,10 +1,10 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' import path = require('path') import rimraf = require('rimraf-then') -import {prepare, testDefaults} from '../utils' -import writeJsonFile = require('write-json-file') import {install, installPkgs} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import writeJsonFile = require('write-json-file') +import {prepare, testDefaults} from '../utils' const test = promisifyTape(tape) diff --git a/test/install/update.ts b/test/install/update.ts index 8a5b676abc..a77a7a5167 100644 --- a/test/install/update.ts +++ b/test/install/update.ts @@ -1,11 +1,11 @@ +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import { - prepare, addDistTag, + prepare, testDefaults, } from '../utils' -import {install, installPkgs} from 'supi' const test = promisifyTape(tape) diff --git a/test/install/updatingPkgJson.ts b/test/install/updatingPkgJson.ts index fd4609bf49..55e3c61093 100644 --- a/test/install/updatingPkgJson.ts +++ b/test/install/updatingPkgJson.ts @@ -1,16 +1,16 @@ +import readPkg = require('read-pkg') +import {installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import readPkg = require('read-pkg') import { - prepare, addDistTag, + prepare, testDefaults, } from '../utils' -import {installPkgs} from 'supi' const test = promisifyTape(tape) -test('save to package.json (rimraf@2.5.1)', async function (t) { +test('save to package.json (rimraf@2.5.1)', async (t) => { const project = prepare(t) await installPkgs(['rimraf@2.5.1'], await testDefaults({ save: true })) @@ -22,13 +22,13 @@ test('save to package.json (rimraf@2.5.1)', async function (t) { }) // NOTE: this works differently for global installations. See similar tests in global.ts -test("don't override existing spec in package.json on named installation", async function (t: tape.Test) { +test("don't override existing spec in package.json on named installation", async (t: tape.Test) => { const project = prepare(t, { dependencies: { - 'is-positive': '^2.0.0', // this will be kept as no newer version is available from the range 'is-negative': '^1.0.0', // this will be updated - sec: 'sindresorhus/sec', - } + 'is-positive': '^2.0.0', // this will be kept as no newer version is available from the range + 'sec': 'sindresorhus/sec', + }, }) await installPkgs(['is-positive'], await testDefaults()) await installPkgs(['is-negative'], await testDefaults()) @@ -39,13 +39,13 @@ test("don't override existing spec in package.json on named installation", async const pkgJson = await readPkg() t.deepEqual(pkgJson.dependencies, { - 'is-positive': '^2.0.0', 'is-negative': '^1.0.1', - sec: 'github:sindresorhus/sec', + 'is-positive': '^2.0.0', + 'sec': 'github:sindresorhus/sec', }) }) -test('saveDev scoped module to package.json (@rstacruz/tap-spec)', async function (t) { +test('saveDev scoped module to package.json (@rstacruz/tap-spec)', async (t) => { const project = prepare(t) await installPkgs(['@rstacruz/tap-spec'], await testDefaults({ saveDev: true })) @@ -56,7 +56,7 @@ test('saveDev scoped module to package.json (@rstacruz/tap-spec)', async functio t.deepEqual(pkgJson.devDependencies, { '@rstacruz/tap-spec': '^4.1.1' }, 'tap-spec has been added to devDependencies') }) -test('dependency should not be added to package.json if it is already there', async function (t: tape.Test) { +test('dependency should not be added to package.json if it is already there', async (t: tape.Test) => { await addDistTag('foo', '100.0.0', 'latest') await addDistTag('bar', '100.0.0', 'latest') @@ -72,14 +72,14 @@ test('dependency should not be added to package.json if it is already there', as const pkgJson = await readPkg({normalize: false}) t.deepEqual(pkgJson, { - name: 'project', - version: '0.0.0', devDependencies: { foo: '^100.0.0', }, + name: 'project', optionalDependencies: { bar: '^100.0.0', }, + version: '0.0.0', }, 'package.json was not changed') const shr = await project.loadShrinkwrap() @@ -91,7 +91,7 @@ test('dependency should not be added to package.json if it is already there', as t.ok(shr.packages['/bar/100.0.0'].optional, 'the `bar` package is marked as optional in shrinkwrap.yaml') }) -test('dependencies should be updated in the fields where they already are', async function (t: tape.Test) { +test('dependencies should be updated in the fields where they already are', async (t: tape.Test) => { await addDistTag('foo', '100.1.0', 'latest') await addDistTag('bar', '100.1.0', 'latest') @@ -107,18 +107,18 @@ test('dependencies should be updated in the fields where they already are', asyn const pkgJson = await readPkg({normalize: false}) t.deepEqual(pkgJson, { - name: 'project', - version: '0.0.0', devDependencies: { foo: '^100.1.0', }, + name: 'project', optionalDependencies: { bar: '^100.1.0', }, + version: '0.0.0', }, 'package.json updated dependencies in the correct properties') }) -test('dependency should be removed from the old field when installing it as a different type of dependency', async function (t: tape.Test) { +test('dependency should be removed from the old field when installing it as a different type of dependency', async (t: tape.Test) => { await addDistTag('foo', '100.0.0', 'latest') await addDistTag('bar', '100.0.0', 'latest') await addDistTag('qar', '100.0.0', 'latest') @@ -140,21 +140,21 @@ test('dependency should be removed from the old field when installing it as a di const pkgJson = await readPkg({normalize: false}) t.deepEqual(pkgJson, { - name: 'project', - version: '0.0.0', dependencies: { bar: '^100.0.0', }, devDependencies: { qar: '^100.0.0', }, + name: 'project', optionalDependencies: { foo: '^100.0.0', }, + version: '0.0.0', }, 'dependencies moved around correctly') }) -test('multiple save to package.json with `exact` versions (@rstacruz/tap-spec & rimraf@2.5.1) (in sorted order)', async function (t: tape.Test) { +test('multiple save to package.json with `exact` versions (@rstacruz/tap-spec & rimraf@2.5.1) (in sorted order)', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['rimraf@2.5.1', '@rstacruz/tap-spec@latest'], await testDefaults({ save: true, saveExact: true })) @@ -167,7 +167,7 @@ test('multiple save to package.json with `exact` versions (@rstacruz/tap-spec & const pkgJson = await readPkg() const expectedDeps = { '@rstacruz/tap-spec': '4.1.1', - rimraf: '2.5.1' + 'rimraf': '2.5.1', } t.deepEqual(pkgJson.dependencies, expectedDeps, 'tap-spec and rimraf have been added to dependencies') t.deepEqual(Object.keys(pkgJson.dependencies), Object.keys(expectedDeps), 'tap-spec and rimraf have been added to dependencies in sorted order') diff --git a/test/link.ts b/test/link.ts index 01e6fb8589..5d491ec953 100644 --- a/test/link.ts +++ b/test/link.ts @@ -1,26 +1,26 @@ +import sinon = require('sinon') import tape = require('tape') import promisifyTape from 'tape-promise' -import sinon = require('sinon') const test = promisifyTape(tape) const testOnly = promisifyTape(tape.only) +import ncpCB = require('ncp') import path = require('path') +import promisify = require('util.promisify') import { - prepare, isExecutable, pathToLocalPkg, + prepare, testDefaults, } from './utils' -import promisify = require('util.promisify') -import ncpCB = require('ncp') const ncp = promisify(ncpCB.ncp) +import exists = require('path-exists') import { - link, - linkToGlobal, - linkFromGlobal, installPkgs, + link, + linkFromGlobal, + linkToGlobal, RootLog, } from 'supi' -import exists = require('path-exists') import writeJsonFile = require('write-json-file') test('relative link', async (t: tape.Test) => { @@ -65,16 +65,16 @@ test('relative link is not rewritten by install', async (t: tape.Test) => { t.ok(project.requireModule('hello-world-js-bin/package.json').isLocal) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', + t.ok(reporter.calledWithMatch({ level: 'debug', linked: { - name: 'hello-world-js-bin', from: linkedPkgPath, + name: 'hello-world-js-bin', to: path.resolve('node_modules'), // TODO: the dependencyType should be `undefined` in this case }, - }), 'linked root dependency logged') + name: 'pnpm:root', + } as RootLog), 'linked root dependency logged') const wantedShrinkwrap = await project.loadShrinkwrap() t.equal(wantedShrinkwrap.dependencies['hello-world-js-bin'], 'link:../hello-world-js-bin', 'link still in wanted shrinkwrap') @@ -83,7 +83,7 @@ test('relative link is not rewritten by install', async (t: tape.Test) => { t.equal(currentShrinkwrap.dependencies['hello-world-js-bin'], 'link:../hello-world-js-bin', 'link still in wanted shrinkwrap') }) -test('global link', async function (t: tape.Test) { +test('global link', async (t: tape.Test) => { prepare(t) const projectPath = process.cwd() diff --git a/test/offline.ts b/test/offline.ts index 9d776cd35a..16e87c45ed 100644 --- a/test/offline.ts +++ b/test/offline.ts @@ -1,15 +1,15 @@ +import rimraf = require('rimraf-then') +import {install, installPkgs} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import { prepare, testDefaults, } from './utils' -import rimraf = require('rimraf-then') -import {installPkgs, install} from 'supi' const test = promisifyTape(tape) -test('offline installation fails when package meta not found in local registry mirror', async function (t) { +test('offline installation fails when package meta not found in local registry mirror', async (t) => { const project = prepare(t) try { @@ -20,7 +20,7 @@ test('offline installation fails when package meta not found in local registry m } }) -test('offline installation fails when package tarball not found in local registry mirror', async function (t) { +test('offline installation fails when package tarball not found in local registry mirror', async (t) => { const project = prepare(t) await installPkgs(['is-positive@3.0.0'], await testDefaults()) @@ -35,7 +35,7 @@ test('offline installation fails when package tarball not found in local registr } }) -test('successful offline installation', async function (t) { +test('successful offline installation', async (t) => { const project = prepare(t) await installPkgs(['is-positive@3.0.0'], await testDefaults({save: true})) diff --git a/test/packageImportMethods.ts b/test/packageImportMethods.ts index b1153afae2..4a007b384f 100644 --- a/test/packageImportMethods.ts +++ b/test/packageImportMethods.ts @@ -1,24 +1,24 @@ -import path = require('path') -import tape = require('tape') -import promisifyTape from 'tape-promise' -import writeYamlFile = require('write-yaml-file') -import exists = require('path-exists') -import { - prepare, - testDefaults, - addDistTag, -} from './utils' -import { - installPkgs, - install, - RootLog, -} from 'supi' +import {stripIndent} from 'common-tags' import loadJsonFile = require('load-json-file') -import writePkg = require('write-pkg') +import fs = require('mz/fs') +import path = require('path') +import exists = require('path-exists') import rimraf = require('rimraf-then') import sinon = require('sinon') -import {stripIndent} from 'common-tags' -import fs = require('mz/fs') +import { + install, + installPkgs, + RootLog, +} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import writePkg = require('write-pkg') +import writeYamlFile = require('write-yaml-file') +import { + addDistTag, + prepare, + testDefaults, +} from './utils' const test = promisifyTape(tape) diff --git a/test/prune.ts b/test/prune.ts index 731d852af6..34ffc545e3 100644 --- a/test/prune.ts +++ b/test/prune.ts @@ -1,13 +1,13 @@ import tape = require('tape') import promisifyTape from 'tape-promise' const test = promisifyTape(tape) -import path = require('path') -import {installPkgs, prune} from 'supi' -import {prepare, testDefaults} from './utils' -import exists = require('path-exists') import existsSymlink = require('exists-link') +import path = require('path') +import exists = require('path-exists') import readPkg = require('read-pkg') +import {installPkgs, prune} from 'supi' import writePkg = require('write-pkg') +import {prepare, testDefaults} from './utils' test('prune removes extraneous packages', async (t: tape.Test) => { const project = prepare(t) @@ -49,8 +49,8 @@ test('prune removes dev dependencies in production', async (t: tape.Test) => { await installPkgs(['is-negative@2.1.0'], await testDefaults({save: true})) await installPkgs(['fnumber@0.1.0'], await testDefaults({saveOptional: true})) await prune(await testDefaults({ - production: true, development: false, + production: true, })) await project.storeHasNot('is-positive', '2.0.0') diff --git a/test/rebuild.ts b/test/rebuild.ts index 9a925395ec..78850f332c 100644 --- a/test/rebuild.ts +++ b/test/rebuild.ts @@ -1,20 +1,20 @@ +import { + installPkgs, + rebuild, + rebuildPkgs, +} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' import { - prepare, isExecutable, pathToLocalPkg, + prepare, testDefaults, } from './utils' -import { - rebuild, - rebuildPkgs, - installPkgs, -} from 'supi' const test = promisifyTape(tape) -test('rebuilds dependencies', async function (t: tape.Test) { +test('rebuilds dependencies', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pre-and-postinstall-scripts-example', 'zkochan/install-scripts-example'], await testDefaults({saveDev: true, ignoreScripts: true})) @@ -37,7 +37,7 @@ test('rebuilds dependencies', async function (t: tape.Test) { } }) -test('rebuilds specific dependencies', async function (t: tape.Test) { +test('rebuilds specific dependencies', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pre-and-postinstall-scripts-example', 'zkochan/install-scripts-example'], await testDefaults({saveDev: true, ignoreScripts: true})) @@ -53,13 +53,13 @@ test('rebuilds specific dependencies', async function (t: tape.Test) { t.ok(typeof generatedByPostinstall === 'function', 'generatedByPostinstall() is available') }) -test('rebuild with pending option', async function (t: tape.Test) { +test('rebuild with pending option', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['pre-and-postinstall-scripts-example'], await testDefaults({ignoreScripts: true})) await installPkgs(['zkochan/install-scripts-example'], await testDefaults({ignoreScripts: true})) let modules = await project.loadModules() - t.doesNotEqual(modules['pendingBuilds'].length, 0) + t.doesNotEqual(modules.pendingBuilds.length, 0) await project.hasNot('pre-and-postinstall-scripts-example/generated-by-preinstall') await project.hasNot('pre-and-postinstall-scripts-example/generated-by-postinstall') @@ -67,10 +67,10 @@ test('rebuild with pending option', async function (t: tape.Test) { await project.hasNot('install-scripts-example-for-pnpm/generated-by-preinstall') await project.hasNot('install-scripts-example-for-pnpm/generated-by-postinstall') - await rebuild(await testDefaults({rawNpmConfig: {'pending': true}})) + await rebuild(await testDefaults({rawNpmConfig: {pending: true}})) modules = await project.loadModules() - t.equal(modules['pendingBuilds'].length, 0) + t.equal(modules.pendingBuilds.length, 0) { const generatedByPreinstall = project.requireModule('pre-and-postinstall-scripts-example/generated-by-preinstall') diff --git a/test/shrinkwrap.ts b/test/shrinkwrap.ts index f0582e2e60..d6b0e1abf7 100644 --- a/test/shrinkwrap.ts +++ b/test/shrinkwrap.ts @@ -1,35 +1,35 @@ -import path = require('path') -import tape = require('tape') -import promisifyTape from 'tape-promise' -import writeYamlFile = require('write-yaml-file') -import exists = require('path-exists') -import { - prepare, - testDefaults, - addDistTag, -} from './utils' -import { - installPkgs, - install, - uninstall, - RootLog, -} from 'supi' +import {stripIndent} from 'common-tags' import loadJsonFile = require('load-json-file') -import writePkg = require('write-pkg') +import fs = require('mz/fs') +import path = require('path') +import exists = require('path-exists') +import R = require('ramda') import rimraf = require('rimraf-then') import sinon = require('sinon') -import {stripIndent} from 'common-tags' -import fs = require('mz/fs') -import R = require('ramda') +import { + install, + installPkgs, + RootLog, + uninstall, +} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import writePkg = require('write-pkg') +import writeYamlFile = require('write-yaml-file') +import { + addDistTag, + prepare, + testDefaults, +} from './utils' const test = promisifyTape(tape) test.only = promisifyTape(tape.only) test.skip = promisifyTape(tape.skip) const SHRINKWRAP_WARN_LOG = { - name: 'pnpm', level: 'warn', message: 'A shrinkwrap.yaml file exists. The current configuration prohibits to read or write a shrinkwrap file', + name: 'pnpm', } test('shrinkwrap file has correct format', async (t: tape.Test) => { @@ -38,7 +38,7 @@ test('shrinkwrap file has correct format', async (t: tape.Test) => { await installPkgs(['pkg-with-1-dep', '@rstacruz/tap-spec@4.1.1', 'kevva/is-negative#1d7e288222b53a0cab90a331f1865220ec29560c'], await testDefaults({save: true})) const modules = await project.loadModules() - t.equal(modules['pendingBuilds'].length, 0) + t.equal(modules.pendingBuilds.length, 0) const shr = await project.loadShrinkwrap() const id = '/pkg-with-1-dep/100.0.0' @@ -85,7 +85,7 @@ test('shrinkwrap file has dev deps even when installing for prod only', async (t t.ok(shr.packages[id], `has resolution for ${id}`) }) -test('shrinkwrap with scoped package', async t => { +test('shrinkwrap with scoped package', async (t) => { const project = prepare(t, { dependencies: { '@types/semver': '^5.3.31', @@ -118,8 +118,6 @@ test('fail when shasum from shrinkwrap does not match with the actual one', asyn }) await writeYamlFile('shrinkwrap.yaml', { - version: 3, - registry: 'http://localhost:4873', dependencies: { 'is-negative': '2.1.0', }, @@ -131,6 +129,8 @@ test('fail when shasum from shrinkwrap does not match with the actual one', asyn }, }, }, + registry: 'http://localhost:4873', + version: 3, }) try { @@ -169,12 +169,10 @@ test('shrinkwrap not created when no deps in package.json', async (t: tape.Test) t.notOk(await exists('node_modules'), 'empty node_modules not created') }) -test('shrinkwrap removed when no deps in package.json', async t => { +test('shrinkwrap removed when no deps in package.json', async (t) => { const project = prepare(t) await writeYamlFile('shrinkwrap.yaml', { - version: 3, - registry: 'http://localhost:4873', dependencies: { 'is-negative': '2.1.0', }, @@ -185,6 +183,8 @@ test('shrinkwrap removed when no deps in package.json', async t => { }, }, }, + registry: 'http://localhost:4873', + version: 3, }) await install(await testDefaults()) @@ -198,19 +198,22 @@ test('shrinkwrap is fixed when it does not match package.json', async (t: tape.T 'is-negative': '^2.1.0', }, optionalDependencies: { - 'is-positive': '^3.1.0' - } + 'is-positive': '^3.1.0', + }, }) await writeYamlFile('shrinkwrap.yaml', { - version: 3, - registry: 'http://localhost:4873', dependencies: { + '@types/semver': '5.3.31', 'is-negative': '2.1.0', 'is-positive': '3.1.0', - '@types/semver': '5.3.31', }, packages: { + '/@types/semver/5.3.31': { + resolution: { + integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=', + }, + }, '/is-negative/2.1.0': { resolution: { tarball: 'http://localhost:4873/is-negative/-/is-negative-2.1.0.tgz', @@ -218,20 +221,17 @@ test('shrinkwrap is fixed when it does not match package.json', async (t: tape.T }, '/is-positive/3.1.0': { resolution: { - integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=' - }, - }, - '/@types/semver/5.3.31': { - resolution: { - integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=', + integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=', }, }, }, + registry: 'http://localhost:4873', specifiers: { + '@types/semver': '5.3.31', 'is-negative': '^2.1.0', 'is-positive': '^3.1.0', - '@types/semver': '5.3.31', - } + }, + version: 3, }) const reporter = sinon.spy() @@ -254,21 +254,24 @@ test('shrinkwrap is fixed when it does not match package.json', async (t: tape.T test('doing named installation when shrinkwrap.yaml exists already', async (t: tape.Test) => { const project = prepare(t, { dependencies: { + '@types/semver': '5.3.31', 'is-negative': '^2.1.0', 'is-positive': '^3.1.0', - '@types/semver': '5.3.31', - } + }, }) await writeYamlFile('shrinkwrap.yaml', { - version: 3, - registry: 'http://localhost:4873', dependencies: { + '@types/semver': '5.3.31', 'is-negative': '2.1.0', 'is-positive': '3.1.0', - '@types/semver': '5.3.31', }, packages: { + '/@types/semver/5.3.31': { + resolution: { + integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=', + }, + }, '/is-negative/2.1.0': { resolution: { tarball: 'http://localhost:4873/is-negative/-/is-negative-2.1.0.tgz', @@ -276,20 +279,17 @@ test('doing named installation when shrinkwrap.yaml exists already', async (t: t }, '/is-positive/3.1.0': { resolution: { - integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=' - }, - }, - '/@types/semver/5.3.31': { - resolution: { - integrity: 'sha1-uZnX2TX0P1IHsBsA094ghS9Mp18=', + integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=', }, }, }, + registry: 'http://localhost:4873', specifiers: { + '@types/semver': '5.3.31', 'is-negative': '^2.1.0', 'is-positive': '^3.1.0', - '@types/semver': '5.3.31', - } + }, + version: 3, }) const reporter = sinon.spy() @@ -314,7 +314,7 @@ test('respects shrinkwrap.yaml for top dependencies', async (t: tape.Test) => { // }) const pkgs = ['foo', 'bar', 'qar'] - await Promise.all(pkgs.map(pkgName => addDistTag(pkgName, '100.0.0', 'latest'))) + await Promise.all(pkgs.map((pkgName) => addDistTag(pkgName, '100.0.0', 'latest'))) await installPkgs(['foo'], await testDefaults({save: true, reporter})) // t.equal(reporter.withArgs(fooProgress).callCount, 1, 'reported foo once') @@ -328,7 +328,7 @@ test('respects shrinkwrap.yaml for top dependencies', async (t: tape.Test) => { t.equal((await loadJsonFile(path.resolve('node_modules', '.localhost+4873', 'foobar', '100.0.0', 'node_modules', 'foo', 'package.json'))).version, '100.0.0') t.equal((await loadJsonFile(path.resolve('node_modules', '.localhost+4873', 'foobar', '100.0.0', 'node_modules', 'bar', 'package.json'))).version, '100.0.0') - await Promise.all(pkgs.map(pkgName => addDistTag(pkgName, '100.1.0', 'latest'))) + await Promise.all(pkgs.map((pkgName) => addDistTag(pkgName, '100.1.0', 'latest'))) await rimraf('node_modules') await rimraf(path.join('..', '.store')) @@ -338,10 +338,10 @@ test('respects shrinkwrap.yaml for top dependencies', async (t: tape.Test) => { // shouldn't care about what the registry in npmrc is // the one in shrinkwrap should be used await install(await testDefaults({ - registry: 'https://registry.npmjs.org', rawNpmConfig: { registry: 'https://registry.npmjs.org', }, + registry: 'https://registry.npmjs.org', reporter, })) @@ -376,7 +376,7 @@ test('subdeps are updated on repeat install if outer shrinkwrap.yaml does not ma }, } - shr.packages['/pkg-with-1-dep/100.0.0']['dependencies']['dep-of-pkg-with-1-dep'] = '100.1.0' + shr.packages['/pkg-with-1-dep/100.0.0'].dependencies['dep-of-pkg-with-1-dep'] = '100.1.0' await writeYamlFile('shrinkwrap.yaml', shr) @@ -451,7 +451,7 @@ test('package is not marked dev if it is also a subdep of a regular dependency', const shr = await project.loadShrinkwrap() - t.notOk(shr.packages['/dep-of-pkg-with-1-dep/100.0.0']['dev'], 'package is not marked as dev') + t.notOk(shr.packages['/dep-of-pkg-with-1-dep/100.0.0'].dev, 'package is not marked as dev') }) test('package is not marked optional if it is also a subdep of a regular dependency', async (t: tape.Test) => { @@ -464,15 +464,15 @@ test('package is not marked optional if it is also a subdep of a regular depende const shr = await project.loadShrinkwrap() - t.notOk(shr.packages['/dep-of-pkg-with-1-dep/100.0.0']['optional'], 'package is not marked as optional') + t.notOk(shr.packages['/dep-of-pkg-with-1-dep/100.0.0'].optional, 'package is not marked as optional') }) -test('scoped module from different registry', async function (t: tape.Test) { +test('scoped module from different registry', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['@zkochan/foo', 'is-positive'], await testDefaults({ rawNpmConfig: { - '@zkochan:registry': 'https://registry.npmjs.org/' - } + '@zkochan:registry': 'https://registry.npmjs.org/', + }, })) const m = project.requireModule('@zkochan/foo') @@ -483,7 +483,7 @@ test('scoped module from different registry', async function (t: tape.Test) { t.deepEqual(shr, { dependencies: { '@zkochan/foo': 'registry.npmjs.org/@zkochan/foo/1.0.0', - 'is-positive': '3.1.0' + 'is-positive': '3.1.0', }, packages: { '/is-positive/3.1.0': { @@ -492,27 +492,27 @@ test('scoped module from different registry', async function (t: tape.Test) { node: '>=0.10.0', }, resolution: { - integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=' - } + integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=', + }, }, 'registry.npmjs.org/@zkochan/foo/1.0.0': { - name: '@zkochan/foo', dev: false, - version: '1.0.0', + name: '@zkochan/foo', resolution: { integrity: 'sha512-IFvrYpq7E6BqKex7A7czIFnFncPiUVdhSzGhAOWpp8RlkXns4y/9ZdynxaA/e0VkihRxQkihE2pTyvxjfe/wBg==', registry: 'https://registry.npmjs.org/', - tarball: 'https://registry.npmjs.org/@zkochan/foo/-/foo-1.0.0.tgz' - } - } + tarball: 'https://registry.npmjs.org/@zkochan/foo/-/foo-1.0.0.tgz', + }, + version: '1.0.0', + }, }, registry: 'http://localhost:4873/', + shrinkwrapMinorVersion: 4, + shrinkwrapVersion: 3, specifiers: { '@zkochan/foo': '^1.0.0', 'is-positive': '^3.1.0', }, - shrinkwrapVersion: 3, - shrinkwrapMinorVersion: 4, }) }) @@ -531,7 +531,7 @@ test('repeat install with no inner shrinkwrap should not rewrite packages in nod // Skipped because the npm-registry.compass.com server was down // might be a good idea to mock it -test['skip']('installing from shrinkwrap when using npm enterprise', async (t: tape.Test) => { +test.skip('installing from shrinkwrap when using npm enterprise', async (t: tape.Test) => { const project = prepare(t) const opts = await testDefaults({registry: 'https://npm-registry.compass.com/'}) @@ -542,7 +542,7 @@ test['skip']('installing from shrinkwrap when using npm enterprise', async (t: t t.deepEqual(shr, { dependencies: { - 'is-positive': '3.1.0' + 'is-positive': '3.1.0', }, packages: { '/is-positive/3.1.0': { @@ -552,16 +552,16 @@ test['skip']('installing from shrinkwrap when using npm enterprise', async (t: t }, resolution: { integrity: 'sha1-hX21hKG6XRyymAUn/DtsQ103sP0=', - tarball: '/i/is-positive/_attachments/is-positive-3.1.0.tgz' - } + tarball: '/i/is-positive/_attachments/is-positive-3.1.0.tgz', + }, }, }, registry: 'https://npm-registry.compass.com/', + shrinkwrapMinorVersion: 4, + shrinkwrapVersion: 3, specifiers: { 'is-positive': '^3.1.0', }, - shrinkwrapVersion: 3, - shrinkwrapMinorVersion: 4, }) await rimraf(opts.store) @@ -575,8 +575,8 @@ test['skip']('installing from shrinkwrap when using npm enterprise', async (t: t test('packages are placed in devDependencies even if they are present as non-dev as well', async (t: tape.Test) => { const project = prepare(t, { devDependencies: { - 'pkg-with-1-dep': '^1.0.0', 'dep-of-pkg-with-1-dep': '^1.1.0', + 'pkg-with-1-dep': '^1.0.0', }, }) @@ -590,24 +590,24 @@ test('packages are placed in devDependencies even if they are present as non-dev t.ok(shr.devDependencies['dep-of-pkg-with-1-dep']) t.ok(shr.devDependencies['pkg-with-1-dep']) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', - level: 'info', + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'dev', name: 'dep-of-pkg-with-1-dep', version: '1.1.0', - dependencyType: 'dev', }, - }), 'dep-of-pkg-with-1-dep added to root') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', level: 'info', + name: 'pnpm:root', + } as RootLog), 'dep-of-pkg-with-1-dep added to root') + t.ok(reporter.calledWithMatch({ added: { + dependencyType: 'dev', name: 'pkg-with-1-dep', version: '1.0.0', - dependencyType: 'dev', }, - }), 'pkg-with-1-dep added to root') + level: 'info', + name: 'pnpm:root', + } as RootLog), 'pkg-with-1-dep added to root') }) // This testcase verifies that pnpm is not failing when trying to preserve dependencies. @@ -710,7 +710,7 @@ test('pendingBuilds gets updated if install removes packages', async (t: tape.Te await install(await testDefaults({ ignoreScripts: true })) const modules2 = await project.loadModules() - t.ok(modules1['pendingBuilds'].length > modules2['pendingBuilds'].length, 'pendingBuilds gets updated when install removes packages') + t.ok(modules1.pendingBuilds.length > modules2.pendingBuilds.length, 'pendingBuilds gets updated when install removes packages') }) test('dev properties are correctly updated on named install', async (t: tape.Test) => { @@ -720,7 +720,7 @@ test('dev properties are correctly updated on named install', async (t: tape.Tes await installPkgs(['foo@npm:inflight@1.0.6'], await testDefaults({})) const shr = await project.loadShrinkwrap() - t.deepEqual(R.values(shr.packages).filter(dep => typeof dep.dev !== 'undefined'), [], 'there are 0 packages with dev property in shrinkwrap.yaml') + t.deepEqual(R.values(shr.packages).filter((dep) => typeof dep.dev !== 'undefined'), [], 'there are 0 packages with dev property in shrinkwrap.yaml') }) test('optional properties are correctly updated on named install', async (t: tape.Test) => { @@ -730,13 +730,13 @@ test('optional properties are correctly updated on named install', async (t: tap await installPkgs(['foo@npm:inflight@1.0.6'], await testDefaults({})) const shr = await project.loadShrinkwrap() - t.deepEqual(R.values(shr.packages).filter(dep => typeof dep.optional !== 'undefined'), [], 'there are 0 packages with optional property in shrinkwrap.yaml') + t.deepEqual(R.values(shr.packages).filter((dep) => typeof dep.optional !== 'undefined'), [], 'there are 0 packages with optional property in shrinkwrap.yaml') }) test('dev property is correctly set for package that is duplicated to both the dependencies and devDependencies group', async (t: tape.Test) => { const project = prepare(t) - //TODO: use a smaller package for testing + // TODO: use a smaller package for testing await installPkgs(['overlap@2.2.8'], await testDefaults()) const shr = await project.loadShrinkwrap() @@ -764,8 +764,6 @@ test('shrinkwrap is ignored when shrinkwrap = false', async (t: tape.Test) => { }) await writeYamlFile('shrinkwrap.yaml', { - version: 3, - registry: 'http://localhost:4873', dependencies: { 'is-negative': '2.1.0', }, @@ -777,6 +775,8 @@ test('shrinkwrap is ignored when shrinkwrap = false', async (t: tape.Test) => { }, }, }, + registry: 'http://localhost:4873', + version: 3, }) const reporter = sinon.spy() diff --git a/test/storePrune.ts b/test/storePrune.ts index 50fa3b4653..f398131c00 100644 --- a/test/storePrune.ts +++ b/test/storePrune.ts @@ -1,16 +1,16 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' -import rimraf = require('rimraf-then') -import {prepare, testDefaults} from './utils' -import { - storePrune, - installPkgs, - uninstall, -} from 'supi' -import sinon = require('sinon') +import loadJsonFile = require('load-json-file') import exists = require('path-exists') import R = require('ramda') -import loadJsonFile = require('load-json-file') +import rimraf = require('rimraf-then') +import sinon = require('sinon') +import { + installPkgs, + storePrune, + uninstall, +} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import {prepare, testDefaults} from './utils' const test = promisifyTape(tape) @@ -63,7 +63,7 @@ test('remove packages that are used by project that no longer exist', async (t: t.notOk(await exists(pkgInStore)) }) -test('keep dependencies used by others', async function (t: tape.Test) { +test('keep dependencies used by others', async (t: tape.Test) => { const project = prepare(t) await installPkgs(['camelcase-keys@3.0.0'], await testDefaults({ save: true })) await installPkgs(['hastscript@3.0.0'], await testDefaults({ saveDev: true })) @@ -84,7 +84,7 @@ test('keep dependencies used by others', async function (t: tape.Test) { const shr = await project.loadShrinkwrap() t.notOk(R.isEmpty(shr.packages)) - R.toPairs(shr.packages).forEach(pair => t.ok(pair[1]['dev'], `${pair[0]} is dev`)) + R.toPairs(shr.packages).forEach((pair) => t.ok(pair[1].dev, `${pair[0]} is dev`)) await storePrune(await testDefaults()) diff --git a/test/storeStatus.ts b/test/storeStatus.ts index f45fffce94..6dc568f274 100644 --- a/test/storeStatus.ts +++ b/test/storeStatus.ts @@ -1,12 +1,12 @@ +import rimraf = require('rimraf-then') +import {installPkgs, storeStatus} from 'supi' import tape = require('tape') import promisifyTape from 'tape-promise' -import rimraf = require('rimraf-then') import {prepare, testDefaults} from './utils' -import {storeStatus, installPkgs} from 'supi' const test = promisifyTape(tape) -test('store status returns empty array when store was not modified', async function (t: tape.Test) { +test('store status returns empty array when store was not modified', async (t: tape.Test) => { const project = prepare(t) const opts = await testDefaults() @@ -17,7 +17,7 @@ test('store status returns empty array when store was not modified', async funct t.equal(mutatedPkgs && mutatedPkgs.length, 0, 'no packages were modified') }) -test('store status does not fail on not installed optional dependencies', async function (t: tape.Test) { +test('store status does not fail on not installed optional dependencies', async (t: tape.Test) => { const project = prepare(t) const opts = await testDefaults({saveOptional: true}) @@ -28,7 +28,7 @@ test('store status does not fail on not installed optional dependencies', async t.equal(mutatedPkgs && mutatedPkgs.length, 0, 'no packages were modified') }) -test('store status returns path to the modified package', async function (t: tape.Test) { +test('store status returns path to the modified package', async (t: tape.Test) => { const project = prepare(t) const opts = await testDefaults() diff --git a/test/uninstall.ts b/test/uninstall.ts index 2d4e742214..a7e65049a1 100644 --- a/test/uninstall.ts +++ b/test/uninstall.ts @@ -1,27 +1,27 @@ import tape = require('tape') import promisifyTape from 'tape-promise' const test = promisifyTape(tape) +import existsSymlink = require('exists-link') +import ncpCB = require('ncp') import path = require('path') import exists = require('path-exists') -import existsSymlink = require('exists-link') import readPkg = require('read-pkg') -import ncpCB = require('ncp') -import { - prepare, - testDefaults, - pathToLocalPkg, -} from './utils' +import sinon = require('sinon') import { installPkgs, - uninstall, link, - storePrune, + PackageJsonLog, RootLog, StatsLog, - PackageJsonLog, + storePrune, + uninstall, } from 'supi' import promisify = require('util.promisify') -import sinon = require('sinon') +import { + pathToLocalPkg, + prepare, + testDefaults, +} from './utils' const ncp = promisify(ncpCB.ncp) @@ -33,39 +33,39 @@ test('uninstall package with no dependencies', async (t: tape.Test) => { const reporter = sinon.spy() await uninstall(['is-negative'], await testDefaults({ save: true, reporter })) - t.ok(reporter.calledWithMatch({ - name: 'pnpm:package-json', - level: 'debug', + t.ok(reporter.calledWithMatch({ initial: { - name: 'project', - version: '0.0.0', dependencies: { 'is-negative': '^2.1.0', }, + name: 'project', + version: '0.0.0', }, - }), 'initial package.json logged') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:stats', level: 'debug', + name: 'pnpm:package-json', + } as PackageJsonLog), 'initial package.json logged') + t.ok(reporter.calledWithMatch({ + level: 'debug', + name: 'pnpm:stats', removed: 1, - }), 'reported info message about removing orphans') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:root', + } as StatsLog), 'reported info message about removing orphans') + t.ok(reporter.calledWithMatch({ level: 'info', + name: 'pnpm:root', removed: { + dependencyType: 'prod', name: 'is-negative', version: '2.1.0', - dependencyType: 'prod', }, - }), 'removing root dependency reported') - t.ok(reporter.calledWithMatch({ - name: 'pnpm:package-json', + } as RootLog), 'removing root dependency reported') + t.ok(reporter.calledWithMatch({ level: 'debug', + name: 'pnpm:package-json', updated: { name: 'project', version: '0.0.0', }, - }), 'updated package.json logged') + } as PackageJsonLog), 'updated package.json logged') // uninstall does not remove packages from store // even if they become unreferenced @@ -77,7 +77,7 @@ test('uninstall package with no dependencies', async (t: tape.Test) => { t.equal(pkgJson.dependencies, undefined, 'is-negative has been removed from dependencies') }) -test('uninstall scoped package', async function (t) { +test('uninstall scoped package', async (t) => { const project = prepare(t) await installPkgs(['@zkochan/logger@0.1.0'], await testDefaults({ save: true })) await uninstall(['@zkochan/logger'], await testDefaults({ save: true })) @@ -103,7 +103,7 @@ test('uninstall tarball dependency', async (t: tape.Test) => { t.equal(pkgJson.dependencies, undefined, 'is-array has been removed from dependencies') }) -test('uninstall package with dependencies and do not touch other deps', async function (t) { +test('uninstall package with dependencies and do not touch other deps', async (t) => { const project = prepare(t) await installPkgs(['is-negative@2.1.0', 'camelcase-keys@3.0.0'], await testDefaults({ save: true })) await uninstall(['camelcase-keys'], await testDefaults({ save: true })) @@ -134,7 +134,7 @@ test('uninstall package with dependencies and do not touch other deps', async fu }, 'camelcase-keys removed from shrinkwrap specifiers') }) -test('uninstall package with its bin files', async function (t) { +test('uninstall package with its bin files', async (t) => { prepare(t) await installPkgs(['sh-hello-world@1.0.1'], await testDefaults({ save: true })) await uninstall(['sh-hello-world'], await testDefaults({ save: true })) @@ -166,11 +166,11 @@ test('pendingBuilds gets updated after uninstall', async (t: tape.Test) => { await installPkgs(['is-negative@2.1.0', 'sh-hello-world@1.0.1'], await testDefaults({save: true, ignoreScripts: true})) const modules1 = await project.loadModules() - t.doesNotEqual(modules1['pendingBuilds'].length, 0, 'installPkgs should update pendingBuilds') + t.doesNotEqual(modules1.pendingBuilds.length, 0, 'installPkgs should update pendingBuilds') await uninstall(['sh-hello-world'], await testDefaults({save: true})) const modules2 = await project.loadModules() - t.doesNotEqual(modules2['pendingBuilds'].length, 0, 'uninstall should not remove all the pendingBuilds') - t.ok(modules1['pendingBuilds'].length > modules2['pendingBuilds'].length, 'uninstall should update pendingBuilds') + t.doesNotEqual(modules2.pendingBuilds.length, 0, 'uninstall should not remove all the pendingBuilds') + t.ok(modules1.pendingBuilds.length > modules2.pendingBuilds.length, 'uninstall should update pendingBuilds') }) diff --git a/test/unlink.ts b/test/unlink.ts index 1fec85367a..6d168c2a80 100644 --- a/test/unlink.ts +++ b/test/unlink.ts @@ -1,42 +1,42 @@ -import tape = require('tape') -import promisifyTape from 'tape-promise' -import { - prepare, - testDefaults, - pathToLocalPkg, - addDistTag, -} from './utils' -import writeJsonFile = require('write-json-file') -import loadJsonFile = require('load-json-file') -import { - link, - unlinkPkgs, - unlink, - installPkgs, -} from 'supi' import isInnerLink = require('is-inner-link') +import loadJsonFile = require('load-json-file') import path = require('path') import exists = require('path-exists') import sinon = require('sinon') +import { + installPkgs, + link, + unlink, + unlinkPkgs, +} from 'supi' +import tape = require('tape') +import promisifyTape from 'tape-promise' +import writeJsonFile = require('write-json-file') +import { + addDistTag, + pathToLocalPkg, + prepare, + testDefaults, +} from './utils' const test = promisifyTape(tape) test('unlink 1 package that exists in package.json', async (t: tape.Test) => { const project = prepare(t, { dependencies: { - 'is-subdir': '^1.0.0', 'is-positive': '^1.0.0', - } + 'is-subdir': '^1.0.0', + }, }) process.chdir('..') await Promise.all([ writeJsonFile('is-subdir/package.json', { + dependencies: { + 'is-windows': '^1.0.0', + }, name: 'is-subdir', version: '1.0.0', - dependencies: { - 'is-windows': '^1.0.0' - } }), writeJsonFile('is-positive/package.json', { name: 'is-positive', @@ -105,18 +105,18 @@ test('unlink 2 packages. One of them exists in package.json', async (t: tape.Tes const project = prepare(t, { dependencies: { 'is-subdir': '^1.0.0', - } + }, }) const opts = await testDefaults({prefix: process.cwd()}) process.chdir('..') await Promise.all([ writeJsonFile('is-subdir/package.json', { + dependencies: { + 'is-windows': '^1.0.0', + }, name: 'is-subdir', version: '1.0.0', - dependencies: { - 'is-windows': '^1.0.0' - } }), writeJsonFile('is-positive/package.json', { name: 'is-positive', @@ -136,20 +136,20 @@ test('unlink 2 packages. One of them exists in package.json', async (t: tape.Tes test('unlink all packages', async (t: tape.Test) => { const project = prepare(t, { dependencies: { - 'is-subdir': '^1.0.0', '@zkochan/logger': '^0.1.0', - } + 'is-subdir': '^1.0.0', + }, }) const opts = await testDefaults({prefix: process.cwd()}) process.chdir('..') await Promise.all([ writeJsonFile('is-subdir/package.json', { + dependencies: { + 'is-windows': '^1.0.0', + }, name: 'is-subdir', version: '1.0.0', - dependencies: { - 'is-windows': '^1.0.0' - } }), writeJsonFile('logger/package.json', { name: '@zkochan/logger', diff --git a/test/utils/index.ts b/test/utils/index.ts index 10fe98449a..c14be06b07 100644 --- a/test/utils/index.ts +++ b/test/utils/index.ts @@ -1,7 +1,7 @@ +import {add as addDistTag} from './distTags' +import isExecutable from './isExecutable' import prepare from './prepare' import testDefaults from './testDefaults' -import isExecutable from './isExecutable' -import {add as addDistTag} from './distTags' export { prepare, diff --git a/test/utils/isExecutable.ts b/test/utils/isExecutable.ts index 91420d009d..f759b76474 100644 --- a/test/utils/isExecutable.ts +++ b/test/utils/isExecutable.ts @@ -1,9 +1,9 @@ -import isexe = require('isexe') -import fs = require('mz/fs') -import {Test} from 'tape' -import semver = require('semver') import {Stats} from 'fs' import isWindows = require('is-windows') +import isexe = require('isexe') +import fs = require('mz/fs') +import semver = require('semver') +import {Test} from 'tape' const IS_WINDOWS = isWindows() diff --git a/test/utils/prepare.ts b/test/utils/prepare.ts index 52f93590ff..2dbc8d932a 100644 --- a/test/utils/prepare.ts +++ b/test/utils/prepare.ts @@ -1,13 +1,13 @@ -import mkdirp = require('mkdirp') -import fs = require('fs') -import path = require('path') import {stripIndent} from 'common-tags' -import {Test} from 'tape' -import exists = require('path-exists') +import fs = require('fs') import loadYamlFile = require('load-yaml-file') +import mkdirp = require('mkdirp') +import path = require('path') +import exists = require('path-exists') +import {Test} from 'tape' +import writePkg = require('write-pkg') import {Modules, read as readModules} from '../../src/fs/modulesController' import isExecutable from './isExecutable' -import writePkg = require('write-pkg') // the testing folder should be outside of the project to avoid lookup in the project's node_modules const tmpPath = path.join(__dirname, '..', '..', '..', '.tmp') @@ -15,7 +15,7 @@ mkdirp.sync(tmpPath) let dirNumber = 0 -export default function prepare (t: Test, pkg?: Object) { +export default function prepare (t: Test, pkg?: object) { process.env.NPM_CONFIG_REGISTRY = 'http://localhost:4873/' process.env.NPM_CONFIG_STORE_PATH = '../.store' process.env.NPM_CONFIG_SILENT = 'true' @@ -35,13 +35,13 @@ export default function prepare (t: Test, pkg?: Object) { requireModule (pkgName: string) { return require(path.join(modules, pkgName)) }, - has: async function (pkgName: string) { + async has (pkgName: string) { t.ok(await exists(path.join(modules, pkgName)), `${pkgName} is in node_modules`) }, - hasNot: async function (pkgName: string) { + async hasNot (pkgName: string) { t.notOk(await exists(path.join(modules, pkgName)), `${pkgName} is not in node_modules`) }, - getStorePath: async function () { + async getStorePath () { if (!cachedStorePath) { const modulesYaml = await readModules(modules) if (!modulesYaml) { @@ -51,18 +51,18 @@ export default function prepare (t: Test, pkg?: Object) { } return cachedStorePath }, - resolve: async function (pkgName: string, version?: string, relativePath?: string) { + async resolve (pkgName: string, version?: string, relativePath?: string) { const pkgFolder = version ? path.join('localhost+4873', pkgName, version) : pkgName if (relativePath) { return path.join(await project.getStorePath(), pkgFolder, 'package', relativePath) } return path.join(await project.getStorePath(), pkgFolder, 'package') }, - storeHas: async function (pkgName: string, version?: string) { + async storeHas (pkgName: string, version?: string) { const pathToCheck = await project.resolve(pkgName, version) t.ok(await exists(pathToCheck), `${pkgName}@${version} is in store (at ${pathToCheck})`) }, - storeHasNot: async function (pkgName: string, version?: string) { + async storeHasNot (pkgName: string, version?: string) { try { const pathToCheck = await project.resolve(pkgName, version) t.notOk(await exists(pathToCheck), `${pkgName}@${version} is not in store (at ${pathToCheck})`) @@ -74,17 +74,9 @@ export default function prepare (t: Test, pkg?: Object) { throw err } }, - isExecutable: function (pathToExe: string) { + isExecutable (pathToExe: string) { return isExecutable(t, path.join(modules, pathToExe)) }, - loadShrinkwrap: async () => { - try { - return await loadYamlFile('shrinkwrap.yaml') // tslint:disable-line - } catch (err) { - if (err.code === 'ENOENT') return null - throw err - } - }, loadCurrentShrinkwrap: async () => { try { return await loadYamlFile('node_modules/.shrinkwrap.yaml') // tslint:disable-line @@ -101,6 +93,14 @@ export default function prepare (t: Test, pkg?: Object) { throw err } }, + loadShrinkwrap: async () => { + try { + return await loadYamlFile('shrinkwrap.yaml') // tslint:disable-line + } catch (err) { + if (err.code === 'ENOENT') return null + throw err + } + }, rewriteDependencies: async (deps: object) => { pkgJson = Object.assign(pkgJson, { dependencies: deps }) writePkg.sync(pkgTmpPath, pkgJson) diff --git a/test/utils/testDefaults.ts b/test/utils/testDefaults.ts index bcf5393c8b..8721edb29f 100644 --- a/test/utils/testDefaults.ts +++ b/test/utils/testDefaults.ts @@ -1,17 +1,17 @@ -import storePath from '@pnpm/store-path' -import {InstallOptions} from 'supi' -import path = require('path') -import createStore from 'package-store' import createFetcher from '@pnpm/default-fetcher' import createResolver from '@pnpm/default-resolver' +import storePath from '@pnpm/store-path' +import createStore from 'package-store' +import path = require('path') +import {InstallOptions} from 'supi' const registry = 'http://localhost:4873/' const retryOpts = { fetchRetries: 2, fetchRetryFactor: 10, - fetchRetryMintimeout: 10_000, fetchRetryMaxtimeout: 60_000, + fetchRetryMintimeout: 10_000, } export default async function testDefaults ( @@ -34,21 +34,21 @@ export default async function testDefaults ( }), createFetcher({ alwaysAuth: true, - registry, rawNpmConfig, + registry, ...retryOpts, ...fetchOpts, }) as {}, { - store, locks: path.join(store, '_locks'), + store, ...storeOpts, - } + }, ) return { + registry, store, storeController, - registry, ...opts, } } diff --git a/tslint.json b/tslint.json index 7891ff2b2c..abb0506087 100644 --- a/tslint.json +++ b/tslint.json @@ -1,4 +1,5 @@ { + "extends": "tslint:recommended", "rules": { "curly": false, "eofline": false, @@ -15,6 +16,8 @@ "no-use-before-declare": true, "no-var-requires": true, "no-require-imports": false, + "space-before-function-paren": [true, "always"], + "interface-name": [true, "never-prefix"], "one-line": [true, "check-else", "check-whitespace",