chore: rebase conflicts

This commit is contained in:
Marc 2023-03-26 11:42:59 -04:00
parent 3c8cb50170
commit d650690081
Signed by: marc
GPG key ID: 048E042F22B5DC79
13 changed files with 432 additions and 2295 deletions

View file

@ -1,13 +0,0 @@
module.exports = {
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
extends: [
"@tophat/eslint-config/base",
"@tophat/eslint-config/jest",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
parserOptions: {
project: ['./tsconfig.eslint.json']
}
}

View file

@ -30,8 +30,8 @@
"prepack": "yarn build",
"prebuild": "rm -rf dist",
"build": "tsc --project .",
"lint": "eslint tests/**/*.ts src/**/*.ts",
"lint:fix": "yarn lint --fix",
"lint": "yarn rome format src tests && yarn rome check src tests",
"lint:fix": "yarn rome format src tests --write && yarn rome check src tests --apply",
"test": "jest tests",
"test:watch": "yarn test --watchAll",
"test:coverage": "yarn test --coverage",
@ -39,19 +39,10 @@
"types:watch": "yarn types --watch"
},
"devDependencies": {
"@tophat/eslint-config": "^6.0.1",
"@types/jest": "^29.5.0",
"@types/node": "^18.15.5",
"@typescript-eslint/eslint-plugin": "^5.56.0",
"@typescript-eslint/parser": "^5.56.0",
"eslint": "^8.36.0",
"eslint-config-prettier": "^8.8.0",
"eslint-import-resolver-node": "^0.3.7",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-jest": "^27.2.1",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^29.5.0",
"prettier": "^2.8.5",
"rome": "^11.0.0",
"ts-jest": "^29.0.5",
"typescript": "^4.3.0"
}

13
rome.json Normal file
View file

@ -0,0 +1,13 @@
{
"formatter": {
"enabled": true,
"lineWidth": 120
},
"javascript": {
"formatter": {
"semicolons": "asNeeded",
"quoteStyle": "single"
}
}
}

View file

@ -5,5 +5,5 @@ import packwatch from '.'
const isUpdatingManifest = process.argv.includes('--update-manifest')
const cwd = process.cwd()
packwatch({ cwd, isUpdatingManifest })
.catch(() => process.exit(1))
.then(() => process.exit(0))
.catch(() => process.exit(1))
.then(() => process.exit(0))

View file

