Skip to content

Commit ad6fd0f

Browse files
committed
WIP
1 parent da29860 commit ad6fd0f

File tree

15 files changed

+159
-207
lines changed

15 files changed

+159
-207
lines changed

.changeset/cuddly-rules-rest.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
"wrangler": patch
2+
"wrangler": minor
33
---
44

55
feat: Add support for the undocumented `_worker.js/` directory in Pages

fixtures/local-mode-tests/package.json

+2-19
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,8 @@
99
"main": "index.js",
1010
"scripts": {
1111
"check:type": "tsc && tsc -p tests/tsconfig.json",
12-
"test": "cross-env NODE_ENV=local-testing NODE_OPTIONS=--experimental-vm-modules npx jest --forceExit",
13-
"test:ci": "cross-env NODE_ENV=local-testing NODE_OPTIONS=--experimental-vm-modules npx jest --forceExit"
14-
},
15-
"jest": {
16-
"restoreMocks": true,
17-
"testRegex": ".*.(test|spec)\\.[jt]sx?$",
18-
"testTimeout": 30000,
19-
"transform": {
20-
"^.+\\.c?(t|j)sx?$": [
21-
"esbuild-jest",
22-
{
23-
"sourcemap": true
24-
}
25-
]
26-
},
27-
"transformIgnorePatterns": [
28-
"node_modules/(?!find-up|locate-path|p-locate|p-limit|p-timeout|p-queue|yocto-queue|path-exists|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream|get-port|supports-color|pretty-bytes)",
29-
"wrangler-dist/cli.js"
30-
]
12+
"test": "npx vitest",
13+
"test:ci": "npx vitest"
3114
},
3215
"devDependencies": {
3316
"@cloudflare/workers-types": "^4.20221111.1",

fixtures/pages-workerjs-directory/public/_worker.js/index.js

+7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
1+
import staticMod from "./static.js";
2+
13
export default {
24
async fetch(request, env) {
35
const { pathname } = new URL(request.url);
6+
7+
if (pathname === "/static") {
8+
return new Response(staticMod);
9+
}
10+
411
if (pathname !== "/") {
512
return new Response((await import(`./${pathname.slice(1)}`)).default);
613
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default "static";

fixtures/pages-workerjs-directory/tests/index.test.ts

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import { resolve } from "node:path";
1+
import { execSync } from "node:child_process";
2+
import { readFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import path, { join, resolve } from "node:path";
25
import { fetch } from "undici";
36
import { describe, it } from "vitest";
47
import { runWranglerPagesDev } from "../../shared/src/run-wrangler-long-lived";
@@ -13,9 +16,27 @@ describe.concurrent("Pages _worker.js/ directory", () => {
1316
await expect(
1417
fetch(`http://${ip}:${port}/`).then((resp) => resp.text())
1518
).resolves.toContain("Hello, world!");
19+
await expect(
20+
fetch(`http://${ip}:${port}/static`).then((resp) => resp.text())
21+
).resolves.toContain("static");
1622
await expect(
1723
fetch(`http://${ip}:${port}/other-script`).then((resp) => resp.text())
1824
).resolves.toContain("test");
1925
await stop();
2026
});
27+
28+
it("should bundle", async ({ expect }) => {
29+
const dir = tmpdir();
30+
const file = join(dir, "./_worker.bundle");
31+
32+
execSync(
33+
`npx wrangler pages functions build --build-output-directory public --outfile ${file} --bindings="{\\"d1_databases\\":{\\"FOO\\":{}}}"`,
34+
{
35+
cwd: path.resolve(__dirname, ".."),
36+
}
37+
);
38+
39+
expect(readFileSync(file, "utf-8")).toContain("D1_ERROR");
40+
expect(readFileSync(file, "utf-8")).toContain('"static"');
41+
});
2142
});

packages/wrangler/src/__tests__/pages/functions-build.test.ts

+10-7
Original file line numberDiff line numberDiff line change
@@ -470,9 +470,7 @@ export default {
470470
export const cat = "cat";`
471471
);
472472

473-
await runWrangler(
474-
`pages functions build --outfile=public/_worker.bundle --compatibility-flag=nodejs_compat`
475-
);
473+
await runWrangler(`pages functions build --outfile=public/_worker.bundle`);
476474

477475
expect(existsSync("public/_worker.bundle")).toBe(true);
478476
expect(std.out).toMatchInlineSnapshot(`
@@ -485,20 +483,24 @@ export const cat = "cat";`
485483
workerBundleContents,
486484
[
487485
[/------formdata-undici-0.[0-9]*/g, "------formdata-undici-0.test"],
488-
[/functionsWorker-0.[0-9]*.js/g, "functionsWorker-0.test.js"],
486+
[/bundledWorker-0.[0-9]*.mjs/g, "bundledWorker-0.test.mjs"],
487+
[/bundledWorker-0.[0-9]*.map/g, "bundledWorker-0.test.map"],
489488
]
490489
);
491490

492491
expect(workerBundleWithConstantData).toMatchInlineSnapshot(`
493492
"------formdata-undici-0.test
494493
Content-Disposition: form-data; name=\\"metadata\\"
495494
496-
{\\"main_module\\":\\"functionsWorker-0.test.js\\"}
495+
{\\"main_module\\":\\"bundledWorker-0.test.mjs\\"}
497496
------formdata-undici-0.test
498-
Content-Disposition: form-data; name=\\"functionsWorker-0.test.js\\"; filename=\\"functionsWorker-0.test.js\\"
497+
Content-Disposition: form-data; name=\\"bundledWorker-0.test.mjs\\"; filename=\\"bundledWorker-0.test.mjs\\"
499498
Content-Type: application/javascript+module
500499
501-
import { cat } from \\"./cat.js\\";
500+
// _worker.js/cat.js
501+
var cat = \\"cat\\";
502+
503+
// _worker.js/index.js
502504
var worker_default = {
503505
async fetch(request, env) {
504506
return new Response(\\"Hello from _worker.js/index.js\\" + cat);
@@ -507,6 +509,7 @@ export const cat = "cat";`
507509
export {
508510
worker_default as default
509511
};
512+
//# sourceMappingURL=bundledWorker-0.test.mjs.map
510513
511514
------formdata-undici-0.test
512515
Content-Disposition: form-data; name=\\"cat.js\\"; filename=\\"cat.js\\"

packages/wrangler/src/api/dev.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export interface UnstableDevOptions {
4343
bucket_name: string;
4444
preview_bucket_name?: string;
4545
}[];
46-
bundleEntrypoint?: boolean;
46+
processEntrypoint?: boolean;
4747
moduleRoot?: string;
4848
rules?: Rule[];
4949
logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug"; // Specify logging level [choices: "debug", "info", "log", "warn", "error", "none"] [default: "log"]
@@ -154,7 +154,7 @@ export async function unstable_dev(
154154
},
155155
config: options?.config,
156156
env: options?.env,
157-
bundleEntrypoint: !!options?.bundleEntrypoint,
157+
processEntrypoint: !!options?.processEntrypoint,
158158
bundle: options?.bundle,
159159
compatibilityDate: options?.compatibilityDate,
160160
compatibilityFlags: options?.compatibilityFlags,

packages/wrangler/src/api/pages/publish.tsx

+16-48
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ import {
1414
import {
1515
buildRawWorker,
1616
checkRawWorker,
17+
traverseAndBuildWorkerJSDirectory,
1718
} from "../../pages/functions/buildWorker";
1819
import { validateRoutes } from "../../pages/functions/routes-validation";
1920
import { upload } from "../../pages/upload";
20-
import traverseModuleGraph from "../../traverse-module-graph";
2121
import { createUploadWorkerBundleContents } from "./create-worker-bundle-contents";
2222
import type { BundleResult } from "../../bundle";
2323
import type { Project, Deployment } from "@cloudflare/types";
@@ -66,7 +66,7 @@ interface PagesPublishOptions {
6666

6767
/**
6868
* Whether to run bundling on `_worker.js` before deploying.
69-
* Default: false
69+
* Default: true
7070
*/
7171
bundle?: boolean;
7272

@@ -96,9 +96,11 @@ export async function publish({
9696
_redirects: string | undefined,
9797
_routesGenerated: string | undefined,
9898
_routesCustom: string | undefined,
99-
_workerJSDirectory = false,
99+
_workerJSIsDirectory = false,
100100
_workerJS: string | undefined;
101101

102+
bundle = bundle ?? true;
103+
102104
const _workerPath = resolvePath(directory, "_worker.js");
103105

104106
try {
@@ -118,8 +120,8 @@ export async function publish({
118120
} catch {}
119121

120122
try {
121-
_workerJSDirectory = lstatSync(_workerPath).isDirectory();
122-
if (!_workerJSDirectory) {
123+
_workerJSIsDirectory = lstatSync(_workerPath).isDirectory();
124+
if (!_workerJSIsDirectory) {
123125
_workerJS = readFileSync(_workerPath, "utf-8");
124126
}
125127
} catch {}
@@ -245,51 +247,17 @@ export async function publish({
245247
* Advanced Mode
246248
* https://developers.cloudflare.com/pages/platform/functions/#advanced-mode
247249
*
248-
* When using a _worker.js file, the entire /functions directory is ignored
250+
* When using a _worker.js file or _worker.js/ directory, the entire /functions directory is ignored
249251
* – this includes its routing and middleware characteristics.
250252
*/
251-
if (_workerJSDirectory) {
252-
const traverseModuleGraphResult = await traverseModuleGraph(
253-
{
254-
file: resolvePath(join(_workerPath, "index.js")),
255-
directory: resolvePath(_workerPath),
256-
format: "modules",
257-
moduleRoot: resolvePath(_workerPath),
258-
},
259-
[
260-
{
261-
type: "ESModule",
262-
globs: ["**/*.js"],
263-
},
264-
]
265-
);
266-
267-
const outfile = join(tmpdir(), `./bundledWorker-${Math.random()}.mjs`);
268-
const bundleResult = await buildRawWorker({
269-
workerScriptPath: _workerPath,
270-
bundle: false,
271-
outfile,
272-
directory,
273-
local: false,
274-
sourcemap: true,
275-
watch: false,
276-
onEnd: () => {},
277-
betaD1Shims: d1Databases,
253+
if (_workerJSIsDirectory) {
254+
workerBundle = await traverseAndBuildWorkerJSDirectory({
255+
bundle,
256+
workerJSDirectory: _workerPath,
257+
buildOutputDirectory: directory,
258+
d1Databases,
278259
nodejsCompat,
279260
});
280-
281-
workerBundle = {
282-
modules: (traverseModuleGraphResult?.modules ??
283-
bundleResult?.modules) as BundleResult["modules"],
284-
dependencies: (bundleResult?.dependencies ??
285-
traverseModuleGraphResult?.dependencies) as BundleResult["dependencies"],
286-
resolvedEntryPointPath: (bundleResult?.resolvedEntryPointPath ??
287-
traverseModuleGraphResult?.resolvedEntryPointPath) as BundleResult["resolvedEntryPointPath"],
288-
bundleType: (bundleResult?.bundleType ??
289-
traverseModuleGraphResult?.bundleType) as BundleResult["bundleType"],
290-
stop: bundleResult?.stop,
291-
sourceMapPath: bundleResult?.sourceMapPath,
292-
};
293261
} else if (_workerJS) {
294262
if (bundle) {
295263
const outfile = join(tmpdir(), `./bundledWorker-${Math.random()}.mjs`);
@@ -317,7 +285,7 @@ export async function publish({
317285
}
318286
}
319287

320-
if (_workerJS || _workerJSDirectory) {
288+
if (_workerJS || _workerJSIsDirectory) {
321289
const workerBundleContents = await createUploadWorkerBundleContents(
322290
workerBundle as BundleResult
323291
);
@@ -351,7 +319,7 @@ export async function publish({
351319
* Pages Functions
352320
* https://developers.cloudflare.com/pages/platform/functions/
353321
*/
354-
if (builtFunctions && !_workerJS) {
322+
if (builtFunctions && !_workerJS && !_workerJSIsDirectory) {
355323
const workerBundleContents = await createUploadWorkerBundleContents(
356324
workerBundle as BundleResult
357325
);

packages/wrangler/src/dev.tsx

+3-3
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ export type AdditionalDevProps = {
334334
preview_bucket_name?: string;
335335
}[];
336336
d1Databases?: Environment["d1_databases"];
337-
bundleEntrypoint?: boolean;
337+
processEntrypoint?: boolean;
338338
moduleRoot?: string;
339339
rules?: Rule[];
340340
};
@@ -427,7 +427,7 @@ export async function startDev(args: StartDevOptions) {
427427
zone={zoneId}
428428
host={host}
429429
routes={routes}
430-
bundleEntrypoint={!!args.bundleEntrypoint}
430+
processEntrypoint={!!args.processEntrypoint}
431431
rules={args.rules ?? getRules(configParam)}
432432
legacyEnv={isLegacyEnv(configParam)}
433433
minify={args.minify ?? configParam.minify}
@@ -564,7 +564,7 @@ export async function startApiDev(args: StartDevOptions) {
564564
zone: zoneId,
565565
host: host,
566566
routes: routes,
567-
bundleEntrypoint: !!args.bundleEntrypoint,
567+
processEntrypoint: !!args.processEntrypoint,
568568
rules: args.rules ?? getRules(configParam),
569569
legacyEnv: isLegacyEnv(configParam),
570570
minify: args.minify ?? configParam.minify,

packages/wrangler/src/dev/dev.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export type DevProps = {
116116
initialPort: number;
117117
initialIp: string;
118118
inspectorPort: number;
119-
bundleEntrypoint: boolean;
119+
processEntrypoint: boolean;
120120
rules: Config["rules"];
121121
accountId: string | undefined;
122122
initialMode: "local" | "remote";
@@ -272,7 +272,7 @@ function DevSession(props: DevSessionProps) {
272272
entry: props.entry,
273273
destination: directory,
274274
jsxFactory: props.jsxFactory,
275-
bundleEntrypoint: props.bundleEntrypoint,
275+
processEntrypoint: props.processEntrypoint,
276276
rules: props.rules,
277277
jsxFragment: props.jsxFragment,
278278
serveAssetsFromWorker: Boolean(

0 commit comments

Comments
 (0)