diff --git a/.changesets/1794464217-f98ed08b.yaml b/.changesets/1794464217-f98ed08b.yaml new file mode 100644 index 000000000..e8663572f --- /dev/null +++ b/.changesets/1794464217-f98ed08b.yaml @@ -0,0 +1,10 @@ +id: 1794464217-f98ed08b +features: + - core +targets: + - typescriptv2 +type: feat +bump: patch +description: validate path, query and header parameter values against portable schema patterns before sending a request +author: TristanSpeakEasy +date: "2026-11-12" diff --git a/templates/perms.go b/templates/perms.go index c36b512cd..d10224fac 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -278,6 +278,7 @@ var fileMode = map[string]fs.FileMode{ "templates/common/common/modelusage.ts": 0o644, "templates/common/common/open-unions.ts": 0o644, "templates/common/common/operations.ts": 0o644, + "templates/common/common/patterns.ts": 0o644, "templates/common/common/polyfill.ts": 0o644, "templates/common/common/sanitization.ts": 0o644, "templates/common/common/sdkdocs.ts": 0o644, @@ -2461,6 +2462,7 @@ var fileMode = map[string]fs.FileMode{ "templates/typescriptv2/tests/primary/open_discriminated_union.test.ts": 0o644, "templates/typescriptv2/tests/primary/pagination.test.ts": 0o644, "templates/typescriptv2/tests/primary/parameter_additional.test.ts": 0o644, + "templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts": 0o644, "templates/typescriptv2/tests/primary/primary_helpers.ts": 0o644, "templates/typescriptv2/tests/primary/react_query_additional.test.ts": 0o644, "templates/typescriptv2/tests/primary/request_extras_additional.test.ts": 0o644, @@ -2500,6 +2502,7 @@ var fileMode = map[string]fs.FileMode{ "templates/typescriptv2/tests/tertiary/auth_additional.test.ts": 0o644, "templates/typescriptv2/tests/tertiary/mcp_additional.test.ts": 0o644, "templates/typescriptv2/tests/tertiary/mcp_compatibility_additional.test.ts": 0o644, + "templates/typescriptv2/tests/tertiary/parameter_patterns_additional.test.ts": 0o644, "templates/typescriptv2/tests/tertiary/servers.test.ts": 0o644, "templates/typescriptv2/tests/tertiary/smart_union.test.ts": 0o644, "templates/typescriptv2/tests/tertiary/webhooks.test.ts": 0o644, diff --git a/templates/templates/cli/includes/metadata.ts b/templates/templates/cli/includes/metadata.ts index df7599982..833763c44 100644 --- a/templates/templates/cli/includes/metadata.ts +++ b/templates/templates/cli/includes/metadata.ts @@ -775,80 +775,6 @@ function collectMultipartMetadata( } } -// Escapes with the same meaning in Go's regexp and ECMA-262 Unicode mode. -const portableEscapes = new Set("dDwWbBtnrfv^$\\.*+?()[]{}|/".split("")); -const portableClassEscapes = new Set("dDwWtnrfv^$\\.*+?()[]{}|/-".split("")); - -/** - * Consumes a `\` escape at pattern[i] and returns the index after it, or -1 - * when the escape is outside the portable set. - */ -function portableEscapeEnd( - pattern: string, - i: number, - allowed: Set, -): number { - const next = pattern[i + 1]; - if (next === "x") { - return /^[0-9A-Fa-f]{2}$/.test(pattern.slice(i + 2, i + 4)) ? i + 4 : -1; - } - return next !== undefined && allowed.has(next) ? i + 2 : -1; -} - -/** - * Whether a schema pattern can be enforced with Go's regexp without rejecting - * a value the JSON Schema pattern (ECMA-262 with the "u" flag) accepts. The - * CLI rejects mismatches outright, so a pattern is emitted only when it stays - * within the interoperable subset JSON Schema recommends — literals, `.`, - * character classes and ranges, `\d \w \b` and their negations, control and - * `\xHH` escapes, anchors, `(...)`/`(?:...)` groups, alternation, and `* + ? - * {n,m}` quantifiers (greedy or lazy) — and Go compiles it. That excludes, for - * example, `\s` (ASCII-only in Go), `\p{...}`, lookarounds, backreferences, and - * POSIX classes. Go's `.` also matches `\r` and U+2028, so it may accept a - * value ECMA-262 rejects; the server still decides those. - */ -function isPortablePattern(pattern: string): boolean { - if (!isRE2Regex(pattern)) return false; - let i = 0; - while (i < pattern.length) { - const c = pattern[i]; - if (c === "\\") { - i = portableEscapeEnd(pattern, i, portableEscapes); - if (i < 0) return false; - } else if (c === "(") { - if (pattern[i + 1] === "?" && pattern[i + 2] !== ":") return false; - i += pattern[i + 1] === "?" ? 3 : 1; - } else if (c === "{") { - // Go reads a bound with a leading zero ({01}) as literal text. - const quantifier = /^\{(0|[1-9]\d*)(,(0|[1-9]\d*)?)?\}/.exec( - pattern.slice(i), - ); - if (!quantifier) return false; - i += quantifier[0].length; - } else if (c === "}" || c === "]") { - return false; - } else if (c === "[") { - i++; - if (pattern[i] === "^") i++; - if (pattern[i] === "]") return false; - while (i < pattern.length && pattern[i] !== "]") { - if (pattern[i] === "[") return false; - if (pattern[i] === "\\") { - i = portableEscapeEnd(pattern, i, portableClassEscapes); - if (i < 0) return false; - } else { - i++; - } - } - if (i >= pattern.length) return false; - i++; - } else { - i++; - } - } - return true; -} - /** * Build a single FlagMeta Go literal for a field. */ diff --git a/templates/templates/common/common/examples.ts b/templates/templates/common/common/examples.ts index cabaac2ae..bac0d9a93 100644 --- a/templates/templates/common/common/examples.ts +++ b/templates/templates/common/common/examples.ts @@ -2,6 +2,7 @@ require("common/faker.ts"); require("common/typematching.ts"); require("common/constants.ts"); require("common/annotations.ts"); +require("common/patterns.ts"); const DEBUG_EXAMPLE_LOGGING = false; // Set this to true to enable very verbose logging of example generation results (don't leave this set to true outside local dev) const DEBUG_EXAMPLE_OP_FILTER = ""; // Set this to a specific operation ID to only log example results for that operation (don't leave this set outside local dev) @@ -1124,6 +1125,7 @@ function calculateBasicExample( } else { example = templatePlaceholderString(arrayIdx); } + example = conformExampleToPattern(fieldDef, example); } return example; @@ -1994,6 +1996,36 @@ function fakeNumber(fieldType: string) { } } +// Targets whose clients reject parameter values that do not match a portable +// schema pattern. +const patternEnforcingLanguages = new Set(["typescript"]); + +function conformExampleToPattern(fieldDef: FieldDef, value: string): string { + if ( + !patternEnforcingLanguages.has(context.Global.Config.Language) || + !isParameterField(fieldDef) + ) { + return value; + } + const pattern = portableStringPattern(fieldDef.Type); + if (!pattern) { + return value; + } + const rawMaxLength = fieldDef.Type.Validations?.MaxLength; + const maxLength = rawMaxLength == null ? Infinity : Number(rawMaxLength); + const fits = (s: string) => [...s].length <= maxLength; + if (fits(value) && new RegExp(pattern, "u").test(value)) { + return value; + } + for (const repeat of [3, 1, 0]) { + const example = exampleForPortablePattern(pattern, repeat); + if (example !== undefined && fits(example)) { + return example; + } + } + return value; +} + function templatePlaceholderString(arrayIdx?: number) { return ``; } diff --git a/templates/templates/common/common/patterns.ts b/templates/templates/common/common/patterns.ts new file mode 100644 index 000000000..343d32b8e --- /dev/null +++ b/templates/templates/common/common/patterns.ts @@ -0,0 +1,224 @@ +// Escapes with the same meaning in Go's regexp and ECMA-262 Unicode mode. +const portableEscapes = new Set("dDwWbBtnrfv^$\\.*+?()[]{}|/".split("")); +const portableClassEscapes = new Set("dDwWtnrfv^$\\.*+?()[]{}|/-".split("")); + +/** + * Consumes a `\` escape at pattern[i] and returns the index after it, or -1 + * when the escape is outside the portable set. + */ +function portableEscapeEnd( + pattern: string, + i: number, + allowed: Set, +): number { + const next = pattern[i + 1]; + if (next === "x") { + return /^[0-9A-Fa-f]{2}$/.test(pattern.slice(i + 2, i + 4)) ? i + 4 : -1; + } + return next !== undefined && allowed.has(next) ? i + 2 : -1; +} + +/** + * Whether a schema pattern means the same thing in Go's regexp and in ECMA-262 + * with the "u" flag (the JSON Schema dialect), so a generated client can + * enforce it without rejecting a value the API accepts. A pattern qualifies + * when it stays within the interoperable subset JSON Schema recommends — + * literals, `.`, character classes and ranges, `\d \w \b` and their negations, + * control and `\xHH` escapes, anchors, `(...)`/`(?:...)` groups, alternation, + * and `* + ? {n,m}` quantifiers (greedy or lazy) — and Go compiles it. That + * excludes, for example, `\s` (ASCII-only in Go), `\p{...}`, lookarounds, + * backreferences, and POSIX classes. Go's `.` also matches `\r` and U+2028, so + * it may accept a value ECMA-262 rejects; the server still decides those. + */ +function isPortablePattern(pattern: string): boolean { + if (!isRE2Regex(pattern)) return false; + let i = 0; + while (i < pattern.length) { + const c = pattern[i]; + if (c === "\\") { + i = portableEscapeEnd(pattern, i, portableEscapes); + if (i < 0) return false; + } else if (c === "(") { + if (pattern[i + 1] === "?" && pattern[i + 2] !== ":") return false; + i += pattern[i + 1] === "?" ? 3 : 1; + } else if (c === "{") { + // Go reads a bound with a leading zero ({01}) as literal text. + const quantifier = /^\{(0|[1-9]\d*)(,(0|[1-9]\d*)?)?\}/.exec( + pattern.slice(i), + ); + if (!quantifier) return false; + i += quantifier[0].length; + } else if (c === "}" || c === "]") { + return false; + } else if (c === "[") { + i++; + if (pattern[i] === "^") i++; + if (pattern[i] === "]") return false; + while (i < pattern.length && pattern[i] !== "]") { + if (pattern[i] === "[") return false; + if (pattern[i] === "\\") { + i = portableEscapeEnd(pattern, i, portableClassEscapes); + if (i < 0) return false; + } else { + i++; + } + } + if (i >= pattern.length) return false; + i++; + } else { + i++; + } + } + return true; +} + +const patternExamplePool = + "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~ "; +const patternLiteralEscapes: Record = { + t: "\t", + n: "\n", + r: "\r", + f: "\f", + v: "\v", +}; + +/** + * A deterministic value matching a portable pattern (see isPortablePattern), + * or undefined when none could be built. Alternation takes the first branch, + * repetition produces `repeat` items within the quantifier's bounds, and + * character sets draw from a small printable pool. + */ +function exampleForPortablePattern( + pattern: string, + repeat: number = 3, +): string | undefined { + let i = 0; + let picks = 0; + + const classEnd = (start: number): number => { + let j = start + 1; + if (pattern[j] === "^") j++; + while (j < pattern.length && pattern[j] !== "]") { + j += pattern[j] === "\\" ? (pattern[j + 1] === "x" ? 4 : 2) : 1; + } + return j; + }; + + const parseAtom = (): (() => string) | undefined => { + const c = pattern[i]; + if (c === "^" || c === "$") { + i++; + return () => ""; + } + if (c === "(") { + i += pattern[i + 1] === "?" ? 3 : 1; + const inner = parseAlternation(); + if (inner === undefined || pattern[i] !== ")") return undefined; + i++; + return () => inner; + } + let set: string; + if (c === "[") { + const end = classEnd(i); + set = pattern.slice(i, end + 1); + i = end + 1; + } else if (c === "\\") { + const next = pattern[i + 1] ?? ""; + if (next === "x") { + const ch = String.fromCharCode( + parseInt(pattern.slice(i + 2, i + 4), 16), + ); + i += 4; + return () => ch; + } + i += 2; + if (next === "b" || next === "B") return () => ""; + const literal = patternLiteralEscapes[next]; + if (literal !== undefined) return () => literal; + if (!"dDwW".includes(next)) return () => next; + set = `\\${next}`; + } else if (c === ".") { + set = "."; + i++; + } else { + i++; + return () => c; + } + const setRE = new RegExp(`^${set}$`, "u"); + const choices = patternExamplePool.split("").filter((ch) => setRE.test(ch)); + if (choices.length === 0) return undefined; + return () => choices[picks++ % choices.length]!; + }; + + const parseQuantifier = (): [number, number] => { + let range: [number, number]; + const c = pattern[i]; + if (c === "*") { + range = [0, Infinity]; + i++; + } else if (c === "+") { + range = [1, Infinity]; + i++; + } else if (c === "?") { + range = [0, 1]; + i++; + } else if (c === "{") { + const bound = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(i)); + if (!bound) return [1, 1]; + const min = Number(bound[1]); + const max = + bound[2] === undefined + ? min + : bound[3] === "" + ? Infinity + : Number(bound[3]); + range = [min, max]; + i += bound[0].length; + } else { + return [1, 1]; + } + if (pattern[i] === "?") i++; + return range; + }; + + const parseSequence = (): string | undefined => { + let out = ""; + while (i < pattern.length && pattern[i] !== "|" && pattern[i] !== ")") { + const atom = parseAtom(); + if (!atom) return undefined; + const [min, max] = parseQuantifier(); + const count = Math.min(max, Math.max(min, repeat)); + for (let n = 0; n < count; n++) out += atom(); + } + return out; + }; + + function parseAlternation(): string | undefined { + const first = parseSequence(); + while (first !== undefined && pattern[i] === "|") { + i++; + if (parseSequence() === undefined) return undefined; + } + return first; + } + + let example: string | undefined; + try { + example = parseAlternation(); + } catch { + return undefined; + } + if (example === undefined || i !== pattern.length) return undefined; + return new RegExp(pattern, "u").test(example) ? example : undefined; +} + +/** + * The schema pattern of a string type when it is portable, otherwise "". + * Validations.Pattern is pointer-valued in the AST, so it is coerced to a JS + * string first. + */ +function portableStringPattern(typeDef: TypeDef): string { + const raw = typeDef.Validations?.Pattern; + const pattern = raw == null ? "" : String(raw); + return pattern && isPortablePattern(pattern) ? pattern : ""; +} diff --git a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts index cebf627c4..439f74b6a 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts +++ b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts @@ -160,3 +160,32 @@ export function isPlainObject( return false; } } + +function exceedsMaxLength(value: string, maxLength: number): boolean { + if (value.length <= maxLength) { + return false; + } + let codePoints = 0; + for (const _ of value) { + if (++codePoints > maxLength) { + return true; + } + } + return false; +} + +export function withinMaxLength(maxLength: number): (value: string) => boolean { + return (value) => !exceedsMaxLength(value, maxLength); +} + +// A value over maxLength is rejected by withinMaxLength, so the pattern is not +// run against arbitrarily long input. +export function matchesPattern( + pattern: string, + maxLength?: number, +): (value: string) => boolean { + const re = new RegExp(pattern, "u"); + return (value) => + (maxLength !== undefined && exceedsMaxLength(value, maxLength)) || + re.test(value); +} diff --git a/templates/templates/typescriptv2/includes/types.ts b/templates/templates/typescriptv2/includes/types.ts index f4cb75ae5..ec8d7b6ff 100644 --- a/templates/templates/typescriptv2/includes/types.ts +++ b/templates/templates/typescriptv2/includes/types.ts @@ -83,6 +83,12 @@ function callImportTypesFunc(func: () => string): string { registerTemplateFunc("callImportTypesFunc", callImportTypesFunc); +type PatternConstraint = { + pattern: string; + message?: string; + maxLength?: number; +}; + function toOutbound(options: { usageLocation: string; typeDef: TypeDef; @@ -91,6 +97,7 @@ function toOutbound(options: { defaultValue?: unknown; visited: Set; optional: boolean; + patternConstraint?: PatternConstraint; }): ResolvedTypes { const { usageLocation, @@ -100,6 +107,7 @@ function toOutbound(options: { defaultValue, visited, optional, + patternConstraint, } = options; const rootModel = rootTypeDef.ResolvedModel; @@ -429,6 +437,30 @@ function toOutbound(options: { } let zod = z.string(); + if (patternConstraint) { + const { pattern, message, maxLength } = patternConstraint; + const literal = (s: string) => + JSON.stringify(s).replaceAll("{{", `{{"{{"}}`); + const errorMessage = message || `Value must match pattern ${pattern}`; + if (maxLength !== undefined) { + zod = z.refine( + zod, + `withinMaxLength$(${maxLength})`, + `{ message: ${literal( + `Value must be at most ${maxLength} characters long`, + )} }`, + ); + } + const patternArgs = + maxLength === undefined + ? literal(pattern) + : `${literal(pattern)}, ${maxLength}`; + zod = z.refine( + zod, + `matchesPattern$(${patternArgs})`, + `{ message: ${literal(errorMessage)} }`, + ); + } if (defaultValue != null) { const dv = quote(String(defaultValue)).replaceAll("{{", `{{"{{"}}`); zod = z.default(zod, dv); @@ -440,7 +472,23 @@ function toOutbound(options: { outputType: "string", importOutputTypes: () => "", zod, - importZodTypes: () => addZodPackageImport(), + importZodTypes: () => { + if (patternConstraint) { + addInternalImport( + "primitives", + "matchesPattern as matchesPattern$", + usageLocation, + ); + if (patternConstraint.maxLength !== undefined) { + addInternalImport( + "primitives", + "withinMaxLength as withinMaxLength$", + usageLocation, + ); + } + } + return addZodPackageImport(); + }, }; } case "date": { @@ -1000,6 +1048,7 @@ function resolveOutbound(options: { visited?: Set; constValue?: AnyValue; defaultValue?: AnyValue; + patternConstraint?: PatternConstraint; }): ResolvedTypes { const { usageLocation, @@ -1011,6 +1060,7 @@ function resolveOutbound(options: { visited, constValue, defaultValue, + patternConstraint, } = options; if (usageLocation == null) { @@ -1043,6 +1093,7 @@ function resolveOutbound(options: { defaultValue: defaultValue?.Value, visited: visited || new Set(), optional, + patternConstraint, }); if (streamable) { @@ -1119,6 +1170,65 @@ function resolveOutbound(options: { registerTemplateFunc("resolveOutbound", resolveOutbound); +const patternConstrainedParamTypes = new Set([ + "pathParam", + "queryParam", + "header", +]); + +// Object parameter properties also carry a param annotation, and their model +// can be shared with request bodies, so only the operation's own request model +// is constrained. +function requestParamPatternConstraint( + field: FieldDef, + rootTypeDef: TypeDef, +): PatternConstraint | undefined { + if ( + isNoZod() || + field.Type.Type.toString() !== "string" || + !rootTypeDef.IsRequest() + ) { + return undefined; + } + const ann = field.Annotations.Get("param"); + if ( + ann == null || + !isParamAnnotation(ann) || + !patternConstrainedParamTypes.has(ann.ParamType) + ) { + return undefined; + } + const pattern = portableStringPattern(field.Type); + if (!pattern) { + return undefined; + } + // Pointer-valued in the AST: coerce through Number and skip when unset. + const rawMaxLength = field.Type.Validations?.MaxLength; + const maxLengthValue = rawMaxLength == null ? NaN : Number(rawMaxLength); + const maxLength = + Number.isInteger(maxLengthValue) && maxLengthValue >= 0 + ? maxLengthValue + : undefined; + // zod v3 runs refinements on defaults, so a default that violates its own + // constraints would fail every call that omits the parameter. + const defaultValue = field.Default?.Value; + if (defaultValue != null) { + const value = String(defaultValue); + if ( + (maxLength !== undefined && [...value].length > maxLength) || + !new RegExp(pattern, "u").test(value) + ) { + return undefined; + } + } + const message = field.Type.Extensions?.PatternErrorMessage; + return { + pattern, + message: message ? String(message) : undefined, + maxLength, + }; +} + function toInbound(options: { usageLocation: string; typeDef: TypeDef; diff --git a/templates/templates/typescriptv2/includes/zod-templating-helpers.ts b/templates/templates/typescriptv2/includes/zod-templating-helpers.ts index 392814418..a7509f1d0 100644 --- a/templates/templates/typescriptv2/includes/zod-templating-helpers.ts +++ b/templates/templates/typescriptv2/includes/zod-templating-helpers.ts @@ -31,6 +31,7 @@ const zodTemplating = { streamable: isMultipartFileField(field), constValue: field.Const, defaultValue: field.Default, + patternConstraint: requestParamPatternConstraint(field, rootTypeDef), }); fieldType.importZodTypes(); diff --git a/templates/templates/typescriptv2/tests/lib/primitives.test.ts b/templates/templates/typescriptv2/tests/lib/primitives.test.ts index 719652f42..33c14a42d 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -1,5 +1,40 @@ import { test, expect } from "vitest"; -import { abortSignalAny } from "../../lib/primitives.js"; +import { + abortSignalAny, + matchesPattern, + withinMaxLength, +} from "../../lib/primitives.js"; + +test("matchesPattern tests values against the pattern", () => { + const matches = matchesPattern("^[a-z0-9-]+$"); + + expect(matches("abc-1")).toBe(true); + expect(matches("..")).toBe(false); + expect(matches("ABC")).toBe(false); +}); + +test("matchesPattern uses Unicode mode", () => { + expect(matchesPattern("^.$")("😀")).toBe(true); +}); + +test("withinMaxLength counts code points", () => { + const within = withinMaxLength(2); + + expect(within("ab")).toBe(true); + expect(within("😀😀")).toBe(true); + expect(within("abc")).toBe(false); + expect(withinMaxLength(0)("")).toBe(true); +}); + +test("matchesPattern skips the pattern for values over maxLength", () => { + // Exponential backtracking on a non-matching suffix without the bound. + const matches = matchesPattern("^(a+)+$", 8); + + expect(matches("aaaa")).toBe(true); + expect(matches("aaab")).toBe(false); + + expect(matches(`${"a".repeat(64)}b`)).toBe(true); +}); test("abortSignalAny with one signal", () => { const sig = new AbortController().signal; diff --git a/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts new file mode 100644 index 000000000..7ed45ef54 --- /dev/null +++ b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, test } from "vitest"; + +import { SDK } from "../index.js"; +import { SDKValidationError } from "../sdk/models/errors/sdkvalidationerror.js"; +import { CliPatternMessagesRequest } from "../sdk/models/operations/clipatternmessages.js"; +import { + HTTPBIN_URL, + RequestLogEntry, + newRequestRecorderClient, +} from "./common_helpers.js"; + +function newSDK(log: RequestLogEntry[]): SDK { + return new SDK({ + serverURL: HTTPBIN_URL, + httpClient: newRequestRecorderClient(log), + }); +} + +async function expectRejected( + request: CliPatternMessagesRequest, + message: string, +): Promise { + const log: RequestLogEntry[] = []; + const err = await newSDK(log) + .cliHygiene.cliPatternMessages(request) + .then( + () => undefined, + (e: unknown) => e, + ); + + expect(err).toBeInstanceOf(SDKValidationError); + expect((err as SDKValidationError).pretty()).toContain(message); + expect(log).toHaveLength(0); +} + +describe("request parameter patterns", () => { + test("sends values that match every pattern", async () => { + const log: RequestLogEntry[] = []; + + const res = await newSDK(log).cliHygiene.cliPatternMessages({ + code: "abc-1", + tag: "abc", + xLabel: "abc", + changed: "123", + composed: "abc", + same: "abc", + replaced: "123", + wrapper: "abc", + unionCode: "123", + unionSame: "abc", + slug: "abc", + }); + + expect(res.httpMeta.response.status).toBe(200); + expect(log).toHaveLength(1); + }); + + test("rejects a path parameter before sending the request", async () => { + await expectRejected( + { code: ".." }, + "Use lowercase letters, digits or hyphens.", + ); + }); + + test("rejects a value over maxLength before testing the pattern", async () => { + await expectRejected( + { code: "abcdefg" }, + "Value must be at most 6 characters long", + ); + }); + + test("rejects a query parameter with its custom message", async () => { + await expectRejected( + { code: "abc", tag: "ABC" }, + 'Use "a" through "z" with 100% accuracy; café.', + ); + }); + + test("rejects a header parameter with a multi-line message", async () => { + await expectRejected( + { code: "abc", xLabel: "ABC" }, + 'Use lowercase letters.\nTry "sample".', + ); + }); + + test("uses a default message when none is declared", async () => { + await expectRejected( + { code: "abc", changed: "abc" }, + "Value must match pattern ^[0-9]+$", + ); + }); + + test("rejects a string oneOf parameter against its merged pattern", async () => { + await expectRejected( + { code: "abc", unionCode: "ABC" }, + "Value must match pattern (^[a-z]+$|^[0-9]+$)", + ); + }); + + test("leaves non-portable patterns such as lookaheads to the server", async () => { + const log: RequestLogEntry[] = []; + + const res = await newSDK(log).cliHygiene.cliPatternMessages({ + code: "abc", + slug: "xyz", + }); + + expect(res.httpMeta.response.status).toBe(200); + expect(log).toHaveLength(1); + }); + + test("leaves request body properties unconstrained", async () => { + const log: RequestLogEntry[] = []; + + const res = await newSDK(log).cliHygiene.cliPatternMessages({ + code: "abc", + requestBody: { name: "ABC", fallback: "ABC" }, + }); + + expect(res.httpMeta.response.status).toBe(200); + expect(log).toHaveLength(1); + }); +}); diff --git a/templates/templates/typescriptv2/tests/tertiary/parameter_patterns_additional.test.ts b/templates/templates/typescriptv2/tests/tertiary/parameter_patterns_additional.test.ts new file mode 100644 index 000000000..06c769d19 --- /dev/null +++ b/templates/templates/typescriptv2/tests/tertiary/parameter_patterns_additional.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "vitest"; + +import { SDK } from "../index.js"; +import { SDKValidationError } from "../sdk/models/errors/sdkvalidationerror.js"; +import { + HTTPBIN_URL, + RequestLogEntry, + newRequestRecorderClient, +} from "./common_helpers.js"; + +function newSDK(log: RequestLogEntry[]): SDK { + return new SDK({ + serverURL: HTTPBIN_URL, + httpClient: newRequestRecorderClient(log), + }); +} + +describe("request parameter patterns", () => { + test("rejects a path parameter before sending the request", async () => { + const log: RequestLogEntry[] = []; + + await expect( + newSDK(log).parameterPatterns.parameterPatternsSharedComponent(".."), + ).rejects.toThrow(SDKValidationError); + expect(log).toHaveLength(0); + }); + + test("sends the default of an omitted patterned parameter", async () => { + const log: RequestLogEntry[] = []; + + await newSDK(log).parameterPatterns.parameterPatternsSharedComponent( + "store_1", + ); + + expect(log).toHaveLength(1); + expect(new URL(log[0]!.url).searchParams.get("sort")).toBe("name"); + }); + + test("leaves properties of an object parameter shared with the body unconstrained", async () => { + const log: RequestLogEntry[] = []; + + await newSDK(log).parameterPatterns.parameterPatternsSharedComponent( + "store_1", + { name: "ABC" }, + undefined, + { name: "ABC" }, + ); + + expect(log).toHaveLength(1); + }); +}); diff --git a/tests/specs/fragments/tertiary/parameter-pattern-validation.yaml b/tests/specs/fragments/tertiary/parameter-pattern-validation.yaml new file mode 100644 index 000000000..d1f2e7f52 --- /dev/null +++ b/tests/specs/fragments/tertiary/parameter-pattern-validation.yaml @@ -0,0 +1,64 @@ +openapi: 3.1.0 +security: + - apiKeyAuth: [] + - oauth2: [] + - clientCredentials: [read, write] + - customSchemeAppId: [] + - basicHttp: [] + - accessToken: [] + - {} +paths: + /anything/parameterPatterns/{storeId}: + post: + operationId: parameterPatternsSharedComponent + description: >- + A path parameter with a pattern and no example, a query parameter with + a pattern and a matching default, and an object schema used both as a + deepObject query parameter and as the JSON request body. The pattern + on the object's property constrains neither usage on the client, so + the same value is accepted in both places. + tags: + - parameterPatterns + parameters: + - name: storeId + in: path + required: true + schema: + type: string + pattern: '^[a-z0-9_]+$' + - name: sort + in: query + schema: + type: string + pattern: '^[a-z]+$' + default: name + - name: filter + in: query + style: deepObject + explode: true + schema: + $ref: '#/components/schemas/PatternFilter' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatternFilter' + responses: + '200': + description: OK + content: + application/json: + schema: + type: object + properties: + url: + type: string +components: + schemas: + PatternFilter: + description: An object schema whose string property declares a pattern. + type: object + properties: + name: + type: string + pattern: '^[a-z]+$' diff --git a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock index 4f9626f9a..39e0ebcf5 100644 --- a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock +++ b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock @@ -1083,7 +1083,7 @@ trackedFiles: src/lib/oauth2-sessions.ts: last_write_checksum: sha1:cd3c9512e03ef6d854e49d5ba3f8a64cdbe6d1f7 src/lib/primitives.ts: - last_write_checksum: sha1:fe3abb7d6b61596e346873519bcec9b2eaa61467 + last_write_checksum: sha1:20a7b0c3258527ae6fbda31c647fb71f22cecf70 src/lib/retries.ts: last_write_checksum: sha1:42c8f6cc4c875be236230a8c760f4f32d8c1ab68 src/lib/schemas.ts: diff --git a/zSDKs/sdk-typescriptv2/src/lib/primitives.ts b/zSDKs/sdk-typescriptv2/src/lib/primitives.ts index 8ce65db0f..e7b759088 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/primitives.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/primitives.ts @@ -164,3 +164,32 @@ export function isPlainObject( return false; } } + +function exceedsMaxLength(value: string, maxLength: number): boolean { + if (value.length <= maxLength) { + return false; + } + let codePoints = 0; + for (const _ of value) { + if (++codePoints > maxLength) { + return true; + } + } + return false; +} + +export function withinMaxLength(maxLength: number): (value: string) => boolean { + return (value) => !exceedsMaxLength(value, maxLength); +} + +// A value over maxLength is rejected by withinMaxLength, so the pattern is not +// run against arbitrarily long input. +export function matchesPattern( + pattern: string, + maxLength?: number, +): (value: string) => boolean { + const re = new RegExp(pattern, "u"); + return (value) => + (maxLength !== undefined && exceedsMaxLength(value, maxLength)) || + re.test(value); +}