@ -3,105 +3,85 @@ import { join, resolve } from 'path'
import { assertInPackageRoot } from './invariants'
import logger from './logger'
import {
createOrUpdateManifest,
getCurrentPackageStats,
getPreviousPackageStats,
mergeDefaultArguments,
} from './utils'
import { createOrUpdateManifest, getCurrentPackageStats, getPreviousPackageStats, mergeDefaultArguments } from './utils'
import type { PackwatchArguments } from './types'
const MANIFEST_FILENAME = '.packwatch.json'
export default async function packwatch(
args: Partial<PackwatchArguments>,
): Promise<void> {
const { cwd, isUpdatingManifest } = mergeDefaultArguments(args)
export default async function packwatch(args: Partial<PackwatchArguments>): Promise<void> {
const { cwd, isUpdatingManifest } = mergeDefaultArguments(args)
const manifestPath = resolve(join(cwd, MANIFEST_FILENAME))
const manifestPath = resolve(join(cwd, MANIFEST_FILENAME))
assertInPackageRoot(cwd)
assertInPackageRoot(cwd)
const currentStats = getCurrentPackageStats(cwd)
const currentStats = getCurrentPackageStats(cwd)
/*
* If there is no manifest file yet, we can use the current package stats as
* a base to build one. The current package size becomes the limit.
*/
/*
* If there is no manifest file yet, we can use the current package stats as
* a base to build one. The current package size becomes the limit.
*/
if (!existsSync(manifestPath)) {
createOrUpdateManifest({ manifestPath, current: currentStats })
logger.warn(
`📝 No Manifest to compare against! Current package stats written to ${MANIFEST_FILENAME}!\nPackage size (${currentStats.packageSize}) adopted as new limit.`,
)
if (!existsSync(manifestPath)) {
createOrUpdateManifest({ manifestPath, current: currentStats })
logger.warn(
`📝 No Manifest to compare against! Current package stats written to ${MANIFEST_FILENAME}!\nPackage size (${currentStats.packageSize}) adopted as new limit.`,
)
if (!isUpdatingManifest) {
logger.error(
'❗ It looks like you ran PackWatch without a manifest. To prevent accidental passes in CI or hooks, packwatch will terminate with an error. If you are running packwatch for the first time in your project, this is expected!',
)
throw new Error('NO_MANIFEST_NO_UPDATE')
}
return
}
if (!isUpdatingManifest) {
logger.error(
'❗ It looks like you ran PackWatch without a manifest. To prevent accidental passes in CI or hooks, packwatch will terminate with an error. If you are running packwatch for the first time in your project, this is expected!',
)
throw new Error('NO_MANIFEST_NO_UPDATE')
}
return
}
const previousStats = getPreviousPackageStats(cwd)
const { packageSizeBytes, packageSize } = currentStats
const {
packageSize: previousSize,
packageSizeBytes: previousSizeBytes,
limit,
limitBytes,
} = previousStats
const hasExceededLimit = limitBytes && packageSizeBytes > limitBytes
const previousStats = getPreviousPackageStats(cwd)
const { packageSizeBytes, packageSize } = currentStats
const { packageSize: previousSize, packageSizeBytes: previousSizeBytes, limit, limitBytes } = previousStats
const hasExceededLimit = limitBytes && packageSizeBytes > limitBytes
/*
* If we are updating the manifest, we can write right away and terminate.
*/
/*
* If we are updating the manifest, we can write right away and terminate.
*/
if (isUpdatingManifest) {
createOrUpdateManifest({
previous: previousStats,
current: currentStats,
updateLimit: true,
manifestPath,
})
logger.log(
`📝 Updated the manifest! Package size: ${packageSize}, Limit: ${packageSize}`,
)
return
}
if (isUpdatingManifest) {
createOrUpdateManifest({
previous: previousStats,
current: currentStats,
updateLimit: true,
manifestPath,
})
logger.log(`📝 Updated the manifest! Package size: ${packageSize}, Limit: ${packageSize}`)
return
}
/*
* If there is a manifest file and the current package busts its limit
* we signal it and terminate with an error.
*/
/*
* If there is a manifest file and the current package busts its limit
* we signal it and terminate with an error.
*/
if (hasExceededLimit) {
logger.error(
`🔥🔥📦🔥🔥 Your package exceeds the limit set in ${MANIFEST_FILENAME}! ${packageSize} > ${limit}\nEither update the limit by using the --update-manifest flag or trim down your packed files!`,
)
throw new Error('PACKAGE_EXCEEDS_LIMIT')
}
if (hasExceededLimit) {
logger.error(
`🔥🔥📦🔥🔥 Your package exceeds the limit set in ${MANIFEST_FILENAME}! ${packageSize} > ${limit}\nEither update the limit by using the --update-manifest flag or trim down your packed files!`,
)
throw new Error('PACKAGE_EXCEEDS_LIMIT')
}
/*
* If there is a manifest file and the limit is not busted, we give
* the user some feedback on how the current package compares with
* the previous one.
*/
/*
* If there is a manifest file and the limit is not busted, we give
* the user some feedback on how the current package compares with
* the previous one.
*/
if (packageSizeBytes > previousSizeBytes) {
logger.log(
`📦 👀 Your package grew! ${packageSize} > ${previousSize} (Limit: ${limit})`,
)
} else if (packageSizeBytes < previousSizeBytes) {
logger.log(
`📦 💯 Your package shrank! ${packageSize} < ${previousSize} (Limit: ${limit})`,
)
} else {
logger.log(
`📦 Nothing to report! Your package is the same size as the latest manifest reports! (Limit: ${limit})`,
)
}
return
if (packageSizeBytes > previousSizeBytes) {
logger.log(`📦 👀 Your package grew! ${packageSize} > ${previousSize} (Limit: ${limit})`)
} else if (packageSizeBytes < previousSizeBytes) {
logger.log(`📦 💯 Your package shrank! ${packageSize} < ${previousSize} (Limit: ${limit})`)
} else {
logger.log(`📦 Nothing to report! Your package is the same size as the latest manifest reports! (Limit: ${limit})`)
}
return
}

View file

@ -4,13 +4,11 @@ import { join, resolve } from 'path'
import logger from './logger'
export function assertInPackageRoot(cwd: string): void {
const packagePath = resolve(join(cwd, 'package.json'))
const packageJsonExists = existsSync(packagePath)
const packagePath = resolve(join(cwd, 'package.json'))
const packageJsonExists = existsSync(packagePath)
if (!packageJsonExists) {
logger.log(
'🤔 There is no package.json file here. Are you in the root directory of your project?',
)
throw new Error('NOT_IN_PACKAGE_ROOT')
}
if (!packageJsonExists) {
logger.log('🤔 There is no package.json file here. Are you in the root directory of your project?')
throw new Error('NOT_IN_PACKAGE_ROOT')
}
}

View file

@ -1,11 +1,11 @@
export default {
log: (...args: unknown[]): void => {
console.log(...args)
},
warn: (...args: unknown[]): void => {
console.warn(...args)
},
error: (...args: unknown[]): void => {
console.error(...args)
},
log: (...args: unknown[]): void => {
console.log(...args)
},
warn: (...args: unknown[]): void => {
console.warn(...args)
},
error: (...args: unknown[]): void => {
console.error(...args)
},
}

View file

@ -1,13 +1,13 @@
export type PackwatchArguments = {
cwd: string
isUpdatingManifest: boolean
cwd: string
isUpdatingManifest: boolean
}
export type Report = {
packageSize: string
unpackedSize: string
packageSizeBytes: number
unpackedSizeBytes: number
limit?: string
limitBytes?: number
packageSize: string
unpackedSize: string
packageSizeBytes: number
unpackedSizeBytes: number
limit?: string
limitBytes?: number
}

View file

@ -11,90 +11,88 @@ const SIZE_MAGNITUDE_PATT = /([0-9]+\.?[0-9]*)/
const MANIFEST_FILENAME = '.packwatch.json'
export function mergeDefaultArguments(
args: Partial<PackwatchArguments>,
): PackwatchArguments {
return {
cwd: args.cwd ?? '.',
isUpdatingManifest: args.isUpdatingManifest ?? false,
}
export function mergeDefaultArguments(args: Partial<PackwatchArguments>): PackwatchArguments {
return {
cwd: args.cwd ?? '.',
isUpdatingManifest: args.isUpdatingManifest ?? false,
}
}
export function convertSizeToBytes(sizeString: string): number {
const sizeSuffix = SIZE_SUFFIX_PATT.exec(sizeString)?.[1] ?? ''
const sizeMagnitude = SIZE_MAGNITUDE_PATT.exec(sizeString)?.[1] ?? '0.0'
const sizeSuffix = SIZE_SUFFIX_PATT.exec(sizeString)?.[1] ?? ''
const sizeMagnitude = SIZE_MAGNITUDE_PATT.exec(sizeString)?.[1] ?? '0.0'
let multiplier = 1
let multiplier = 1
if (sizeSuffix === 'kB') multiplier = 1000
else if (sizeSuffix === 'mB') {
multiplier = 1000000
}
if (sizeSuffix === 'kB') multiplier = 1000
else if (sizeSuffix === 'mB') {
multiplier = 1000000
}
return multiplier * parseFloat(sizeMagnitude)
return multiplier * parseFloat(sizeMagnitude)
}
export function getCurrentPackageStats(cwd: string): Report {
const { stderr } = spawnSync('npm', ['pack', '--dry-run'], {
encoding: 'utf-8',
cwd,
})
const stderrString = String(stderr)
const packageSize = PACKAGE_SIZE_PATT.exec(stderrString)?.[1] ?? '0'
const unpackedSize = UNPACKED_SIZE_PATT.exec(stderrString)?.[1] ?? '0'
const { stderr } = spawnSync('npm', ['pack', '--dry-run'], {
encoding: 'utf-8',
cwd,
})
const stderrString = String(stderr)
const packageSize = PACKAGE_SIZE_PATT.exec(stderrString)?.[1] ?? '0'
const unpackedSize = UNPACKED_SIZE_PATT.exec(stderrString)?.[1] ?? '0'
return {
packageSize,
unpackedSize,
packageSizeBytes: convertSizeToBytes(packageSize),
unpackedSizeBytes: convertSizeToBytes(unpackedSize),
}
return {
packageSize,
unpackedSize,
packageSizeBytes: convertSizeToBytes(packageSize),
unpackedSizeBytes: convertSizeToBytes(unpackedSize),
}
}
export function getPreviousPackageStats(cwd: string): Report {
const manifestPath = resolve(join(cwd, MANIFEST_FILENAME))
try {
const currentManifest = readFileSync(manifestPath, {
encoding: 'utf-8',
})
const parsedManifest = JSON.parse(currentManifest)
return {
...parsedManifest,
packageSizeBytes: convertSizeToBytes(parsedManifest.packageSize),
unpackedSizeBytes: convertSizeToBytes(parsedManifest.unpackedSize),
limitBytes: convertSizeToBytes(parsedManifest.limit),
}
} catch {
/* No manifest */
return {
packageSize: '0',
packageSizeBytes: 0,
unpackedSizeBytes: 0,
unpackedSize: '0',
limitBytes: 0,
}
}
const manifestPath = resolve(join(cwd, MANIFEST_FILENAME))
try {
const currentManifest = readFileSync(manifestPath, {
encoding: 'utf-8',
})
const parsedManifest = JSON.parse(currentManifest)
return {
...parsedManifest,
packageSizeBytes: convertSizeToBytes(parsedManifest.packageSize),
unpackedSizeBytes: convertSizeToBytes(parsedManifest.unpackedSize),
limitBytes: convertSizeToBytes(parsedManifest.limit),
}
} catch {
/* No manifest */
return {
packageSize: '0',
packageSizeBytes: 0,
unpackedSizeBytes: 0,
unpackedSize: '0',
limitBytes: 0,
}
}
}
export function createOrUpdateManifest({
previous,
current,
manifestPath,
updateLimit = false,
previous,
current,
manifestPath,
updateLimit = false,
}: {
previous?: Report
current: Report
manifestPath: string
updateLimit?: boolean
previous?: Report
current: Report
manifestPath: string
updateLimit?: boolean
}): void {
const { limit } = previous || {}
const { packageSize, unpackedSize } = current
const { limit } = previous || {}
const { packageSize, unpackedSize } = current
const newManifest = {
limit: updateLimit ? packageSize : limit || packageSize,
packageSize: packageSize,
unpackedSize: unpackedSize,
}
const newManifest = {
limit: updateLimit ? packageSize : limit || packageSize,
packageSize: packageSize,
unpackedSize: unpackedSize,
}
writeFileSync(manifestPath, JSON.stringify(newManifest))
writeFileSync(manifestPath, JSON.stringify(newManifest))
}

View file

@ -9,255 +9,226 @@ import type { Report } from '../src/types'
let workspace: string | null
function getActualPackageSizeByNodeVersion(nodeVersion: string): string {
if (nodeVersion.startsWith('v14')) return '160'
else if (nodeVersion.startsWith('v16')) return '157'
else if (nodeVersion.startsWith('v18')) return '157'
if (nodeVersion.startsWith('v14')) return '160'
else if (nodeVersion.startsWith('v16')) return '157'
else if (nodeVersion.startsWith('v18')) return '157'
return 'unknown'
return 'unknown'
}
async function prepareWorkspace(): Promise<string> {
const workspacePath = await fs.mkdtemp(`${tmpdir()}/`)
workspace = workspacePath
return workspacePath
const workspacePath = await fs.mkdtemp(`${tmpdir()}/`)
workspace = workspacePath
return workspacePath
}
async function cleanUpWorkspace(paths: string[]): Promise<void> {
await Promise.all(
paths.map(async (path) => fs.rmdir(path, { recursive: true })),
)
await Promise.all(paths.map(async (path) => fs.rmdir(path, { recursive: true })))
}
async function createFile(path: string, content: string): Promise<void> {
await fs.writeFile(path, content)
await fs.writeFile(path, content)
}
async function createPackageJson(cwd: string): Promise<void> {
const path = resolve(join(cwd, 'package.json'))
await createFile(
path,
'{ "name": "wow", "version": "0.0.0", "files": ["!.packwatch.json"] }',
)
const path = resolve(join(cwd, 'package.json'))
await createFile(path, '{ "name": "wow", "version": "0.0.0", "files": ["!.packwatch.json"] }')
}
async function createManifest(
cwd: string,
configuration: Report,
): Promise<void> {
const path = resolve(join(cwd, '.packwatch.json'))
await createFile(path, JSON.stringify(configuration))
async function createManifest(cwd: string, configuration: Report): Promise<void> {
const path = resolve(join(cwd, '.packwatch.json'))
await createFile(path, JSON.stringify(configuration))
}
describe('Packwatch', () => {
const actualSize = getActualPackageSizeByNodeVersion(process.version)
afterEach(async () => {
jest.restoreAllMocks()
const actualSize = getActualPackageSizeByNodeVersion(process.version)
afterEach(async () => {
jest.restoreAllMocks()
if (workspace) {
await cleanUpWorkspace([workspace])
workspace = null
}
})
if (workspace) {
await cleanUpWorkspace([workspace])
workspace = null
}
})
it('warns the user and errors if run away from package.json', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
it('warns the user and errors if run away from package.json', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await expect(async () =>
packwatch({ cwd: workspacePath }),
).rejects.toThrow('NOT_IN_PACKAGE_ROOT')
await expect(async () => packwatch({ cwd: workspacePath })).rejects.toThrow('NOT_IN_PACKAGE_ROOT')
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
'There is no package.json file here. Are you in the root directory of your project?',
),
)
})
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching('There is no package.json file here. Are you in the root directory of your project?'),
)
})
describe('without manifest', () => {
it('generates the initial manifest properly', async () => {
const workspacePath = await prepareWorkspace()
await createPackageJson(workspacePath)
describe('without manifest', () => {
it('generates the initial manifest properly', async () => {
const workspacePath = await prepareWorkspace()
await createPackageJson(workspacePath)
await expect(async () =>
packwatch({ cwd: workspacePath }),
).rejects.toThrow('NO_MANIFEST_NO_UPDATE')
await expect(async () => packwatch({ cwd: workspacePath })).rejects.toThrow('NO_MANIFEST_NO_UPDATE')
const generatedManifest = await fs.readFile(
resolve(join(workspacePath, '.packwatch.json')),
{ encoding: 'utf8' },
)
const generatedManifest = await fs.readFile(resolve(join(workspacePath, '.packwatch.json')), { encoding: 'utf8' })
expect(generatedManifest).toBe(
`{"limit":"${actualSize} B","packageSize":"${actualSize} B","unpackedSize":"68 B"}`,
)
})
expect(generatedManifest).toBe(
`{"limit":"${actualSize} B","packageSize":"${actualSize} B","unpackedSize":"68 B"}`,
)
})
it('outputs expected messaging', async () => {
const workspacePath = await prepareWorkspace()
const mockWarn = jest.spyOn(console, 'warn')
const mockError = jest.spyOn(console, 'error')
await createPackageJson(workspacePath)
it('outputs expected messaging', async () => {
const workspacePath = await prepareWorkspace()
const mockWarn = jest.spyOn(console, 'warn')
const mockError = jest.spyOn(console, 'error')
await createPackageJson(workspacePath)
await expect(async () =>
packwatch({ cwd: workspacePath }),
).rejects.toThrow()
await expect(async () => packwatch({ cwd: workspacePath })).rejects.toThrow()
expect(mockWarn.mock.calls).toHaveLength(1)
expect(mockWarn.mock.calls[0][0]).toEqual(
expect.stringMatching(
/No Manifest to compare against! Current package stats written to \.packwatch\.json!\nPackage size \(\d+ B\) adopted as new limit\./,
),
)
expect(mockError.mock.calls).toHaveLength(1)
expect(mockError.mock.calls[0][0]).toEqual(
expect.stringMatching(
'It looks like you ran PackWatch without a manifest. To prevent accidental passes in CI or hooks, packwatch will terminate with an error. If you are running packwatch for the first time in your project, this is expected!',
),
)
})
expect(mockWarn.mock.calls).toHaveLength(1)
expect(mockWarn.mock.calls[0][0]).toEqual(
expect.stringMatching(
/No Manifest to compare against! Current package stats written to \.packwatch\.json!\nPackage size \(\d+ B\) adopted as new limit\./,
),
)
expect(mockError.mock.calls).toHaveLength(1)
expect(mockError.mock.calls[0][0]).toEqual(
expect.stringMatching(
'It looks like you ran PackWatch without a manifest. To prevent accidental passes in CI or hooks, packwatch will terminate with an error. If you are running packwatch for the first time in your project, this is expected!',
),
)
})
it('outputs expected messaging when not updating the manifest', async () => {
const mockWarn = jest.spyOn(console, 'warn')
const workspacePath = await prepareWorkspace()
it('outputs expected messaging when not updating the manifest', async () => {
const mockWarn = jest.spyOn(console, 'warn')
const workspacePath = await prepareWorkspace()
await createPackageJson(workspacePath)
await createPackageJson(workspacePath)
await packwatch({ cwd: workspacePath, isUpdatingManifest: true })
await packwatch({ cwd: workspacePath, isUpdatingManifest: true })
expect(mockWarn.mock.calls).toHaveLength(1)
expect(mockWarn.mock.calls[0][0]).toEqual(
expect.stringMatching(
/No Manifest to compare against! Current package stats written to \.packwatch\.json!\nPackage size \(\d+ B\) adopted as new limit\./,
),
)
})
})
expect(mockWarn.mock.calls).toHaveLength(1)
expect(mockWarn.mock.calls[0][0]).toEqual(
expect.stringMatching(
/No Manifest to compare against! Current package stats written to \.packwatch\.json!\nPackage size \(\d+ B\) adopted as new limit\./,
),
)
})
})
describe('with manifest', () => {
it('messages when the size is equal to the limit', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: `${actualSize}B`,
packageSize: `${actualSize}B`,
packageSizeBytes: Number(actualSize),
unpackedSize: '150B',
unpackedSizeBytes: 150,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Nothing to report! Your package is the same size as the latest manifest reports!/,
),
)
})
describe('with manifest', () => {
it('messages when the size is equal to the limit', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: `${actualSize}B`,
packageSize: `${actualSize}B`,
packageSizeBytes: Number(actualSize),
unpackedSize: '150B',
unpackedSizeBytes: 150,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(/Nothing to report! Your package is the same size as the latest manifest reports!/),
)
})
it('messages when the size is lower than the limit (no growth)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '170B',
packageSize: `${actualSize}B`,
packageSizeBytes: Number(actualSize),
unpackedSize: '150B',
unpackedSizeBytes: 150,
})
it('messages when the size is lower than the limit (no growth)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '170B',
packageSize: `${actualSize}B`,
packageSizeBytes: Number(actualSize),
unpackedSize: '150B',
unpackedSizeBytes: 150,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Nothing to report! Your package is the same size as the latest manifest reports! \(Limit: 170B\)/,
),
)
})
it('messages when the size is lower than the limit (growth)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '180B',
packageSize: '150B',
packageSizeBytes: 150,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Nothing to report! Your package is the same size as the latest manifest reports! \(Limit: 170B\)/,
),
)
})
it('messages when the size is lower than the limit (growth)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '180B',
packageSize: '150B',
packageSizeBytes: 150,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Your package grew! \d+ B > 150B \(Limit: 180B\)/,
),
)
})
it('messages when the size is lower than the limit (shrinkage)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '180B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(/Your package grew! \d+ B > 150B \(Limit: 180B\)/),
)
})
it('messages when the size is lower than the limit (shrinkage)', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '180B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Your package shrank! \d+ B < 170B \(Limit: 180B\)/,
),
)
})
it('messages when the size exceeds the limit', async () => {
const workspacePath = await prepareWorkspace()
const mockError = jest.spyOn(console, 'error')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '10B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(/Your package shrank! \d+ B < 170B \(Limit: 180B\)/),
)
})
it('messages when the size exceeds the limit', async () => {
const workspacePath = await prepareWorkspace()
const mockError = jest.spyOn(console, 'error')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '10B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await expect(async () =>
packwatch({ cwd: workspacePath }),
).rejects.toThrow('PACKAGE_EXCEEDS_LIMIT')
expect(mockError.mock.calls).toHaveLength(1)
expect(mockError.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Your package exceeds the limit set in \.packwatch\.json! \d+ B > 10B\nEither update the limit by using the --update-manifest flag or trim down your packed files!/,
),
)
})
await expect(async () => packwatch({ cwd: workspacePath })).rejects.toThrow('PACKAGE_EXCEEDS_LIMIT')
expect(mockError.mock.calls).toHaveLength(1)
expect(mockError.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Your package exceeds the limit set in \.packwatch\.json! \d+ B > 10B\nEither update the limit by using the --update-manifest flag or trim down your packed files!/,
),
)
})
it('messages when updating the manifest', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '10B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
it('messages when updating the manifest', async () => {
const workspacePath = await prepareWorkspace()
const mockLogger = jest.spyOn(console, 'log')
await createPackageJson(workspacePath)
await createManifest(workspacePath, {
limit: '10B',
packageSize: '170B',
packageSizeBytes: 170,
unpackedSize: '140B',
unpackedSizeBytes: 140,
})
await packwatch({ cwd: workspacePath, isUpdatingManifest: true })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(
/Updated the manifest! Package size: \d+ B, Limit: \d+ B/,
),
)
})
})
await packwatch({ cwd: workspacePath, isUpdatingManifest: true })
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(
expect.stringMatching(/Updated the manifest! Package size: \d+ B, Limit: \d+ B/),
)
})
})
})

View file

@ -1,15 +1,12 @@
import { convertSizeToBytes } from '../src/utils'
describe('utils', () => {
it.each`
initialSize | expectedSize
${'1 B'} | ${1}
${'1 kB'} | ${1000}
${'1 mB'} | ${1000000}
`(
'converts sizes properly ($initialSize -> $expectedSize)',
({ initialSize, expectedSize }) => {
expect(convertSizeToBytes(initialSize)).toEqual(expectedSize)
},
)
it.each`
initialSize | expectedSize
${'1 B'} | ${1}
${'1 kB'} | ${1000}
${'1 mB'} | ${1000000}
`('converts sizes properly ($initialSize -> $expectedSize)', ({ initialSize, expectedSize }) => {
expect(convertSizeToBytes(initialSize)).toEqual(expectedSize)
})
})

View file

@ -1,7 +0,0 @@
{
"extends": "./tsconfig.json",
"include": ["src", "tests", ".eslintrc.js"],
"exclude": [
"dist/**/*"
]
}

1941
yarn.lock

File diff suppressed because it is too large Load diff