Skip to content

Commit 45edc9f

Browse files
committed
fixup! prepare for the assetResolver
See opennextjs/opennextjs-aws#917
1 parent 5906b89 commit 45edc9f

File tree

3 files changed

+5
-122
lines changed

3 files changed

+5
-122
lines changed

packages/cloudflare/src/cli/build/open-next/compile-skew-protection.ts

Lines changed: 1 addition & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,8 @@ import { fileURLToPath } from "node:url";
33

44
import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
55
import { build } from "esbuild";
6-
import { glob } from "glob";
76

87
import type { OpenNextConfig } from "../../../api";
9-
import type { FolderNode } from "../../templates/skew-protection";
108

119
export async function compileSkewProtection(options: BuildOptions, config: OpenNextConfig) {
1210
const currentDir = path.join(path.dirname(fileURLToPath(import.meta.url)));
@@ -15,23 +13,6 @@ export async function compileSkewProtection(options: BuildOptions, config: OpenN
1513

1614
const skewProtectionEnabled = config.cloudflare?.skewProtectionEnabled ?? false;
1715

18-
// Create a tree of assets located inside the base path
19-
const assetPath = path.join(options.outputDir, "assets", globalThis.__NEXT_BASE_PATH__ ?? "");
20-
const assets = skewProtectionEnabled
21-
? await glob(`**/*`, {
22-
windowsPathsNoEscape: true,
23-
posix: true,
24-
nodir: true,
25-
absolute: false,
26-
cwd: assetPath,
27-
// All files located inside `_next/static` are static assets, no need to list them
28-
ignore: ["_next/static/**"],
29-
})
30-
: [];
31-
32-
33-
const assetTree = filesToTree(assets);
34-
3516
await build({
3617
entryPoints: [initPath],
3718
outdir: path.join(options.outputDir, "cloudflare"),
@@ -42,39 +23,6 @@ export async function compileSkewProtection(options: BuildOptions, config: OpenN
4223
platform: "node",
4324
define: {
4425
__SKEW_PROTECTION_ENABLED__: JSON.stringify(skewProtectionEnabled),
45-
__CF_ASSETS_TREE__: JSON.stringify(assetTree),
4626
},
4727
});
48-
}
49-
50-
/**
51-
* Converts a list of file paths into a tree of `FolderNode`
52-
*
53-
* @param paths The list of path
54-
* @returns The root node of the tree
55-
*/
56-
export function filesToTree(paths: string[]): FolderNode {
57-
const root: FolderNode = {
58-
f: [],
59-
d: {},
60-
};
61-
62-
for (const filePath of paths) {
63-
// Split the path into components, filtering out empty strings from potential leading/trailing slashes
64-
const parts = filePath.split("/").filter(Boolean);
65-
66-
let currentNode: FolderNode = root;
67-
68-
// Traverse through folder parts, creating new nodes as needed
69-
for (let i = 0; i < parts.length - 1; i++) {
70-
const folderName = parts[i] as string;
71-
if (!currentNode.d[folderName]) {
72-
currentNode.d[folderName] = { f: [], d: {} };
73-
}
74-
currentNode = currentNode.d[folderName];
75-
}
76-
// Add the file to the current node's files array
77-
currentNode.f.push(parts[parts.length - 1] as string);
78-
}
79-
return root;
80-
}
28+
}

packages/cloudflare/src/cli/templates/skew-protection.ts

Lines changed: 3 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -25,25 +25,21 @@ export const CURRENT_VERSION_ID = "current";
2525
* @param request
2626
* @returns
2727
*/
28-
export function maybeGetSkewProtectionResponse(
29-
request: Request,
30-
assets: Fetcher | undefined
31-
): Promise<Response> | Response | undefined {
28+
export function maybeGetSkewProtectionResponse(request: Request): Promise<Response> | Response | undefined {
3229
// no early return as esbuild would not treeshake the code.
3330
if (__SKEW_PROTECTION_ENABLED__) {
3431
const url = new URL(request.url);
3532

3633
// Skew protection is only active for the latest version of the app served on a custom domain.
37-
// For `localhost` and older deployments we still need to serve assets when the worker runs first.
3834
if (url.hostname === "localhost" || url.pathname.endsWith(".workers.dev")) {
39-
return maybeFetchAsset(request, assets);
35+
return undefined;
4036
}
4137

4238
const requestDeploymentId = request.headers.get("x-deployment-id") ?? url.searchParams.get("dpl");
4339

4440
if (!requestDeploymentId || requestDeploymentId === process.env.DEPLOYMENT_ID) {
4541
// The request does not specify a deployment id or it is the current deployment id
46-
return maybeFetchAsset(request, assets);
42+
return undefined;
4743
}
4844

4945
const mapping = process.env[DEPLOYMENT_MAPPING_ENV_NAME]
@@ -69,69 +65,8 @@ export function maybeGetSkewProtectionResponse(
6965
}
7066
}
7167

72-
/**
73-
* Fetches a file from the assets when the path is a known asset.
74-
*
75-
* @param request The incoming request
76-
* @param assets The Fetcher used to retrieve assets
77-
* @returns A `Promise<Response>` when the path is an assets, undefined otherwise
78-
*/
79-
function maybeFetchAsset(request: Request, assets: Fetcher | undefined): Promise<Response> | undefined {
80-
if (!assets) {
81-
return undefined;
82-
}
83-
84-
let path = new URL(request.url).pathname;
85-
const basePath = globalThis.__NEXT_BASE_PATH__;
86-
if (basePath && path.startsWith(basePath)) {
87-
path = path.slice(basePath.length);
88-
}
89-
if (path.startsWith("/_next/static/") || isFileInTree(path, __CF_ASSETS_TREE__)) {
90-
return assets.fetch(request);
91-
}
92-
}
93-
94-
/**
95-
* A node represents a folder in the file tree
96-
*/
97-
export type FolderNode = {
98-
// List of files in this folder
99-
f: string[];
100-
// Sub-folders.
101-
d: Record<string, FolderNode>;
102-
};
103-
104-
/**
105-
* Checks whether a file is in the tree
106-
*
107-
* @param filepath The path to the file
108-
* @param tree The root node of the tree
109-
* @returns Whether the file is in this tree
110-
*/
111-
export function isFileInTree(filepath: string, tree: FolderNode): boolean {
112-
// Split the filename into components, filtering out empty strings from potential leading/trailing slashes
113-
const parts = filepath.split("/").filter(Boolean);
114-
115-
if (parts.length === 0) {
116-
return false; // An empty filename cannot be in the tree
117-
}
118-
119-
let currentNode: FolderNode | undefined = tree;
120-
121-
// Traverse through folder parts
122-
for (let i = 0; i < parts.length - 1; i++) {
123-
currentNode = currentNode.d[parts[i] as string];
124-
if (!currentNode) {
125-
return false; // Folder not found in the tree
126-
}
127-
}
128-
// Check if the file exists in the current node's files array
129-
return currentNode.f.includes(parts.at(-1) as string);
130-
}
131-
13268
/* eslint-disable no-var */
13369
declare global {
13470
var __SKEW_PROTECTION_ENABLED__: boolean;
135-
var __CF_ASSETS_TREE__: FolderNode;
13671
}
13772
/* eslint-enable no-var */

packages/cloudflare/src/cli/templates/worker.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export { BucketCachePurge } from "./.build/durable-objects/bucket-cache-purge.js
1717
export default {
1818
async fetch(request, env, ctx) {
1919
return runWithCloudflareRequestContext(request, env, ctx, async () => {
20-
const response = maybeGetSkewProtectionResponse(request, env.ASSETS);
20+
const response = maybeGetSkewProtectionResponse(request);
2121

2222
if (response) {
2323
return response;

0 commit comments

Comments
 (0)