From 94bcfcd1c74eb7de3705d97edab3d87db697db56 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 2 Dec 2024 22:05:06 +0000 Subject: [PATCH] refactor: move projectRoot computation to config validation --- fixtures/import-npm/package-lock.json | 2 +- .../LocalRuntimeController.test.ts | 3 -- .../src/__tests__/configuration.test.ts | 1 + .../__tests__/find-additional-modules.test.ts | 14 +++++----- .../wrangler/src/__tests__/get-entry.test.ts | 28 +++++++++---------- .../__tests__/navigator-user-agent.test.ts | 2 -- .../src/__tests__/pages/deploy.test.ts | 2 +- .../api/startDevWorker/BundlerController.ts | 4 +-- .../api/startDevWorker/ConfigController.ts | 2 +- packages/wrangler/src/config/config.ts | 17 +++++++++-- .../wrangler/src/config/validation-pages.ts | 5 ++-- packages/wrangler/src/config/validation.ts | 3 ++ packages/wrangler/src/d1/execute.ts | 4 +-- .../wrangler/src/d1/migrations/helpers.ts | 8 +++--- packages/wrangler/src/deploy/deploy.ts | 13 +++++++-- packages/wrangler/src/deploy/index.ts | 5 ++-- .../wrangler/src/deployment-bundle/bundle.ts | 10 +++---- .../wrangler/src/deployment-bundle/entry.ts | 7 ++--- .../find-additional-modules.ts | 3 +- .../deployment-bundle/module-collection.ts | 7 ++++- .../src/deployment-bundle/resolve-entry.ts | 12 +++----- packages/wrangler/src/dev/use-esbuild.ts | 7 +++-- .../src/pages/functions/buildPlugin.ts | 2 +- .../src/pages/functions/buildWorker.ts | 17 ++++++----- packages/wrangler/src/versions/index.ts | 5 +--- packages/wrangler/src/versions/upload.ts | 16 +++++++---- 26 files changed, 111 insertions(+), 88 deletions(-) diff --git a/fixtures/import-npm/package-lock.json b/fixtures/import-npm/package-lock.json index 7f3936d259bd..4a7536533dc4 100644 --- a/fixtures/import-npm/package-lock.json +++ b/fixtures/import-npm/package-lock.json @@ -15,7 +15,7 @@ "dev": true }, "../../packages/wrangler": { - "version": "3.90.0", + "version": "3.91.0", "dev": true, "license": "MIT OR Apache-2.0", "dependencies": { diff --git a/packages/wrangler/src/__tests__/api/startDevWorker/LocalRuntimeController.test.ts b/packages/wrangler/src/__tests__/api/startDevWorker/LocalRuntimeController.test.ts index d9735954a1e7..7b85f793f933 100644 --- a/packages/wrangler/src/__tests__/api/startDevWorker/LocalRuntimeController.test.ts +++ b/packages/wrangler/src/__tests__/api/startDevWorker/LocalRuntimeController.test.ts @@ -88,7 +88,6 @@ function makeEsbuildBundle(testBundle: TestBundle): Bundle { entrypointSource: "", entry: { file: "index.mjs", - projectRoot: "/virtual/", format: "modules", moduleRoot: "/virtual", name: undefined, @@ -233,7 +232,6 @@ describe("LocalRuntimeController", () => { `, entry: { file: "esm/index.mjs", - projectRoot: "/virtual/", format: "modules", moduleRoot: "/virtual", name: undefined, @@ -347,7 +345,6 @@ describe("LocalRuntimeController", () => { path: "/virtual/index.js", entry: { file: "index.js", - projectRoot: "/virtual/", format: "service-worker", moduleRoot: "/virtual", name: undefined, diff --git a/packages/wrangler/src/__tests__/configuration.test.ts b/packages/wrangler/src/__tests__/configuration.test.ts index 0c0c59c60df1..a6991ba6513e 100644 --- a/packages/wrangler/src/__tests__/configuration.test.ts +++ b/packages/wrangler/src/__tests__/configuration.test.ts @@ -63,6 +63,7 @@ describe("normalizeAndValidateConfig()", () => { compatibility_date: undefined, compatibility_flags: [], configPath: undefined, + projectRoot: process.cwd(), d1_databases: [], vectorize: [], hyperdrive: [], diff --git a/packages/wrangler/src/__tests__/find-additional-modules.test.ts b/packages/wrangler/src/__tests__/find-additional-modules.test.ts index dc9df03f2670..a3b436afc15a 100644 --- a/packages/wrangler/src/__tests__/find-additional-modules.test.ts +++ b/packages/wrangler/src/__tests__/find-additional-modules.test.ts @@ -37,9 +37,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + process.cwd(), { file: path.join(process.cwd(), "./index.js"), - projectRoot: process.cwd(), format: "modules", moduleRoot: process.cwd(), exports: [], @@ -73,9 +73,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + process.cwd(), { file: path.join(process.cwd(), "./index.js"), - projectRoot: process.cwd(), format: "modules", moduleRoot: process.cwd(), exports: [], @@ -107,9 +107,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + path.join(process.cwd(), "./src/nested"), { file: path.join(process.cwd(), "./src/nested/index.js"), - projectRoot: path.join(process.cwd(), "./src/nested"), format: "modules", // The default module root is dirname(file) moduleRoot: path.join(process.cwd(), "./src/nested"), @@ -142,9 +142,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + path.join(process.cwd(), "./src/nested"), { file: path.join(process.cwd(), "./src/nested/index.js"), - projectRoot: path.join(process.cwd(), "./src/nested"), format: "modules", // The default module root is dirname(file) moduleRoot: path.join(process.cwd(), "./src"), @@ -177,9 +177,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + path.join(process.cwd(), "./src/nested"), { file: path.join(process.cwd(), "./src/nested/index.js"), - projectRoot: path.join(process.cwd(), "./src/nested"), format: "modules", // The default module root is dirname(file) moduleRoot: path.join(process.cwd(), "./src"), @@ -212,9 +212,9 @@ describe("traverse module graph", () => { ); const modules = await findAdditionalModules( + path.join(process.cwd(), "./src"), { file: path.join(process.cwd(), "./src/index.js"), - projectRoot: path.join(process.cwd(), "./src"), format: "modules", // The default module root is dirname(file) moduleRoot: path.join(process.cwd(), "./src"), @@ -247,9 +247,9 @@ describe("traverse module graph", () => { await expect( findAdditionalModules( + path.join(process.cwd(), "./src"), { file: path.join(process.cwd(), "./src/index.js"), - projectRoot: path.join(process.cwd(), "./src"), format: "modules", // The default module root is dirname(file) moduleRoot: path.join(process.cwd(), "./src"), diff --git a/packages/wrangler/src/__tests__/get-entry.test.ts b/packages/wrangler/src/__tests__/get-entry.test.ts index aa938d5054dc..d2f67af500d4 100644 --- a/packages/wrangler/src/__tests__/get-entry.test.ts +++ b/packages/wrangler/src/__tests__/get-entry.test.ts @@ -5,8 +5,16 @@ import { getEntry } from "../deployment-bundle/entry"; import { mockConsoleMethods } from "./helpers/mock-console"; import { runInTempDir } from "./helpers/run-in-tmp"; import { seed } from "./helpers/seed"; +import type { Config } from "../config/config"; import type { Entry } from "../deployment-bundle/entry"; +function getConfig(): Config { + return { + ...defaultWranglerConfig, + projectRoot: process.cwd(), + }; +} + function normalize(entry: Entry): Entry { const tmpDir = process.cwd(); const tmpDirName = path.basename(tmpDir); @@ -37,13 +45,8 @@ describe("getEntry()", () => { } `, }); - const entry = await getEntry( - { script: "index.ts" }, - defaultWranglerConfig, - "deploy" - ); + const entry = await getEntry({ script: "index.ts" }, getConfig(), "deploy"); expect(normalize(entry)).toMatchObject({ - projectRoot: "/tmp/dir", file: "/tmp/dir/index.ts", moduleRoot: "/tmp/dir", }); @@ -61,11 +64,10 @@ describe("getEntry()", () => { }); const entry = await getEntry( { script: "src/index.ts" }, - defaultWranglerConfig, + getConfig(), "deploy" ); expect(normalize(entry)).toMatchObject({ - projectRoot: "/tmp/dir", file: "/tmp/dir/src/index.ts", moduleRoot: "/tmp/dir/src", }); @@ -83,11 +85,10 @@ describe("getEntry()", () => { }); const entry = await getEntry( {}, - { ...defaultWranglerConfig, main: "index.ts" }, + { ...getConfig(), main: "index.ts" }, "deploy" ); expect(normalize(entry)).toMatchObject({ - projectRoot: "/tmp/dir", file: "/tmp/dir/index.ts", moduleRoot: "/tmp/dir", }); @@ -105,11 +106,10 @@ describe("getEntry()", () => { }); const entry = await getEntry( {}, - { ...defaultWranglerConfig, main: "src/index.ts" }, + { ...getConfig(), main: "src/index.ts" }, "deploy" ); expect(normalize(entry)).toMatchObject({ - projectRoot: "/tmp/dir", file: "/tmp/dir/src/index.ts", moduleRoot: "/tmp/dir/src", }); @@ -128,14 +128,14 @@ describe("getEntry()", () => { const entry = await getEntry( {}, { - ...defaultWranglerConfig, + ...getConfig(), main: "src/index.ts", configPath: "other-worker/wrangler.toml", + projectRoot: "other-worker", }, "deploy" ); expect(normalize(entry)).toMatchObject({ - projectRoot: "/tmp/dir/other-worker", file: "/tmp/dir/other-worker/src/index.ts", moduleRoot: "/tmp/dir/other-worker/src", }); diff --git a/packages/wrangler/src/__tests__/navigator-user-agent.test.ts b/packages/wrangler/src/__tests__/navigator-user-agent.test.ts index 6b66a311a9ab..43d470ffef8a 100644 --- a/packages/wrangler/src/__tests__/navigator-user-agent.test.ts +++ b/packages/wrangler/src/__tests__/navigator-user-agent.test.ts @@ -104,7 +104,6 @@ describe("defineNavigatorUserAgent is respected", () => { await bundleWorker( { file: path.resolve("src/index.js"), - projectRoot: process.cwd(), format: "modules", moduleRoot: path.dirname(path.resolve("src/index.js")), exports: [], @@ -167,7 +166,6 @@ describe("defineNavigatorUserAgent is respected", () => { await bundleWorker( { file: path.resolve("src/index.js"), - projectRoot: process.cwd(), format: "modules", moduleRoot: path.dirname(path.resolve("src/index.js")), exports: [], diff --git a/packages/wrangler/src/__tests__/pages/deploy.test.ts b/packages/wrangler/src/__tests__/pages/deploy.test.ts index 806f69219560..e60b27d57c65 100644 --- a/packages/wrangler/src/__tests__/pages/deploy.test.ts +++ b/packages/wrangler/src/__tests__/pages/deploy.test.ts @@ -2855,7 +2855,7 @@ Failed to publish your Function. Got error: Uncaught TypeError: a is not a funct }); }); - describe("in Advanced Mode [_worker,js]", () => { + describe("in Advanced Mode [_worker.js]", () => { it("should upload an Advanced Mode project", async () => { // set up the directory of static files to upload. mkdirSync("public"); diff --git a/packages/wrangler/src/api/startDevWorker/BundlerController.ts b/packages/wrangler/src/api/startDevWorker/BundlerController.ts index 115690965f23..830630495ad1 100644 --- a/packages/wrangler/src/api/startDevWorker/BundlerController.ts +++ b/packages/wrangler/src/api/startDevWorker/BundlerController.ts @@ -79,7 +79,6 @@ export class BundlerController extends Controller { const entry: Entry = { file: config.entrypoint, - projectRoot: config.projectRoot, format: config.build.format, moduleRoot: config.build.moduleRoot, exports: config.build.exports, @@ -87,6 +86,7 @@ export class BundlerController extends Controller { const entryDirectory = path.dirname(config.entrypoint); const moduleCollector = createModuleCollector({ + projectRoot: config.projectRoot, wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences( entryDirectory, config.entrypoint @@ -103,6 +103,7 @@ export class BundlerController extends Controller { ).bindings; const bundleResult: Omit = !config.build?.bundle ? await noBundleWorker( + config.projectRoot, entry, config.build.moduleRules, this.#tmpDir.path @@ -234,7 +235,6 @@ export class BundlerController extends Controller { assert(this.#tmpDir); const entry: Entry = { file: config.entrypoint, - projectRoot: config.projectRoot, format: config.build.format, moduleRoot: config.build.moduleRoot, exports: config.build.exports, diff --git a/packages/wrangler/src/api/startDevWorker/ConfigController.ts b/packages/wrangler/src/api/startDevWorker/ConfigController.ts index 0b66b8c60ee5..5b27ae348d9a 100644 --- a/packages/wrangler/src/api/startDevWorker/ConfigController.ts +++ b/packages/wrangler/src/api/startDevWorker/ConfigController.ts @@ -263,7 +263,7 @@ async function resolveConfig( compatibilityDate: getDevCompatibilityDate(config, input.compatibilityDate), compatibilityFlags: input.compatibilityFlags ?? config.compatibility_flags, entrypoint: entry.file, - projectRoot: entry.projectRoot, + projectRoot: config.projectRoot, bindings, migrations: input.migrations ?? config.migrations, sendMetrics: input.sendMetrics ?? config.send_metrics, diff --git a/packages/wrangler/src/config/config.ts b/packages/wrangler/src/config/config.ts index a0f7284b3aff..5efd39b48c99 100644 --- a/packages/wrangler/src/config/config.ts +++ b/packages/wrangler/src/config/config.ts @@ -22,7 +22,10 @@ import type { CamelCaseKey } from "yargs"; * - `@breaking`: the deprecation/optionality is a breaking change from Wrangler v1. * - `@todo`: there's more work to be done (with details attached). */ -export type Config = ConfigFields & PagesConfigFields & Environment; +export type Config = ComputedConfigFields & + ConfigFields & + PagesConfigFields & + Environment; export type RawConfig = Partial> & PagesConfigFields & @@ -30,9 +33,14 @@ export type RawConfig = Partial> & DeprecatedConfigFields & EnvironmentMap & { $schema?: string }; -export interface ConfigFields { +export interface ComputedConfigFields { + /** Path to the configuration file (e.g. wrangler.toml/json), if one was provided. */ configPath: string | undefined; + /** A worker's directory. Usually where the Wrangler configuration file is located */ + projectRoot: string; +} +export interface ConfigFields { /** * A boolean to enable "legacy" style wrangler environments (from Wrangler v1). * These have been superseded by Services, but there may be projects that won't @@ -325,8 +333,11 @@ export const defaultWranglerConfig: Config = { /*====================================================*/ /* Fields supported by Workers only */ /*====================================================*/ - /* TOP-LEVEL ONLY FIELDS */ + /* COMPUTED CONFIG FIELDS */ configPath: undefined, + projectRoot: process.cwd(), + + /* TOP-LEVEL ONLY FIELDS */ legacy_env: true, site: undefined, legacy_assets: undefined, diff --git a/packages/wrangler/src/config/validation-pages.ts b/packages/wrangler/src/config/validation-pages.ts index a948b7189695..27c501843cfc 100644 --- a/packages/wrangler/src/config/validation-pages.ts +++ b/packages/wrangler/src/config/validation-pages.ts @@ -36,9 +36,10 @@ const supportedPagesConfigFields = [ "dev", "mtls_certificates", "browser", - // normalizeAndValidateConfig() sets this value - "configPath", "upload_source_maps", + // normalizeAndValidateConfig() sets the following values + "configPath", + "projectRoot", ] as const; export function validatePagesConfig( diff --git a/packages/wrangler/src/config/validation.ts b/packages/wrangler/src/config/validation.ts index 948af1d5b36e..e7a5329208f9 100644 --- a/packages/wrangler/src/config/validation.ts +++ b/packages/wrangler/src/config/validation.ts @@ -260,6 +260,9 @@ export function normalizeAndValidateConfig( // Process the top-level default environment configuration. const config: Config = { configPath, + projectRoot: path.resolve( + configPath !== undefined ? path.dirname(configPath) : process.cwd() + ), pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir( configPath, rawConfig.pages_build_output_dir diff --git a/packages/wrangler/src/d1/execute.ts b/packages/wrangler/src/d1/execute.ts index bea1bd4fe49d..aca0aac306f4 100644 --- a/packages/wrangler/src/d1/execute.ts +++ b/packages/wrangler/src/d1/execute.ts @@ -19,7 +19,7 @@ import { requireAuth } from "../user"; import * as options from "./options"; import splitSqlQuery from "./splitter"; import { getDatabaseByNameOrBinding, getDatabaseInfoFromConfig } from "./utils"; -import type { Config, ConfigFields, DevConfig, Environment } from "../config"; +import type { Config } from "../config"; import type { CommonYargsArgv, StrictYargsOptionsToInterface, @@ -197,7 +197,7 @@ export async function executeSql({ }: { local: boolean | undefined; remote: boolean | undefined; - config: ConfigFields & Environment; + config: Config; name: string; shouldPrompt: boolean | undefined; persistTo: string | undefined; diff --git a/packages/wrangler/src/d1/migrations/helpers.ts b/packages/wrangler/src/d1/migrations/helpers.ts index 8b4399fec691..bfaca5f78355 100644 --- a/packages/wrangler/src/d1/migrations/helpers.ts +++ b/packages/wrangler/src/d1/migrations/helpers.ts @@ -7,7 +7,7 @@ import { isNonInteractiveOrCI } from "../../is-interactive"; import { logger } from "../../logger"; import { DEFAULT_MIGRATION_PATH } from "../constants"; import { executeSql } from "../execute"; -import type { ConfigFields, DevConfig, Environment } from "../../config"; +import type { Config } from "../../config"; import type { QueryResult } from "../execute"; import type { Migration } from "../types"; @@ -57,7 +57,7 @@ export async function getUnappliedMigrations({ migrationsPath: string; local: boolean | undefined; remote: boolean | undefined; - config: ConfigFields & Environment; + config: Config; name: string; persistTo: string | undefined; preview: boolean | undefined; @@ -92,7 +92,7 @@ type ListAppliedMigrationsProps = { migrationsTableName: string; local: boolean | undefined; remote: boolean | undefined; - config: ConfigFields & Environment; + config: Config; name: string; persistTo: string | undefined; preview: boolean | undefined; @@ -170,7 +170,7 @@ export const initMigrationsTable = async ({ migrationsTableName: string; local: boolean | undefined; remote: boolean | undefined; - config: ConfigFields & Environment; + config: Config; name: string; persistTo: string | undefined; preview: boolean | undefined; diff --git a/packages/wrangler/src/deploy/deploy.ts b/packages/wrangler/src/deploy/deploy.ts index b618327e5c87..43f4d28b6f34 100644 --- a/packages/wrangler/src/deploy/deploy.ts +++ b/packages/wrangler/src/deploy/deploy.ts @@ -103,7 +103,7 @@ type Props = { logpush: boolean | undefined; uploadSourceMaps: boolean | undefined; oldAssetTtl: number | undefined; - projectRoot: string | undefined; + projectRoot: string; dispatchNamespace: string | undefined; experimentalVersions: boolean | undefined; }; @@ -548,6 +548,7 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m const entryDirectory = path.dirname(props.entry.file); const moduleCollector = createModuleCollector({ + projectRoot: config.projectRoot, wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences( entryDirectory, props.entry.file @@ -569,7 +570,12 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m bundleType, ...bundle } = props.noBundle - ? await noBundleWorker(props.entry, props.rules, props.outDir) + ? await noBundleWorker( + props.projectRoot, + props.entry, + props.rules, + props.outDir + ) : await bundleWorker( props.entry, typeof destination === "string" ? destination : destination.path, @@ -1308,11 +1314,12 @@ export async function updateQueueConsumers( } export async function noBundleWorker( + projectRoot: string, entry: Entry, rules: Rule[], outDir: string | undefined ) { - const modules = await findAdditionalModules(entry, rules); + const modules = await findAdditionalModules(projectRoot, entry, rules); if (outDir) { await writeAdditionalModules(modules, outDir); } diff --git a/packages/wrangler/src/deploy/index.ts b/packages/wrangler/src/deploy/index.ts index 05b1eebb6748..4bc0c45d0c70 100644 --- a/packages/wrangler/src/deploy/index.ts +++ b/packages/wrangler/src/deploy/index.ts @@ -265,7 +265,6 @@ async function deployWorker(args: DeployArgs) { const configPath = args.config || (args.script && findWranglerConfig(path.dirname(args.script))); - const projectRoot = configPath && path.dirname(configPath); const config = readConfig(configPath, args); if (config.pages_build_output_dir) { throw new UserError( @@ -342,7 +341,7 @@ async function deployWorker(args: DeployArgs) { await verifyWorkerMatchesCITag( accountId, name, - path.relative(entry.projectRoot, config.configPath ?? "wrangler.toml") + path.relative(config.projectRoot, config.configPath ?? "wrangler.toml") ); } const { sourceMapSize, versionId, workerTag, targets } = await deploy({ @@ -377,7 +376,7 @@ async function deployWorker(args: DeployArgs) { logpush: args.logpush, uploadSourceMaps: args.uploadSourceMaps, oldAssetTtl: args.oldAssetTtl, - projectRoot, + projectRoot: config.projectRoot, dispatchNamespace: args.dispatchNamespace, experimentalVersions: args.experimentalVersions, }); diff --git a/packages/wrangler/src/deployment-bundle/bundle.ts b/packages/wrangler/src/deployment-bundle/bundle.ts index c5f920d03d0a..dd6bce6e555a 100644 --- a/packages/wrangler/src/deployment-bundle/bundle.ts +++ b/packages/wrangler/src/deployment-bundle/bundle.ts @@ -134,7 +134,7 @@ export type BundleOptions = { plugins: esbuild.Plugin[] | undefined; isOutfile: boolean | undefined; local: boolean; - projectRoot: string | undefined; + projectRoot: string; defineNavigatorUserAgent: boolean; external: string[] | undefined; }; @@ -382,7 +382,7 @@ export async function bundleWorker( path: require.resolve(aliasPath, { // From the esbuild alias docs: "Note that when an import path is substituted using an alias, the resulting import path is resolved in the working directory instead of in the directory containing the source file with the import path." // https://esbuild.github.io/api/#alias:~:text=Note%20that%20when%20an%20import%20path%20is%20substituted%20using%20an%20alias%2C%20the%20resulting%20import%20path%20is%20resolved%20in%20the%20working%20directory%20instead%20of%20in%20the%20directory%20containing%20the%20source%20file%20with%20the%20import%20path. - paths: [entry.projectRoot], + paths: [projectRoot], }), }; } @@ -394,7 +394,7 @@ export async function bundleWorker( // Don't use entryFile here as the file may have been changed when applying the middleware entryPoints: [entry.file], bundle, - absWorkingDir: entry.projectRoot, + absWorkingDir: projectRoot, outdir: destination, keepNames: true, entryNames: entryName || path.parse(entryFile).name, @@ -522,7 +522,7 @@ export async function bundleWorker( )[0]; const resolvedEntryPointPath = path.resolve( - entry.projectRoot, + projectRoot, entryPoint.relativePath ); @@ -544,7 +544,7 @@ export async function bundleWorker( sourceMapPath, sourceMapMetadata: { tmpDir: tmpDir.path, - entryDirectory: entry.projectRoot, + entryDirectory: projectRoot, }, }; } diff --git a/packages/wrangler/src/deployment-bundle/entry.ts b/packages/wrangler/src/deployment-bundle/entry.ts index 23ff0dce5661..4a11e2bf7fdf 100644 --- a/packages/wrangler/src/deployment-bundle/entry.ts +++ b/packages/wrangler/src/deployment-bundle/entry.ts @@ -22,8 +22,6 @@ import type { CfScriptFormat } from "./worker"; export type Entry = { /** A worker's entrypoint */ file: string; - /** A worker's directory. Usually where the Wrangler configuration file is located */ - projectRoot: string; /** Is this a module worker or a service worker? */ format: CfScriptFormat; /** The directory that contains all of a `--no-bundle` worker's modules. Usually `${directory}/src`. Defaults to path.dirname(file) */ @@ -60,9 +58,9 @@ export async function getEntry( if (args.script) { paths = resolveEntryWithScript(args.script); } else if (config.main !== undefined) { - paths = resolveEntryWithMain(config.main, config.configPath); + paths = resolveEntryWithMain(config.main, config.projectRoot); } else if (entryPoint) { - paths = resolveEntryWithEntryPoint(entryPoint, config.configPath); + paths = resolveEntryWithEntryPoint(entryPoint, config.projectRoot); } else if ( args.legacyAssets || config.legacy_assets || @@ -124,7 +122,6 @@ export async function getEntry( return { file: paths.absolutePath, - projectRoot, format, moduleRoot: args.moduleRoot ?? config.base_dir ?? path.dirname(paths.absolutePath), diff --git a/packages/wrangler/src/deployment-bundle/find-additional-modules.ts b/packages/wrangler/src/deployment-bundle/find-additional-modules.ts index 55ee98d2ba2c..eb8cd66a242d 100644 --- a/packages/wrangler/src/deployment-bundle/find-additional-modules.ts +++ b/packages/wrangler/src/deployment-bundle/find-additional-modules.ts @@ -45,6 +45,7 @@ function isValidPythonPackageName(name: string): boolean { * that match the given `rules`. */ export async function findAdditionalModules( + projectRoot: string, entry: Entry, rules: Rule[] | ParsedRules, attachSourcemaps = false @@ -72,7 +73,7 @@ export async function findAdditionalModules( let pythonRequirements = ""; try { pythonRequirements = await readFile( - path.resolve(entry.projectRoot, "requirements.txt"), + path.resolve(projectRoot, "requirements.txt"), "utf-8" ); } catch (e) { diff --git a/packages/wrangler/src/deployment-bundle/module-collection.ts b/packages/wrangler/src/deployment-bundle/module-collection.ts index 8087d0ac8a62..1fd051b4cfbf 100644 --- a/packages/wrangler/src/deployment-bundle/module-collection.ts +++ b/packages/wrangler/src/deployment-bundle/module-collection.ts @@ -70,6 +70,7 @@ export const noopModuleCollector: ModuleCollector = { }; export function createModuleCollector(props: { + projectRoot: string; entry: Entry; findAdditionalModules: boolean; rules?: Config["rules"]; @@ -106,7 +107,11 @@ export function createModuleCollector(props: { return { errors: [{ text: error }] }; } - const found = await findAdditionalModules(props.entry, parsedRules); + const found = await findAdditionalModules( + props.projectRoot, + props.entry, + parsedRules + ); foundModulePaths = found.map(({ name }) => path.resolve(props.entry.moduleRoot, name) ); diff --git a/packages/wrangler/src/deployment-bundle/resolve-entry.ts b/packages/wrangler/src/deployment-bundle/resolve-entry.ts index 2da92e262709..1568bfd1464a 100644 --- a/packages/wrangler/src/deployment-bundle/resolve-entry.ts +++ b/packages/wrangler/src/deployment-bundle/resolve-entry.ts @@ -12,32 +12,28 @@ export function resolveEntryWithScript(script: string): { export function resolveEntryWithMain( main: string, - configPath?: string + projectRoot: string ): { absolutePath: string; relativePath: string; - projectRoot: string; } { - const projectRoot = path.resolve(path.dirname(configPath ?? ".")); const file = path.resolve(projectRoot, main); const relativePath = path.relative(projectRoot, file) || "."; - return { absolutePath: file, relativePath, projectRoot }; + return { absolutePath: file, relativePath }; } export function resolveEntryWithEntryPoint( entryPoint: string, - configPath?: string + projectRoot: string ): { absolutePath: string; relativePath: string; - projectRoot: string; } { - const projectRoot = path.resolve(path.dirname(configPath ?? ".")); const file = path.extname(entryPoint) ? path.resolve(entryPoint) : path.resolve(entryPoint, "index.js"); const relativePath = path.relative(projectRoot, file) || "."; - return { absolutePath: file, relativePath, projectRoot }; + return { absolutePath: file, relativePath }; } export function resolveEntryWithAssets(): { diff --git a/packages/wrangler/src/dev/use-esbuild.ts b/packages/wrangler/src/dev/use-esbuild.ts index 0e2bdad78008..406230239653 100644 --- a/packages/wrangler/src/dev/use-esbuild.ts +++ b/packages/wrangler/src/dev/use-esbuild.ts @@ -82,7 +82,7 @@ export function runBuild( local: boolean; targetConsumer: "dev" | "deploy"; testScheduled: boolean; - projectRoot: string | undefined; + projectRoot: string; onStart: () => void; defineNavigatorUserAgent: boolean; checkFetch: boolean; @@ -98,6 +98,7 @@ export function runBuild( const moduleCollector = noBundle ? noopModuleCollector : createModuleCollector({ + projectRoot: projectRoot, wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences( entryDirectory, entry.file @@ -110,7 +111,7 @@ export function runBuild( async function getAdditionalModules() { return noBundle ? dedupeModulesByName([ - ...((await doFindAdditionalModules(entry, rules)) ?? []), + ...((await doFindAdditionalModules(projectRoot, entry, rules)) ?? []), ...additionalModules, ]) : additionalModules; @@ -193,7 +194,7 @@ export function runBuild( // Check whether we need to watch a Python requirements.txt file. const watchPythonRequirements = getBundleType(entry.format, entry.file) === "python" - ? path.resolve(entry.projectRoot, "requirements.txt") + ? path.resolve(projectRoot, "requirements.txt") : undefined; if (watchPythonRequirements) { diff --git a/packages/wrangler/src/pages/functions/buildPlugin.ts b/packages/wrangler/src/pages/functions/buildPlugin.ts index 2ac907f29ae0..4c5f5deb84c6 100644 --- a/packages/wrangler/src/pages/functions/buildPlugin.ts +++ b/packages/wrangler/src/pages/functions/buildPlugin.ts @@ -29,12 +29,12 @@ export function buildPluginFromFunctions({ }: Options) { const entry: Entry = { file: resolve(getBasePath(), "templates/pages-template-plugin.ts"), - projectRoot: functionsDirectory, format: "modules", moduleRoot: functionsDirectory, exports: [], }; const moduleCollector = createModuleCollector({ + projectRoot: functionsDirectory, entry, findAdditionalModules: false, }); diff --git a/packages/wrangler/src/pages/functions/buildWorker.ts b/packages/wrangler/src/pages/functions/buildWorker.ts index 95c9e4cc4b5b..1856191f08fb 100644 --- a/packages/wrangler/src/pages/functions/buildWorker.ts +++ b/packages/wrangler/src/pages/functions/buildWorker.ts @@ -11,7 +11,7 @@ import { import { FatalError } from "../../errors"; import { logBuildFailure, logger } from "../../logger"; import { getBasePath } from "../../paths"; -import { getPagesProjectRoot, getPagesTmpDir } from "../utils"; +import { getPagesTmpDir } from "../utils"; import type { BundleResult } from "../../deployment-bundle/bundle"; import type { Entry } from "../../deployment-bundle/entry"; import type { CfModule } from "../../deployment-bundle/worker"; @@ -55,12 +55,12 @@ export function buildWorkerFromFunctions({ }: Options) { const entry: Entry = { file: resolve(getBasePath(), "templates/pages-template-worker.ts"), - projectRoot: functionsDirectory, format: "modules", moduleRoot: functionsDirectory, exports: [], }; const moduleCollector = createModuleCollector({ + projectRoot: functionsDirectory, entry, findAdditionalModules: false, }); @@ -90,7 +90,7 @@ export function buildWorkerFromFunctions({ checkFetch: local && checkFetch, targetConsumer: local ? "dev" : "deploy", local, - projectRoot: getPagesProjectRoot(), + projectRoot: functionsDirectory, defineNavigatorUserAgent, legacyAssets: undefined, @@ -151,14 +151,17 @@ export function buildRawWorker({ }: RawOptions) { const entry: Entry = { file: workerScriptPath, - projectRoot: resolve(directory), format: "modules", moduleRoot: resolve(directory), exports: [], }; const moduleCollector = externalModules ? noopModuleCollector - : createModuleCollector({ entry, findAdditionalModules: false }); + : createModuleCollector({ + projectRoot: resolve(directory), + entry, + findAdditionalModules: false, + }); return bundleWorker(entry, outdir ? resolve(outdir) : resolve(outfile), { bundle, @@ -204,7 +207,7 @@ export function buildRawWorker({ checkFetch: local && checkFetch, targetConsumer: local ? "dev" : "deploy", local, - projectRoot: getPagesProjectRoot(), + projectRoot: resolve(directory), defineNavigatorUserAgent, legacyAssets: undefined, @@ -238,9 +241,9 @@ export async function produceWorkerBundleForWorkerJSDirectory({ const entrypoint = resolve(join(workerJSDirectory, "index.js")); const additionalModules = await findAdditionalModules( + resolve(workerJSDirectory), { file: entrypoint, - projectRoot: resolve(workerJSDirectory), format: "modules", moduleRoot: resolve(workerJSDirectory), exports: [], diff --git a/packages/wrangler/src/versions/index.ts b/packages/wrangler/src/versions/index.ts index 20086d43cc65..de4294a02e6c 100644 --- a/packages/wrangler/src/versions/index.ts +++ b/packages/wrangler/src/versions/index.ts @@ -202,7 +202,6 @@ async function versionsUploadHandler( const configPath = args.config || (args.script && findWranglerConfig(path.dirname(args.script))); - const projectRoot = configPath && path.dirname(configPath); const config = readConfig(configPath, args); const entry = await getEntry(args, config, "versions upload"); await metrics.sendMetricsEvent( @@ -268,7 +267,7 @@ async function versionsUploadHandler( await verifyWorkerMatchesCITag( accountId, name, - path.relative(entry.projectRoot, config.configPath ?? "wrangler.toml") + path.relative(config.projectRoot, config.configPath ?? "wrangler.toml") ); } @@ -302,8 +301,6 @@ async function versionsUploadHandler( dryRun: args.dryRun, noBundle: !(args.bundle ?? !config.no_bundle), keepVars: false, - projectRoot, - tag: args.tag, message: args.message, }); diff --git a/packages/wrangler/src/versions/upload.ts b/packages/wrangler/src/versions/upload.ts index 0e55160e8da7..0896c5be2586 100644 --- a/packages/wrangler/src/versions/upload.ts +++ b/packages/wrangler/src/versions/upload.ts @@ -69,7 +69,6 @@ type Props = { dryRun: boolean | undefined; noBundle: boolean | undefined; keepVars: boolean | undefined; - projectRoot: string | undefined; tag: string | undefined; message: string | undefined; @@ -229,7 +228,7 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m } const destination = - props.outDir ?? getWranglerTmpDir(props.projectRoot, "deploy"); + props.outDir ?? getWranglerTmpDir(props.config.projectRoot, "deploy"); const start = Date.now(); const workerName = scriptName; @@ -271,6 +270,7 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m const entryDirectory = path.dirname(props.entry.file); const moduleCollector = createModuleCollector({ + projectRoot: props.config.projectRoot, wrangler1xLegacyModuleReferences: getWrangler1xLegacyModuleReferences( entryDirectory, props.entry.file @@ -291,7 +291,12 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m bundleType, ...bundle } = props.noBundle - ? await noBundleWorker(props.entry, props.rules, props.outDir) + ? await noBundleWorker( + props.config.projectRoot, + props.entry, + props.rules, + props.outDir + ) : await bundleWorker( props.entry, typeof destination === "string" ? destination : destination.path, @@ -319,7 +324,7 @@ See https://developers.cloudflare.com/workers/platform/compatibility-dates for m // This could potentially cause issues as we no longer have identical behaviour between dev and deploy? targetConsumer: "deploy", local: false, - projectRoot: props.projectRoot, + projectRoot: props.config.projectRoot, defineNavigatorUserAgent: isNavigatorDefined( props.compatibilityDate ?? config.compatibility_date, props.compatibilityFlags ?? config.compatibility_flags @@ -627,11 +632,12 @@ function formatTime(duration: number) { } async function noBundleWorker( + projectRoot: string, entry: Entry, rules: Rule[], outDir: string | undefined ) { - const modules = await findAdditionalModules(entry, rules); + const modules = await findAdditionalModules(projectRoot, entry, rules); if (outDir) { await writeAdditionalModules(modules, outDir); }