Skip to content
Merged
7 changes: 7 additions & 0 deletions .changeset/move-package-dependencies-to-deploy-helpers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@cloudflare/deploy-helpers": minor
---

Export `collectPackageDependencies` for npm dependency metadata collection

The package dependency discovery logic (collecting installed npm package names and versions from a project's `package.json`) is now owned by `deploy-helpers` and called internally during deploy and version uploads, rather than being pre-computed in wrangler and passed through as a prop.
9 changes: 9 additions & 0 deletions .changeset/move-package-resolution-to-workers-utils.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@cloudflare/workers-utils": minor
---

Export `getInstalledPackageVersion`, `getPackagePath`, and `isPackageInstalled` utilities

Package resolution helpers that were previously internal to `@cloudflare/autoconfig` are now exported from `@cloudflare/workers-utils` so they can be shared across packages without pulling in the full autoconfig dependency.

`getPackagePath` now also consistently returns a directory path. Previously the fallback resolution strategy could return a file path (the package entry point) instead of its containing directory.
17 changes: 17 additions & 0 deletions .changeset/package-dependencies-instrumentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"wrangler": minor
---

Send npm package dependency metadata with worker uploads

Wrangler now collects npm package dependency information from the project's `package.json` at deploy and version upload time, and includes it in the upload metadata sent to the Cloudflare API. This enables dependency analytics and future features like vulnerability alerting.

The collected data includes the package name, the version constraint from `package.json`, and the exact installed version from `node_modules`. Both `dependencies` and `devDependencies` are included, while workspace packages, private packages, and unresolvable packages are excluded. The list is capped at 200 entries per upload.

To opt out, set `dependencies_instrumentation` to `false` in your Wrangler configuration file:

```json
{
"dependencies_instrumentation": false
}
```
105 changes: 4 additions & 101 deletions packages/autoconfig/src/frameworks/utils/packages.ts
Original file line number Diff line number Diff line change
@@ -1,101 +1,4 @@
import path from "node:path";
import { parsePackageJSON, readFileSync } from "@cloudflare/workers-utils";
import * as find from "empathic/find";

/**
* Checks wether a package is installed in a target project or not
*
* @param packageName the name of the target package
* @param projectPath the path of the project to check
* @returns true if the package is installed, false otherwise
*/
export function isPackageInstalled(
packageName: string,
projectPath: string
): boolean {
return !!getPackagePath(packageName, projectPath);
}

/**
* Gets the exact version of a package installed by a project (or undefined if the package is not installed)

* @param packageName the name of the target package
* @param projectPath the path of the project to check
* @param opts.stopAtProjectPath flag indicating whether the function should stop looking for the package at the project's path
* @returns the version of the package if the package is installed, undefined otherwise
*/
export function getInstalledPackageVersion(
packageName: string,
projectPath: string,
opts: {
stopAtProjectPath?: boolean;
} = {}
): string | undefined {
try {
const packagePath = getPackagePath(packageName, projectPath);
if (!packagePath) {
return undefined;
}
const packageJsonPath = find.file("package.json", {
cwd: packagePath,
last: opts.stopAtProjectPath === true ? projectPath : undefined,
});
if (!packageJsonPath) {
return undefined;
}
const packageJson = parsePackageJSON(
readFileSync(packageJsonPath),
packageJsonPath
);
// The requested package may be installed under an alias (e.g. vite+
// installs `@voidzero-dev/vite-plus-core` under the `vite` alias). In that
// case the resolved package.json belongs to the aliased package, so its
// `version` is not the version of the requested package.
//
// `bundledVersions` is NOT a standard package.json field (it is not the
// standard `bundledDependencies`) — it is a vite+ convention that maps the
// names of the tools it bundles to the versions it provides. When the
// resolved package name doesn't match the requested one, prefer the version
// declared there for the requested package.
if (packageJson.name !== packageName) {
const bundledVersion = packageJson.bundledVersions?.[packageName];
if (bundledVersion !== undefined) {
return bundledVersion;
}
}
return packageJson.version;
} catch {}
}

/**
* Gets the path for a package installed by a project (or undefined if the package is not installed)
*
* @param packageName the name of the target package
* @param projectPath the path of the project
* @returns the path for the package if the package is installed, undefined otherwise
*/
function getPackagePath(
packageName: string,
projectPath: string
): string | undefined {
try {
// Note: we first try to `require.resolve` using the package.json this will succeed
// if the package.json is exported by the package
return path.dirname(
require.resolve(`${packageName}/package.json`, {
paths: [projectPath],
})
);
} catch {}

try {
// Note: if `require.resolve` using the package.json failed (the package.json is not
// exported by the package) then let's try to `require.resolve` on the package
// name directly
return require.resolve(packageName, {
paths: [projectPath],
});
} catch {}

return undefined;
}
export {
isPackageInstalled,
getInstalledPackageVersion,
} from "@cloudflare/workers-utils";
2 changes: 1 addition & 1 deletion packages/autoconfig/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ export {
AutoConfigFrameworkConfigurationError,
} from "./errors";

export { getInstalledPackageVersion } from "./frameworks/utils/packages";
export { getInstalledPackageVersion } from "@cloudflare/workers-utils";
5 changes: 5 additions & 0 deletions packages/deploy-helpers/src/deploy/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
renderExportsReconciliationSuccess,
} from "./helpers/exports-reconciliation";
import { helpIfErrorIsSizeOrScriptStartup } from "./helpers/friendly-validator-errors";
import { collectPackageDependencies } from "./helpers/package-dependencies";
import { parseBulkInputToObject } from "./helpers/parse-bulk-input";
import { parseConfigPlacement } from "./helpers/placement";
import { printBindings } from "./helpers/print-bindings";
Expand Down Expand Up @@ -344,6 +345,10 @@ export default async function deploy(
: undefined,
observability: config.observability,
cache: config.cache,
package_dependencies:
config.dependencies_instrumentation !== false && projectRoot
? await collectPackageDependencies(projectRoot)
: undefined,
Comment thread
dario-piotrowicz marked this conversation as resolved.
};

