Registry Mirror
Skip to content

‎apps/content/docs/integrations/nest.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ const contract = populateRouterContractOpenAPIPaths({
4646
})
4747
```
4848

49+
:::info
50+
NestJS matches paths with its platform's router. A param with literal text after it works only when that text starts with `.` or `-`, and a catch-all param must fill its whole segment. `/files/{name}.json` works, while `/apps/{id}:publish`, `/files/{name}json` and `/files/x{+path}.json` throw.
51+
:::
52+
4953
## Implement Your Contract
5054

5155
To implement your contract in NestJS, use the `@Implement` decorator and the `implement` function. The `@Implement` very similar to NestJS built-in HTTP method decorators (e.g., `@Get`, `@Post`) and can be used to implement either a single procedure contract or an [router contract](/docs/contract/router) or combine with other NestJS decorators.

‎apps/content/docs/migrations/from-v1.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ const listPlanet = os
106106
:::
107107

108108
:::warning[rou3 path syntax is now literal text]
109-
v1 also accepted rou3 syntax such as `/:id` and `**`. v2 reads only `{name}` and `{+name}` filling a whole path segment, so anything else is literal text and the route returns 404. This includes paths set with the `.route` extension.
109+
v1 also accepted rou3 syntax such as `/:id` and `**`. v2 reads only `{name}` and `{+name}` ([Path Parameters](/docs/openapi/routing#path-parameters)), so anything else is literal text and the route returns 404. This includes paths set with the `.route` extension.
110110

111111
<CodeGroup>
112112

‎apps/content/docs/openapi/routing.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ const getFile = os
4646

4747
A path can have only one `{+name}`, but more segments can follow it, as in `/files/{+path}/raw`.
4848

49+
A param can have literal text around it in its segment, as in `/files/{name}.json`, `/apps/{id}:publish` or `/files/x{+path}.json`. A segment can have only one param, and a name only ASCII letters, digits, `_` and `-`, so `/{name}-{version}.zip` and `/{a.b}` throw when the OpenAPI handler starts or the spec is generated.
50+
4951
:::info
5052
To customize path parameter encoding and decoding, see [Path Parameter Styles](/docs/openapi/input-and-output-mapping#path-parameter-styles).
5153
:::

‎packages/json-schema/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
"prepack": "tsdown"
4545
},
4646
"dependencies": {
47-
"@openapi-spec/types": "~0.8.0",
47+
"@openapi-spec/types": "~0.11.0",
4848
"@orpc/client": "workspace:*",
4949
"@orpc/contract": "workspace:*",
5050
"@orpc/server": "workspace:*",

‎packages/nest/src/implement.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,27 @@ describe('requirements', () => {
6464
}).toThrow(/openapi\.path/)
6565
})
6666

67+
it.each([
68+
['/files/{name}json', 'a param must be followed by "/", "." or "-", or end the path.'],
69+
['/apps/{id}:publish', 'a param must be followed by "/", "." or "-", or end the path.'],
70+
['/files/x{+path}', 'a catch-all param ({+name}) must fill its whole segment.'],
71+
['/files/{+path}.json', 'a catch-all param ({+name}) must fill its whole segment.'],
72+
] as const)('should throw for %s, which NestJS cannot route', (path, reason) => {
73+
const contract = oc.meta(openapi({ method: 'GET', path }))
74+
75+
expect(() => {
76+
@Controller()
77+
class ImplController {
78+
@Implement(contract)
79+
procedure() {
80+
return implement(contract).handler(() => {})
81+
}
82+
}
83+
84+
void ImplController
85+
}).toThrow(`NestJS can't route the OpenAPI path "${path}": ${reason}`)
86+
})
87+
6788
it('should throw if @Implement uses the QUERY HTTP method when QueryMethod is not available (NestJS < 11.2)', async () => {
6889
vi.resetModules()
6990
vi.doMock('@nestjs/common', async (importOriginal) => {
@@ -340,6 +361,15 @@ describe('routing', () => {
340361
)
341362
.input(z.object({ rest: z.string() })),
342363

364+
segmentPath: oc
365+
.meta(
366+
openapi({
367+
path: '/files/{name}.json',
368+
method: 'GET',
369+
}),
370+
)
371+
.input(z.object({ name: z.string() })),
372+
343373
prefixedPath: oc.meta(
344374
openapi({
345375
path: '/static',
@@ -398,6 +428,11 @@ describe('routing', () => {
398428
return implement(contract.restPath).handler(({ input }) => `rest: ${input.rest}`)
399429
}
400430

431+
@Implement(contract.segmentPath)
432+
segmentPath() {
433+
return implement(contract.segmentPath).handler(({ input }) => `name: ${input.name}`)
434+
}
435+
401436
@Implement(contract.prefixedPath)
402437
prefixedPath() {
403438
return implement(contract.prefixedPath).handler(({ input }) => `prefixed path`)
@@ -434,6 +469,7 @@ describe('routing', () => {
434469
({ input }) => `param: ${input.param}`,
435470
),
436471
restPath: implement(contract.restPath).handler(({ input }) => `rest: ${input.rest}`),
472+
segmentPath: implement(contract.segmentPath).handler(({ input }) => `name: ${input.name}`),
437473
prefixedPath: implement(contract.prefixedPath).handler(() => `prefixed path`),
438474
dynamicPrefix: implement(contract.dynamicPrefix).handler(
439475
({ input }) => `prefix: ${input.prefix}`,
@@ -492,6 +528,13 @@ describe('routing', () => {
492528
expect(res.body).toEqual('rest: some/long/path')
493529
})
494530

531+
it('should handle a param with literal text around it in a segment', async () => {
532+
const res = await supertest(httpServer).get('/files/report.json')
533+
534+
expect(res.statusCode).toEqual(200)
535+
expect(res.body).toEqual('name: report')
536+
})
537+
495538
it('should handle prefixed path', async () => {
496539
const res = await supertest(httpServer).post('/prefix/static')
497540

‎packages/nest/src/implement.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -537,14 +537,31 @@ function toNestPattern(path: `/${string}`): `/${string}` {
537537
return path
538538
}
539539

540+
let pattern = path
541+
540542
for (let i = params.length - 1; i >= 0; i--) {
541543
const param = params[i]!
542-
const pattern = param.allowsSlash ? `*` : `:${param.parameterName}`
543-
path =
544-
path.slice(0, param.startIndex) +
545-
pattern +
546-
path.slice(param.startIndex + param.segment.length)
544+
const next = path[param.startIndex + param.segment.length]
545+
546+
if (
547+
param.allowsSlash &&
548+
(path[param.startIndex - 1] !== '/' || (next !== undefined && next !== '/'))
549+
) {
550+
throw new TypeError(
551+
`NestJS can't route the OpenAPI path "${path}": a catch-all param ({+name}) must fill its whole segment.`,
552+
)
553+
}
554+
555+
// NestJS platforms read a letter, digit or `:` right after a param as part of its name
556+
if (!param.allowsSlash && next !== undefined && next !== '/' && next !== '.' && next !== '-') {
557+
throw new TypeError(
558+
`NestJS can't route the OpenAPI path "${path}": a param must be followed by "/", "." or "-", or end the path.`,
559+
)
560+
}
561+
562+
pattern =
563+
`${pattern.slice(0, param.startIndex)}${param.allowsSlash ? '*' : `:${param.parameterName}`}${pattern.slice(param.startIndex + param.segment.length)}` as `/${string}`
547564
}
548565

549-
return path
566+
return pattern
550567
}

‎packages/openapi/package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@
9898
"prepack": "tsdown"
9999
},
100100
"dependencies": {
101-
"@openapi-spec/downgrader": "~0.8.0",
102-
"@openapi-spec/router": "~0.8.0",
103-
"@openapi-spec/types": "~0.8.0",
101+
"@openapi-spec/downgrader": "~0.11.0",
102+
"@openapi-spec/router": "~0.11.0",
103+
"@openapi-spec/types": "~0.11.0",
104104
"@orpc/client": "workspace:*",
105105
"@orpc/contract": "workspace:*",
106106
"@orpc/json-schema": "workspace:*",

‎packages/openapi/src/adapters/standard/openapi-link-codec.test.ts‎

Lines changed: 54 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,38 @@ describe('openAPILinkCodec', () => {
712712
expect(request.url).toBe('/api/items/a%2Fb/docs/v1/read%20me')
713713
})
714714

715+
it('fills params with literal text around them in a segment', async () => {
716+
const codec = new OpenAPILinkCodec(
717+
{
718+
publish: oc.meta(openapi({ path: '/apps/{id}:publish' })),
719+
download: oc.meta(
720+
openapi({ path: '/v{version}/{name}.zip', inputStructure: 'detailed' }),
721+
),
722+
file: oc.meta(openapi({ path: '/files/x{+path}.json' })),
723+
},
724+
{ url: '/api', serializer },
725+
)
726+
727+
const publish = await codec.encodeInput({ id: 'a:b', draft: true }, ['publish'], {
728+
context: {},
729+
})
730+
731+
expect(publish.url).toBe('/api/apps/a%3Ab:publish')
732+
expect(publish.body).toEqual({ draft: true })
733+
734+
const download = await codec.encodeInput(
735+
{ params: { version: '2', name: 'a-b' } },
736+
['download'],
737+
{ context: {} },
738+
)
739+
740+
expect(download.url).toBe('/api/v2/a-b.zip')
741+
742+
const file = await codec.encodeInput({ path: 'a b/c' }, ['file'], { context: {} })
743+
744+
expect(file.url).toBe('/api/files/xa%20b/c.json')
745+
})
746+
715747
it('treats scalar values as primitive for array/object params', async () => {
716748
const codec = new OpenAPILinkCodec(
717749
{
@@ -806,35 +838,34 @@ describe('openAPILinkCodec', () => {
806838
await expect(
807839
codec.encodeInput({ ...valid, id }, ['item'], { context: {} }),
808840
).rejects.toThrow(
809-
'Path param "id" cannot contain "." or ".." segments in call to procedure (item).',
841+
'Path params cannot form "." or ".." segments in call to procedure (item).',
810842
)
811843
}
812844

813845
for (const ids of [['.'], ['..'], [null, '..']]) {
814846
await expect(
815847
codec.encodeInput({ ...valid, ids }, ['item'], { context: {} }),
816848
).rejects.toThrow(
817-
'Path param "ids" cannot contain "." or ".." segments in call to procedure (item).',
849+
'Path params cannot form "." or ".." segments in call to procedure (item).',
818850
)
819851
}
820852

821-
for (const rest of [
822-
'.',
823-
'..',
824-
'./a',
825-
'../a',
826-
'a/.',
827-
'a/..',
828-
'a/./b',
829-
'a/../../admin',
830-
'/../a',
831-
]) {
853+
for (const rest of ['.', '..', './a', '../a', 'a/.', 'a/..', 'a/./b', 'a/../../admin']) {
832854
await expect(
833855
codec.encodeInput({ ...valid, rest }, ['item'], { context: {} }),
834856
).rejects.toThrow(
835-
'Path param "rest" cannot contain "." or ".." segments in call to procedure (item).',
857+
'Path params cannot form "." or ".." segments in call to procedure (item).',
836858
)
837859
}
860+
861+
const dotted = new OpenAPILinkCodec(
862+
{ item: oc.meta(openapi({ path: '/x/.{name}' })) },
863+
{ url: '/api', serializer },
864+
)
865+
866+
await expect(dotted.encodeInput({ name: '.' }, ['item'], { context: {} })).rejects.toThrow(
867+
'Path params cannot form "." or ".." segments in call to procedure (item).',
868+
)
838869
})
839870

840871
it('allows path params that only contain dots within a segment', async () => {
@@ -845,6 +876,7 @@ describe('openAPILinkCodec', () => {
845876
path: '/items/{id}/{+rest}',
846877
}),
847878
),
879+
file: oc.meta(openapi({ path: '/files/{name}.json' })),
848880
},
849881
{ url: '/api', serializer },
850882
)
@@ -856,6 +888,14 @@ describe('openAPILinkCodec', () => {
856888
)
857889

858890
expect(request.url).toBe('/api/items/.../.well-known/a..b/v1.2/.../%252e%252e')
891+
892+
expect(
893+
(await codec.encodeInput({ id: 'a', rest: '/../a' }, ['item'], { context: {} })).url,
894+
).toBe('/api/items/a/%2F../a')
895+
896+
expect((await codec.encodeInput({ name: '.' }, ['file'], { context: {} })).url).toBe(
897+
'/api/files/..json',
898+
)
859899
})
860900

861901
it('encodes a leading slash in catch-all path params so the url is never protocol-relative', async () => {

‎packages/openapi/src/adapters/standard/openapi-link-codec.ts‎

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ import {
3939
import type { OpenAPIMeta } from '../../meta'
4040
import { getOpenAPIMeta } from '../../meta'
4141
import { OpenAPISerializer } from '../../openapi-serializer'
42-
import { getDynamicPathParams, isBodylessMethod } from '../../utils'
42+
import type { DynamicPathParam } from '../../utils'
43+
import { fillDynamicPathParams, getDynamicPathParams, isBodylessMethod } from '../../utils'
4344
import { serializeHeaders } from './utils'
4445

4546
export interface OpenAPILinkCodecOptions<T extends ClientContext> {
@@ -151,18 +152,11 @@ export class OpenAPILinkCodec<T extends ClientContext> implements StandardLinkCo
151152
)
152153
}
153154

155+
pathname = this.fillPathname(pathname, dynamicParams, input, meta, path)
156+
154157
const remaining = { ...input }
155158

156-
for (let i = dynamicParams.length - 1; i >= 0; i--) {
157-
const param = dynamicParams[i]!
158-
const encoded = this.encodePathParam(
159-
input[param.parameterName],
160-
param,
161-
meta?.paramsStyles?.[param.parameterName],
162-
path,
163-
)
164-
pathname =
165-
`${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}` as `/${string}`
159+
for (const param of dynamicParams) {
166160
delete remaining[param.parameterName]
167161
}
168162

@@ -217,18 +211,7 @@ export class OpenAPILinkCodec<T extends ClientContext> implements StandardLinkCo
217211
)
218212
}
219213

220-
for (let i = dynamicParams.length - 1; i >= 0; i--) {
221-
const param = dynamicParams[i]!
222-
const val = input.params[param.parameterName]
223-
const encoded = this.encodePathParam(
224-
val,
225-
param,
226-
meta?.paramsStyles?.[param.parameterName],
227-
path,
228-
)
229-
pathname =
230-
`${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}` as `/${string}`
231-
}
214+
pathname = this.fillPathname(pathname, dynamicParams, input.params, meta, path)
232215
}
233216

234217
if (input?.headers) {
@@ -259,9 +242,35 @@ export class OpenAPILinkCodec<T extends ClientContext> implements StandardLinkCo
259242
}
260243
}
261244

245+
private fillPathname(
246+
pathname: `/${string}`,
247+
params: DynamicPathParam[],
248+
values: Record<PropertyKey, unknown>,
249+
meta: OpenAPIMeta | undefined,
250+
path: string[],
251+
): `/${string}` {
252+
const filled = fillDynamicPathParams(pathname, params, (param) =>
253+
this.encodePathParam(
254+
values[param.parameterName],
255+
param,
256+
meta?.paramsStyles?.[param.parameterName],
257+
path,
258+
),
259+
)
260+
261+
// URL parsing (e.g. in fetch) resolves "." and ".." segments, which would send the request to a different endpoint
262+
if (DOT_SEGMENT_REGEX.test(filled)) {
263+
throw new TypeError(
264+
`Path params cannot form "." or ".." segments in call to procedure (${path.join('.')}).`,
265+
)
266+
}
267+
268+
return filled
269+
}
270+
262271
private encodePathParam(
263272
val: unknown,
264-
param: { parameterName: string; allowsSlash: boolean; segment: string },
273+
param: DynamicPathParam,
265274
style: Exclude<OpenAPIMeta['paramsStyles'], undefined>[string],
266275
path: string[],
267276
): string {
@@ -303,13 +312,6 @@ export class OpenAPILinkCodec<T extends ClientContext> implements StandardLinkCo
303312
)
304313
}
305314

306-
// URL parsing (e.g. in fetch) resolves "." and ".." segments, which would send the request to a different endpoint
307-
if (DOT_SEGMENT_REGEX.test(encoded)) {
308-
throw new TypeError(
309-
`Path param "${param.parameterName}" cannot contain "." or ".." segments in call to procedure (${path.join('.')}).`,
310-
)
311-
}
312-
313315
if (encoded.startsWith('/')) {
314316
encoded = `%2F${encoded.slice(1)}`
315317
}

0 commit comments

Comments
 (0)