Skip to content

Commit

Permalink
Fix esm-worker redirect dead-loop
Browse files Browse the repository at this point in the history
  • Loading branch information
ije committed Nov 21, 2023
1 parent 8b8b277 commit 301c73a
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 42 deletions.
34 changes: 21 additions & 13 deletions packages/esm-worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,19 @@ class ESMWorker {
url.pathname = pathname;
}

// strip loc
if (/:\d+:\d+$/.test(pathname)) {
pathname = splitBy(pathname, ":")[0];
}

// singleton build module
if (pathname.startsWith("/+")) {
return ctx.withCache(
() => fetchOriginWithKVCache(req, env, ctx, pathname),
{ varyUA: true },
);
}

// strip build version prefix
const hasBuildVerPrefix = regexpBuildVersionPrefix.test(pathname);
const hasBuildVerQuery = !hasBuildVerPrefix &&
Expand All @@ -263,13 +276,6 @@ class ESMWorker {
buildVersion = url.searchParams.get("pin")!;
}

if (pathname.startsWith("/+")) {
return ctx.withCache(
() => fetchOriginWithKVCache(req, env, ctx, pathname),
{ varyUA: true },
);
}

if (
pathname === "/build" || pathname === "/run" || pathname === "/server"
) {
Expand All @@ -281,7 +287,14 @@ class ESMWorker {
);
}
return ctx.withCache(
() => fetchOrigin(req, env, ctx, pathname, corsHeaders()),
() =>
fetchOrigin(
req,
env,
ctx,
`/${buildVersion}${pathname}`,
corsHeaders(),
),
{ varyUA: true },
);
}
Expand All @@ -297,11 +310,6 @@ class ESMWorker {
pathname = "/" + pathname.slice(2);
}

// strip loc
if (/:\d+:\d+$/.test(pathname)) {
pathname = splitBy(pathname, ":")[0];
}

if (
hasBuildVerPrefix && (
pathname === "/node.ns.d.ts" || (
Expand Down
44 changes: 22 additions & 22 deletions server/esm_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,28 +220,6 @@ func esmHandler() rex.Handle {
pathname = regexpLocPath.ReplaceAllString(pathname, "$1")
}

var hasBuildVerPrefix bool
var hasStablePrefix bool
var outdatedBuildVer string

// check build version prefix
buildBasePath := fmt.Sprintf("/v%d", CTX_BUILD_VERSION)
if strings.HasPrefix(pathname, "/stable/") {
pathname = strings.TrimPrefix(pathname, "/stable")
hasBuildVerPrefix = true
hasStablePrefix = true
} else if strings.HasPrefix(pathname, buildBasePath+"/") || pathname == buildBasePath {
a := strings.Split(pathname, "/")
pathname = "/" + strings.Join(a[2:], "/")
hasBuildVerPrefix = true
// Otherwise check possible fixed version
} else if regexpBuildVersionPath.MatchString(pathname) {
a := strings.Split(pathname, "/")
pathname = "/" + strings.Join(a[2:], "/")
hasBuildVerPrefix = true
outdatedBuildVer = a[1]
}

// determine build target by `?target` query or `User-Agent` header
target := strings.ToLower(ctx.Form.Value("target"))
targetFromUA := targets[target] == 0
Expand All @@ -268,6 +246,28 @@ func esmHandler() rex.Handle {
return rex.Content(savaPath, fi.ModTime(), r) // auto closed
}

var hasBuildVerPrefix bool
var hasStablePrefix bool
var outdatedBuildVer string

// check build version prefix
buildBasePath := fmt.Sprintf("/v%d", CTX_BUILD_VERSION)
if strings.HasPrefix(pathname, "/stable/") {
pathname = strings.TrimPrefix(pathname, "/stable")
hasBuildVerPrefix = true
hasStablePrefix = true
} else if strings.HasPrefix(pathname, buildBasePath+"/") || pathname == buildBasePath {
a := strings.Split(pathname, "/")
pathname = "/" + strings.Join(a[2:], "/")
hasBuildVerPrefix = true
// Otherwise check possible fixed version
} else if regexpBuildVersionPath.MatchString(pathname) {
a := strings.Split(pathname, "/")
pathname = "/" + strings.Join(a[2:], "/")
hasBuildVerPrefix = true
outdatedBuildVer = a[1]
}

if pathname == "/build" || pathname == "/run" {
if !hasBuildVerPrefix && !ctx.Form.Has("pin") {
url := fmt.Sprintf("%s%s/v%d%s", cdnOrigin, cfg.CdnBasePath, CTX_BUILD_VERSION, pathname)
Expand Down
15 changes: 8 additions & 7 deletions test/esm-worker/esm-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,26 @@ async function run(name: string, ...args: string[]) {
await run("pnpm", "i");
await run("node", "build.mjs");

const env = {
ESM_ORIGIN: "http://localhost:8080",
};
const workerOrigin = "http://localhost:8787";
const { withESMWorker } = await import(
"../../packages/esm-worker/dist/index.js"
`../../packages/esm-worker/dist/index.js`
);
const worker = withESMWorker(
(_req: Request, _env: {}, ctx: { url: URL }) => {
(_req: Request, _env: typeof env, ctx: { url: URL }) => {
if (ctx.url.pathname === "/") {
return new Response("<h1>Welcome to esm.sh!</h1>", {
headers: { "content-type": "text/html" },
});
}
},
);
const env = {
ESM_ORIGIN: "http://localhost:8080",
};

const ac = new AbortController();

// start worker
// start the worker
serve((req) => worker.fetch(req, env, { waitUntil: () => {} }), {
port: 8787,
signal: ac.signal,
Expand Down Expand Up @@ -280,7 +281,7 @@ Deno.test("esm-worker", {
res2.headers.get("Cache-Control"),
"public, max-age=31536000, immutable",
);
const pkgJson: any = await res2.json();
const pkgJson = await res2.json();
assertEquals(pkgJson.name, "react");
});

Expand Down

0 comments on commit 301c73a

Please sign in to comment.