Skip to content

Commit

Permalink
rename from standalone-analyzer --> bundle-analyzer
Browse files Browse the repository at this point in the history
  • Loading branch information
suejung-sentry committed Sep 5, 2024
1 parent c317b76 commit a2ced1d
Show file tree
Hide file tree
Showing 16 changed files with 1,133 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/bundle-analyzer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023-2024 Codecov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
79 changes: 79 additions & 0 deletions packages/bundle-analyzer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<p align="center">
<a href="https://about.codecov.io" target="_blank">
<img src="https://about.codecov.io/wp-content/themes/codecov/assets/brand/sentry-cobranding/logos/codecov-by-sentry-logo.svg" alt="Codecov by Sentry logo" width="280" height="84">
</a>
</p>

# Codecov Bundle Analyzer

> [!WARNING]
> These plugins are currently in beta and are subject to change.
>
> An importable library + CLI for Codecov bundle analysis support.
>
> The plugin does not support code coverage, see our [docs](https://docs.codecov.com/docs/quick-start) to set up coverage today!
## Installation

Using npm:

```bash
npm install @codecov/bundle-analyzer --save-dev
```

Using yarn:

```bash
yarn add @codecov/bundle-analyzer --dev
```

Using pnpm:

```bash
pnpm add @codecov/bundle-analyzer --save-dev
```

## Example

This example shows how the package can be imported as a library.

```js
// analyze.js
import { createAndUploadReport } from "@codecov/bundle-analyzer";

const buildDir = "path/to/build";

const coreOpts = {
dryRun: false,
uploadToken: "your-upload-token",
retryCount: 3,
apiUrl: "https://localhost:3000",
bundleName: "my-bundle", // bundle identifier in Codecov
enableBundleAnalysis: true,
debug: true,
};

const bundle-analyzerOpts = {
beforeReportUpload: async (original) => original,
};

createAndUploadReport(buildDir, coreOpts, bundle-analyzerOpts)
.then((reportAsJson) =>
console.log(`Report successfully generated and uploaded: ${reportAsJson}`),
)
.catch((error) =>
console.error("Failed to generate or upload report:", error),
);
```

This example shows how the package can be used as a CLI.

```
npx @codecov/bundle-analyzer ./dist --bundle-name=test-cli --upload-token=abcd --dry-run
```

## More information

- [Codecov Documentation](https://docs.codecov.com/docs)
- [Codecov Feedback](https://github.com/codecov/feedback/discussions)
- [Sentry Discord](https://discord.gg/Ww9hbqr)
52 changes: 52 additions & 0 deletions packages/bundle-analyzer/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { defineBuildConfig } from "unbuild";
import { codecovRollupPlugin } from "codecovProdRollupPlugin";
import packageJson from "./package.json";

// This file defines the Rollup configuration used by "unbuild" to bundle
// the bundle-analyzer package
export default defineBuildConfig({
// We build with 2 entrypoints - one for the library and one for the CLI
entries: ["./src/index.ts", "./src/cli.ts"],
outDir: "dist",
declaration: "compatible",
sourcemap: true,
rollup: {
dts: {
compilerOptions: {
removeComments: false,
},
},
emitCJS: true,
esbuild: {
minify: true,
},
replace: {
preventAssignment: true,
values: {
// We pull into environment variables the package version and name
// which get written to the bundle stats report
__PACKAGE_VERSION__: JSON.stringify(packageJson.version),
__PACKAGE_NAME__: JSON.stringify(packageJson.name),
},
},
},
hooks: {
"rollup:options": (_ctx, opts) => {
if (process.env.PLUGIN_CODECOV_TOKEN && Array.isArray(opts.plugins)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
opts.plugins = [
...opts.plugins,
// We analyze this bundle-analyzer package's build
// using the codecov rollup plugin
codecovRollupPlugin({
enableBundleAnalysis:
typeof process.env.PLUGIN_CODECOV_TOKEN === "string",
bundleName: packageJson.name,
uploadToken: process.env.PLUGIN_CODECOV_TOKEN,
apiUrl: process.env.PLUGIN_CODECOV_API_URL,
}),
];
}
},
},
});
75 changes: 75 additions & 0 deletions packages/bundle-analyzer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"name": "@codecov/bundle-analyzer",
"version": "0.0.1-beta.12",
"description": "Official Codecov Bundle Analyzer",
"author": "Codecov",
"license": "MIT",
"keywords": [
"Codecov",
"bundle-analyzer",
"bundler",
"analyzer"
],
"type": "module",
"bin": {
"bundle-analyzer": "./dist/cli.cjs"
},
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.cjs"
}
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"type-check": "tsc --noEmit",
"build": "unbuild",
"dev": "unbuild --stub && node --watch-path=src dist/index.mjs",
"clean": "rm -rf dist node_modules",
"lint": "eslint . --ext .ts,.tsx",
"lint:fix": "pnpm lint --fix",
"format": "prettier '**/*.{cjs,mjs,ts,tsx,md,json}' --ignore-path ../.gitignore --ignore-unknown --no-error-on-unmatched-pattern --write",
"format:check": "prettier '**/*.{cjs,mjs,ts,tsx,md,json}' --ignore-path ../.gitignore --ignore-unknown --no-error-on-unmatched-pattern --check",
"test:unit": "vitest run",
"test:unit:watch": "vitest watch",
"test:unit:ci": "vitest --coverage --reporter=junit --outputFile=./bundle-analyzer.junit.xml run",
"test:unit:update": "vitest -u run",
"generate:typedoc": "typedoc --options ./typedoc.json"
},
"dependencies": {
"@codecov/bundler-plugin-core": "workspace:^",
"yargs": "^17.7.2"
},
"devDependencies": {
"@rollup/plugin-replace": "^5.0.5",
"@types/node": "^20.11.15",
"@types/yargs": "^17.0.33",
"@vitest/coverage-v8": "^1.5.0",
"codecovProdRollupPlugin": "npm:@codecov/[email protected]",
"msw": "^2.1.5",
"ts-node": "^10.9.2",
"typedoc": "^0.25.12",
"typescript": "^5.3.3",
"unbuild": "^2.0.0",
"vite": "^5.2.10",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.5.0"
},
"volta": {
"extends": "../../package.json"
},
"engines": {
"node": ">=18.0.0"
}
}
166 changes: 166 additions & 0 deletions packages/bundle-analyzer/src/assets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import {
describe,
it,
expect,
vi,
beforeEach,
type Mock,
afterEach,
} from "vitest";
import path from "node:path";
import fs from "node:fs/promises";
import { getAssets, getAsset, listChildFilePaths } from "./assets";
import { getCompressedSize, normalizePath } from "@codecov/bundler-plugin-core";
import { fileURLToPath } from "url";

vi.mock("node:fs/promises");
vi.mock("@codecov/bundler-plugin-core", () => ({
getCompressedSize: vi.fn(),
normalizePath: vi.fn(),
}));

describe("getAssets", () => {
const mockFileContents = Buffer.from("mock file content");
const mockCompressedSize = 100;
const mockNormalizedName = "file-*.js";

beforeEach(() => {
vi.clearAllMocks();
(fs.readdir as Mock).mockResolvedValue([]);
(fs.readFile as Mock).mockResolvedValue(mockFileContents);
(getCompressedSize as Mock).mockResolvedValue(mockCompressedSize);
(normalizePath as Mock).mockReturnValue(mockNormalizedName);
});

it("should get all assets from the build directory", async () => {
const mockFiles = [
{ name: "file1.js", isDirectory: () => false, isFile: () => true },
{ name: "file2.css", isDirectory: () => false, isFile: () => true },
];

(fs.readdir as Mock).mockResolvedValueOnce(mockFiles);

const assets = await getAssets("path/to/build/directory");

expect(fs.readdir).toHaveBeenCalledTimes(1);
expect(getCompressedSize).toHaveBeenCalledTimes(mockFiles.length);
expect(normalizePath).toHaveBeenCalledTimes(mockFiles.length);
expect(assets).toEqual([
{
name: "file1.js",
size: mockFileContents.byteLength,
gzipSize: mockCompressedSize,
normalized: mockNormalizedName,
},
{
name: "file2.css",
size: mockFileContents.byteLength,
gzipSize: mockCompressedSize,
normalized: mockNormalizedName,
},
]);
});
});

describe("getAsset", () => {
const mockFilePath = "/path/to/assets/file1.js";
const mockParentPath = "/path/to/assets";
const mockFileContents = Buffer.from("mock file content");
const mockCompressedSize = 100;
const mockNormalizedName = "file-*.js";

beforeEach(() => {
vi.clearAllMocks();
(fs.readFile as Mock).mockResolvedValue(mockFileContents);
(getCompressedSize as Mock).mockResolvedValue(mockCompressedSize);
(normalizePath as Mock).mockReturnValue(mockNormalizedName);
});

it("should create an asset for a given file", async () => {
const asset = await getAsset(mockFilePath, mockParentPath);

expect(fs.readFile).toHaveBeenCalledWith(mockFilePath);
expect(getCompressedSize).toHaveBeenCalledWith({
fileName: path.relative(mockParentPath, mockFilePath),
code: mockFileContents,
});
expect(normalizePath).toHaveBeenCalledWith(
path.relative(mockParentPath, mockFilePath),
"",
);
expect(asset).toEqual({
name: path.relative(mockParentPath, mockFilePath),
size: mockFileContents.byteLength,
gzipSize: mockCompressedSize,
normalized: mockNormalizedName,
});
});
});

describe("listChildFilePaths", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("should list all files in a directory recursively", async () => {
const mockFiles = [
{ name: "file1.js", isDirectory: () => false, isFile: () => true },
{ name: "subdir", isDirectory: () => true, isFile: () => false },
];
const mockSubDirFiles = [
{ name: "file2.css", isDirectory: () => false, isFile: () => true },
];

(fs.readdir as Mock).mockResolvedValueOnce(mockFiles);
(fs.readdir as Mock).mockResolvedValueOnce(mockSubDirFiles);

const filePaths = await listChildFilePaths("/path/to/directory");

expect(fs.readdir).toHaveBeenCalledTimes(2);
expect(filePaths).toEqual([
path.join("/path/to/directory", "file1.js"),
path.join("/path/to/directory", "subdir", "file2.css"),
]);
});
});

describe("Module System Compatibility", () => {
let fileName: string;
let __dirname: string;

const setCommonJSContext = () => {
// @ts-expect-error - ignore ts error for module cleanup
global.module = { exports: {} };
fileName = __filename;
__dirname = path.dirname(fileName);
};

const setESModulesContext = () => {
// @ts-expect-error - ignore ts error for module cleanup
delete global.module;
fileName = fileURLToPath(import.meta.url);
__dirname = path.dirname(fileName);
};

afterEach(() => {
// clean up the global context after each test
// @ts-expect-error - ignore ts error for module cleanup
delete global.module;
});

it("should correctly set fileName and __dirname in CommonJS environment", () => {
setCommonJSContext();

// Assert that fileName and __dirname are correctly set for CommonJS
expect(fileName).toBe(__filename);
expect(__dirname).toBe(path.dirname(__filename));
});

it("should correctly set fileName and __dirname in ESModules environment", () => {
setESModulesContext();

// Assert that fileName and __dirname are correctly set for ESModules
expect(fileName).toBe(fileURLToPath(import.meta.url));
expect(__dirname).toBe(path.dirname(fileURLToPath(import.meta.url)));
});
});
Loading

0 comments on commit a2ced1d

Please sign in to comment.