const sourceMapSize = worker.sourceMaps?.reduce(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export function createWorkerUploadForm(
assets,
observability,
cache,
package_dependencies,
} = worker;

const assetConfig: AssetConfigMetadata = {
Expand Down Expand Up @@ -849,6 +850,7 @@ export function createWorkerUploadForm(
}),
...(observability && { observability }),
...(cache && { cache_options: cache }),
...(package_dependencies?.length && { package_dependencies }),
};

if (options?.unsafe?.metadata !== undefined) {
Expand Down
155 changes: 155 additions & 0 deletions packages/deploy-helpers/src/deploy/helpers/package-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { access, readFile } from "node:fs/promises";
import path from "node:path";
import {
getInstalledPackageVersion,
getPackagePath,
parsePackageJSON,
} from "@cloudflare/workers-utils";
import { logger } from "../../shared/context";

/**
* A single npm package dependency entry, matching the upload API schema
* see: https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update.
*/
export type PackageDependency = {
/** The npm package name, e.g. "lodash" or "@cloudflare/workers-types". */
name: string;
/** The version constraint as written in package.json, e.g. "^4.17.21". */
packageJsonVersion: string;
/** The exact version resolved and installed by the package manager, e.g. "4.17.22". */
installedVersion: string;
};

/**
* Maximum number of dependency entries to include in a single upload.
* This also gets truncated to this limit server-side, but we cap client-side
* to avoid sending unnecessarily large payloads.
*/
const MAX_PACKAGE_DEPENDENCIES = 200;

/**
* Collects npm package dependency metadata from the project's package.json.
*
* Reads both `dependencies` and `devDependencies`, resolves each package's
* installed version from node_modules, and filters out:
* - Workspace packages (version prefixed with `workspace:`)
* - Pnpm catalog packages (version prefixed with `catalog:`)
* - Private packages (`"private": true` in the package's own package.json)
* - Packages whose installed version cannot be resolved
*
* The result is capped at {@link MAX_PACKAGE_DEPENDENCIES} entries.
*
* @param projectPath - Path to the project directory (where package.json is located)
* @returns An array of package dependency entries, or `undefined` if package.json
* cannot be read or no valid dependencies are found
*/
export async function collectPackageDependencies(
projectPath: string
): Promise<PackageDependency[] | undefined> {
const packageJsonPath = path.join(projectPath, "package.json");

try {
await access(packageJsonPath);
} catch {
return undefined;
}

try {
const content = await readFile(packageJsonPath, "utf-8");
const packageJson = parsePackageJSON(content, packageJsonPath);

const allDependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
} as Record<string, string>;

const result: PackageDependency[] = [];

for (const [dependencyName, packageJsonVersion] of Object.entries(
allDependencies
)) {
if (result.length >= MAX_PACKAGE_DEPENDENCIES) {
break;
}

if (
packageJsonVersion.startsWith("workspace:") ||
packageJsonVersion.startsWith("catalog:")
) {
continue;
Comment thread
dario-piotrowicz marked this conversation as resolved.
}

const installedVersion = getInstalledPackageVersion(
dependencyName,
projectPath
);

Comment thread
dario-piotrowicz marked this conversation as resolved.
if (!installedVersion) {
continue;
}

if (await isPackagePrivate(dependencyName, projectPath)) {
continue;
}

result.push({
name: dependencyName,
packageJsonVersion,
installedVersion,
});
}

return result.length > 0 ? result : undefined;
} catch (error) {
logger.debug(
`Failed to collect package dependencies: ${error instanceof Error ? error.message : error}`
);
return undefined;
}
}

