Skip to content

Commit 93ef8d3

Browse files
committed
improve withCloudflare() execution cost
1 parent 0876873 commit 93ef8d3

File tree

1 file changed

+59
-22
lines changed

1 file changed

+59
-22
lines changed

packages/open-next/src/overrides/originResolver/pattern-env.ts

Lines changed: 59 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,71 @@ import type { OriginResolver } from "types/overrides";
33

44
import { debug, error } from "../../adapters/logger";
55

6+
// Cache parsed origin and compiled patterns at module level
7+
let cachedOrigin: Record<string, Origin> | null = null;
8+
const cachedPatterns: Array<{
9+
key: string;
10+
patterns: string[];
11+
regexes: RegExp[];
12+
}> = [];
13+
let initialized = false;
14+
15+
function initialize() {
16+
if (initialized) return;
17+
18+
// Parse origin JSON once
19+
cachedOrigin = JSON.parse(process.env.OPEN_NEXT_ORIGIN ?? "{}") as Record<
20+
string,
21+
Origin
22+
>;
23+
24+
// Pre-compile all regex patterns
25+
const functions = globalThis.openNextConfig.functions ?? {};
26+
for (const key in functions) {
27+
if (key !== "default") {
28+
const value = functions[key];
29+
const regexes: RegExp[] = [];
30+
31+
for (const pattern of value.patterns) {
32+
// Convert cloudfront pattern to regex
33+
const regexPattern = `/${pattern
34+
.replace(/\*\*/g, "(.*)")
35+
.replace(/\*/g, "([^/]*)")
36+
.replace(/\//g, "\\/")
37+
.replace(/\?/g, ".")}`;
38+
regexes.push(new RegExp(regexPattern));
39+
}
40+
41+
cachedPatterns.push({
42+
key,
43+
patterns: value.patterns,
44+
regexes,
45+
});
46+
}
47+
}
48+
49+
initialized = true;
50+
}
51+
652
const envLoader: OriginResolver = {
753
name: "env",
854
resolve: async (_path: string) => {
955
try {
10-
const origin = JSON.parse(process.env.OPEN_NEXT_ORIGIN ?? "{}") as Record<
11-
string,
12-
Origin
13-
>;
14-
for (const [key, value] of Object.entries(
15-
globalThis.openNextConfig.functions ?? {},
16-
).filter(([key]) => key !== "default")) {
17-
if (
18-
value.patterns.some((pattern) => {
19-
// Convert cloudfront pattern to regex
20-
return new RegExp(
21-
// transform glob pattern to regex
22-
`/${pattern
23-
.replace(/\*\*/g, "(.*)")
24-
.replace(/\*/g, "([^/]*)")
25-
.replace(/\//g, "\\/")
26-
.replace(/\?/g, ".")}`,
27-
).test(_path);
28-
})
29-
) {
30-
debug("Using origin", key, value.patterns);
31-
return origin[key];
56+
initialize();
57+
58+
// Use cached origin
59+
const origin = cachedOrigin!;
60+
61+
// Test against pre-compiled patterns
62+
for (const { key, patterns, regexes } of cachedPatterns) {
63+
for (const regex of regexes) {
64+
if (regex.test(_path)) {
65+
debug("Using origin", key, patterns);
66+
return origin[key];
67+
}
3268
}
3369
}
70+
3471
if (_path.startsWith("/_next/image") && origin.imageOptimizer) {
3572
debug("Using origin", "imageOptimizer", _path);
3673
return origin.imageOptimizer;

0 commit comments

Comments
 (0)