Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http"
---

Fix route joining to preserve trailing `/` when it would not result in `//`
15 changes: 8 additions & 7 deletions packages/http/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,28 @@ function needsSlashPrefix(fragment: string) {
);
}

function normalizeFragment(fragment: string, trimLast = false) {
function normalizeFragment(fragment: string) {
if (needsSlashPrefix(fragment)) {
// Insert the default separator
fragment = `/${fragment}`;
}

if (trimLast && fragment[fragment.length - 1] === "/") {
return fragment.slice(0, -1);
}
return fragment;
}

/**
* Joins route fragments, adding a slash when a fragment lacks a recognized separator
* and trimming one trailing slash from non-final fragments. Preserves URI-template path expansions.
* and merging overlapping slashes at fragment boundaries. Preserves URI-template path expansions.
* An empty input returns an empty string.
*/
export function joinPathSegments(rest: string[]) {
let current = "";
for (const [index, segment] of rest.entries()) {
current += normalizeFragment(segment, index < rest.length - 1);
for (const segment of rest) {
const normalized = normalizeFragment(segment);
if (current.endsWith("/") && (normalized.startsWith("/") || normalized.startsWith("{/"))) {
current = current.slice(0, -1);
}
current += normalized;
}
return current;
}
Expand Down
27 changes: 27 additions & 0 deletions packages/http/test/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,25 @@ describe("http: routes", () => {

deepStrictEqual(routes, [{ verb: "get", path: `/abc${sep}restype=container`, params: [] }]);
});

it("keeps trailing / on parent route when joining with child route", async () => {
const routes = await getRoutesFor(
`
@route("{blobName}/")
interface Container {
@put @route("${sep}some-query=true") op foo(blobName: string): void;
}
`,
);

deepStrictEqual(routes, [
{
verb: "put",
path: `/{blobName}/${sep}some-query=true`,
params: ["blobName"],
},
]);
});
});

describe("joinPathSegments", () => {
Expand Down Expand Up @@ -621,6 +640,14 @@ describe("uri template", () => {
const op = await getOp(`@route("/foo") op foo(${param}): void;`);
expect(op.uriTemplate).toEqual(expectedUri);
});

it.each([`@path(#{style: "path"}) one: string`, "@path one?: string"])(
"merges trailing / with path expansion for %s",
async (param) => {
const op = await getOp(`@route("/foo/") op foo(${param}): void;`);
expect(op.uriTemplate).toEqual("/foo{/one}");
},
);
});

describe("warn when path interpolation would result in duplicate //", () => {
Expand Down
Loading