/**
* Checks whether a package is marked as private in its own package.json.
*
* Resolves the package from the project's node_modules and reads its
* package.json to check the `private` field.
*
* @param packageName - Name of the npm package to check
* @param projectPath - Path to the project directory
* @returns `true` if the package has `"private": true`, `false` otherwise
*/
async function isPackagePrivate(
packageName: string,
projectPath: string
): Promise<boolean> {
try {
const packagePath = getPackagePath(packageName, projectPath);
if (!packagePath) {
return false;
}

// Walk up from the resolved path to find the package's package.json
let currentDir = packagePath;
const root = path.parse(currentDir).root;

while (currentDir !== root) {
const potentialPackageJson = path.join(currentDir, "package.json");
try {
await access(potentialPackageJson);
const content = await readFile(potentialPackageJson, "utf-8");
const packageJson = parsePackageJSON(content, potentialPackageJson);

if (packageJson.name === packageName) {
return packageJson.private === true;
}
} catch {
// package.json doesn't exist at this level, keep walking up
}
currentDir = path.dirname(currentDir);
}

return false;
} catch {
return false;
}
}
5 changes: 5 additions & 0 deletions packages/deploy-helpers/src/deploy/versions-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
import { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE } from "./helpers/error-codes";
import { resolveExportsUploadPayload } from "./helpers/exports";
import { helpIfErrorIsSizeOrScriptStartup } from "./helpers/friendly-validator-errors";
import { collectPackageDependencies } from "./helpers/package-dependencies";
import { parseBulkInputToObject } from "./helpers/parse-bulk-input";
import { parseConfigPlacement } from "./helpers/placement";
import { printBindings } from "./helpers/print-bindings";
Expand Down Expand Up @@ -192,6 +193,10 @@ export default async function versionsUpload(
logpush: undefined, // logpush and observability are non-versioned settings
observability: undefined,
cache: config.cache, // cache is a versioned setting
package_dependencies:
config.dependencies_instrumentation !== false && projectRoot
? await collectPackageDependencies(projectRoot)
: undefined,
};

await printBundleSize(
Expand Down
1 change: 1 addition & 0 deletions packages/deploy-helpers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ export * from "./deploy/helpers/print-bindings";
export * from "./deploy/helpers/assets";
export * from "./deploy/helpers/hash";
export * from "./deploy/helpers/jwt";
export * from "./deploy/helpers/package-dependencies";
export * from "./deploy/helpers/provision-bindings";
Loading
Loading