From 2863c152ed9c76edb28f4c5a4e68b67bbd92ec34 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Thu, 12 Nov 2026 16:17:25 +1000 Subject: [PATCH 1/6] feat(typescript): validate request parameters against schema patterns --- .changesets/1794464217-f98ed08b.yaml | 10 ++ templates/perms.go | 1 + .../auxiliary/src/lib/primitives.ts | 15 +++ .../templates/typescriptv2/includes/types.ts | 59 +++++++++++- .../includes/zod-templating-helpers.ts | 1 + .../typescriptv2/tests/lib/primitives.test.ts | 26 ++++- .../parameter_patterns_additional.test.ts | 96 +++++++++++++++++++ zSDKs/sdk-typescriptv2/.speakeasy/gen.lock | 2 +- zSDKs/sdk-typescriptv2/src/lib/primitives.ts | 15 +++ 9 files changed, 222 insertions(+), 3 deletions(-) create mode 100644 .changesets/1794464217-f98ed08b.yaml create mode 100644 templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts diff --git a/.changesets/1794464217-f98ed08b.yaml b/.changesets/1794464217-f98ed08b.yaml new file mode 100644 index 000000000..e149983aa --- /dev/null +++ b/.changesets/1794464217-f98ed08b.yaml @@ -0,0 +1,10 @@ +id: 1794464217-f98ed08b +features: + - core +targets: + - typescriptv2 +type: feat +bump: patch +description: validate request parameter values against schema patterns +author: TristanSpeakEasy +date: "2026-11-12" diff --git a/templates/perms.go b/templates/perms.go index c36b512cd..c16645c64 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -2461,6 +2461,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, diff --git a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts index cebf627c4..a953915a4 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts +++ b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts @@ -160,3 +160,18 @@ export function isPlainObject( return false; } } + +// A pattern that this runtime cannot compile is left for the server to enforce. +export function matchesPattern(pattern: string): (value: string) => boolean { + let re: RegExp; + try { + re = new RegExp(pattern, "u"); + } catch { + try { + re = new RegExp(pattern); + } catch { + return () => true; + } + } + return (value) => re.test(value); +} diff --git a/templates/templates/typescriptv2/includes/types.ts b/templates/templates/typescriptv2/includes/types.ts index f4cb75ae5..6a888b0f5 100644 --- a/templates/templates/typescriptv2/includes/types.ts +++ b/templates/templates/typescriptv2/includes/types.ts @@ -83,6 +83,8 @@ function callImportTypesFunc(func: () => string): string { registerTemplateFunc("callImportTypesFunc", callImportTypesFunc); +type PatternConstraint = { pattern: string; message?: string }; + function toOutbound(options: { usageLocation: string; typeDef: TypeDef; @@ -91,6 +93,7 @@ function toOutbound(options: { defaultValue?: unknown; visited: Set; optional: boolean; + patternConstraint?: PatternConstraint; }): ResolvedTypes { const { usageLocation, @@ -100,6 +103,7 @@ function toOutbound(options: { defaultValue, visited, optional, + patternConstraint, } = options; const rootModel = rootTypeDef.ResolvedModel; @@ -429,6 +433,17 @@ function toOutbound(options: { } let zod = z.string(); + if (patternConstraint) { + const { pattern, message } = patternConstraint; + const literal = (s: string) => + JSON.stringify(s).replaceAll("{{", `{{"{{"}}`); + const errorMessage = message || `Value must match pattern ${pattern}`; + zod = z.refine( + zod, + `matchesPattern$(${literal(pattern)})`, + `{ message: ${literal(errorMessage)} }`, + ); + } if (defaultValue != null) { const dv = quote(String(defaultValue)).replaceAll("{{", `{{"{{"}}`); zod = z.default(zod, dv); @@ -440,7 +455,16 @@ function toOutbound(options: { outputType: "string", importOutputTypes: () => "", zod, - importZodTypes: () => addZodPackageImport(), + importZodTypes: () => { + if (patternConstraint) { + addInternalImport( + "primitives", + "matchesPattern as matchesPattern$", + usageLocation, + ); + } + return addZodPackageImport(); + }, }; } case "date": { @@ -1000,6 +1024,7 @@ function resolveOutbound(options: { visited?: Set; constValue?: AnyValue; defaultValue?: AnyValue; + patternConstraint?: PatternConstraint; }): ResolvedTypes { const { usageLocation, @@ -1011,6 +1036,7 @@ function resolveOutbound(options: { visited, constValue, defaultValue, + patternConstraint, } = options; if (usageLocation == null) { @@ -1043,6 +1069,7 @@ function resolveOutbound(options: { defaultValue: defaultValue?.Value, visited: visited || new Set(), optional, + patternConstraint, }); if (streamable) { @@ -1119,6 +1146,36 @@ function resolveOutbound(options: { registerTemplateFunc("resolveOutbound", resolveOutbound); +const patternConstrainedParamTypes = new Set([ + "pathParam", + "queryParam", + "header", +]); + +function requestParamPatternConstraint( + field: FieldDef, +): PatternConstraint | undefined { + if (isNoZod() || field.Type.Type.toString() !== "string") { + return undefined; + } + const ann = field.Annotations.Get("param"); + if ( + ann == null || + !isParamAnnotation(ann) || + !patternConstrainedParamTypes.has(ann.ParamType) + ) { + return undefined; + } + // Pointer-valued in the AST: coerce to a JS string and skip when unset. + const raw = field.Type.Validations?.Pattern; + const pattern = raw == null ? "" : String(raw); + if (!pattern) { + return undefined; + } + const message = field.Type.Extensions?.PatternErrorMessage; + return { pattern, message: message ? String(message) : undefined }; +} + 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..e70278d83 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), }); fieldType.importZodTypes(); diff --git a/templates/templates/typescriptv2/tests/lib/primitives.test.ts b/templates/templates/typescriptv2/tests/lib/primitives.test.ts index 719652f42..365cbea71 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -1,5 +1,29 @@ import { test, expect } from "vitest"; -import { abortSignalAny } from "../../lib/primitives.js"; +import { abortSignalAny, matchesPattern } 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 when the pattern allows it", () => { + expect(matchesPattern("^.$")("😀")).toBe(true); +}); + +test("matchesPattern falls back to legacy mode", () => { + // A class range from an escape is only a syntax error in Unicode mode. + const matches = matchesPattern("^[\\w-]+$"); + + expect(matches("a_b-c")).toBe(true); + expect(matches("a b")).toBe(false); +}); + +test("matchesPattern accepts every value for an uncompilable pattern", () => { + expect(matchesPattern("(?i)abc")("anything")).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..13957f3f7 --- /dev/null +++ b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts @@ -0,0 +1,96 @@ +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", + unionCode: "123", + 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 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("enforces ECMAScript-only syntax such as lookaheads", async () => { + await expectRejected({ code: "abc", slug: "xyz" }, "Avoid the x prefix."); + }); + + 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/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock index 4f9626f9a..f115ecfa4 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:a7a84c5c53c1c72b6779dcf8dfb41bec63e6d9fc 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..021994418 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/primitives.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/primitives.ts @@ -164,3 +164,18 @@ export function isPlainObject( return false; } } + +// A pattern that this runtime cannot compile is left for the server to enforce. +export function matchesPattern(pattern: string): (value: string) => boolean { + let re: RegExp; + try { + re = new RegExp(pattern, "u"); + } catch { + try { + re = new RegExp(pattern); + } catch { + return () => true; + } + } + return (value) => re.test(value); +} From 4120c2f9ecf7acf4f29db8ee11f5c3f3509bf3a5 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Thu, 12 Nov 2026 16:32:54 +1000 Subject: [PATCH 2/6] test(typescript): cover the legacy regex fallback and every patterned parameter --- .../typescriptv2/tests/lib/primitives.test.ts | 2 +- .../primary/parameter_patterns_additional.test.ts | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/templates/templates/typescriptv2/tests/lib/primitives.test.ts b/templates/templates/typescriptv2/tests/lib/primitives.test.ts index 365cbea71..62a72d0a7 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -15,7 +15,7 @@ test("matchesPattern uses Unicode mode when the pattern allows it", () => { test("matchesPattern falls back to legacy mode", () => { // A class range from an escape is only a syntax error in Unicode mode. - const matches = matchesPattern("^[\\w-]+$"); + const matches = matchesPattern("^[\\w-a]+$"); expect(matches("a_b-c")).toBe(true); expect(matches("a b")).toBe(false); diff --git a/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts index 13957f3f7..96ada0d2a 100644 --- a/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts +++ b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts @@ -42,7 +42,12 @@ describe("request parameter patterns", () => { tag: "abc", xLabel: "abc", changed: "123", + composed: "abc", + same: "abc", + replaced: "123", + wrapper: "abc", unionCode: "123", + unionSame: "abc", slug: "abc", }); @@ -78,6 +83,13 @@ describe("request parameter patterns", () => { ); }); + 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("enforces ECMAScript-only syntax such as lookaheads", async () => { await expectRejected({ code: "abc", slug: "xyz" }, "Avoid the x prefix."); }); From 61b59536e79ee93c2a5e749119cb87212ba9df70 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Fri, 13 Nov 2026 09:32:47 +1000 Subject: [PATCH 3/6] fix(typescript): only enforce portable patterns on operation parameters and generate matching examples --- .changesets/1794464217-f98ed08b.yaml | 2 +- templates/perms.go | 2 + templates/templates/cli/includes/metadata.ts | 74 ---------------- templates/templates/common/common/examples.ts | 40 +++++++++ templates/templates/common/common/patterns.ts | 84 +++++++++++++++++++ .../auxiliary/src/lib/primitives.ts | 12 +-- .../templates/typescriptv2/includes/types.ts | 23 ++++- .../includes/zod-templating-helpers.ts | 2 +- .../typescriptv2/tests/lib/primitives.test.ts | 14 +--- .../parameter_patterns_additional.test.ts | 12 ++- .../parameter_patterns_additional.test.ts | 51 +++++++++++ .../parameter-pattern-validation.yaml | 64 ++++++++++++++ zSDKs/sdk-typescriptv2/.speakeasy/gen.lock | 2 +- zSDKs/sdk-typescriptv2/src/lib/primitives.ts | 12 +-- 14 files changed, 276 insertions(+), 118 deletions(-) create mode 100644 templates/templates/common/common/patterns.ts create mode 100644 templates/templates/typescriptv2/tests/tertiary/parameter_patterns_additional.test.ts create mode 100644 tests/specs/fragments/tertiary/parameter-pattern-validation.yaml diff --git a/.changesets/1794464217-f98ed08b.yaml b/.changesets/1794464217-f98ed08b.yaml index e149983aa..e8663572f 100644 --- a/.changesets/1794464217-f98ed08b.yaml +++ b/.changesets/1794464217-f98ed08b.yaml @@ -5,6 +5,6 @@ targets: - typescriptv2 type: feat bump: patch -description: validate request parameter values against schema patterns +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 c16645c64..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, @@ -2501,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..702564adc 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,44 @@ 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 re = new RegExp(pattern, "u"); + if (re.test(value)) { + return value; + } + // fromRegExp treats anchors as literal characters. + let body = pattern.startsWith("^") ? pattern.slice(1) : pattern; + if (body.endsWith("$") && !body.endsWith("\\$")) { + body = body.slice(0, -1); + } + for (let attempt = 0; attempt < 5; attempt++) { + let candidate: string; + try { + candidate = faker.helpers.fromRegExp(body); + } catch { + return value; + } + if (re.test(candidate)) { + return candidate; + } + } + 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..7c039b021 --- /dev/null +++ b/templates/templates/common/common/patterns.ts @@ -0,0 +1,84 @@ +// 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; +} + +/** + * 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 a953915a4..934dbfd3e 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts +++ b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts @@ -161,17 +161,7 @@ export function isPlainObject( } } -// A pattern that this runtime cannot compile is left for the server to enforce. export function matchesPattern(pattern: string): (value: string) => boolean { - let re: RegExp; - try { - re = new RegExp(pattern, "u"); - } catch { - try { - re = new RegExp(pattern); - } catch { - return () => true; - } - } + const re = new RegExp(pattern, "u"); return (value) => re.test(value); } diff --git a/templates/templates/typescriptv2/includes/types.ts b/templates/templates/typescriptv2/includes/types.ts index 6a888b0f5..3fc01f279 100644 --- a/templates/templates/typescriptv2/includes/types.ts +++ b/templates/templates/typescriptv2/includes/types.ts @@ -1152,10 +1152,18 @@ const patternConstrainedParamTypes = new Set([ "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") { + if ( + isNoZod() || + field.Type.Type.toString() !== "string" || + !rootTypeDef.IsRequest() + ) { return undefined; } const ann = field.Annotations.Get("param"); @@ -1166,12 +1174,19 @@ function requestParamPatternConstraint( ) { return undefined; } - // Pointer-valued in the AST: coerce to a JS string and skip when unset. - const raw = field.Type.Validations?.Pattern; - const pattern = raw == null ? "" : String(raw); + const pattern = portableStringPattern(field.Type); if (!pattern) { return undefined; } + // zod v3 runs refinements on defaults, so a default that violates its own + // pattern would fail every call that omits the parameter. + const defaultValue = field.Default?.Value; + if ( + defaultValue != null && + !new RegExp(pattern, "u").test(String(defaultValue)) + ) { + return undefined; + } const message = field.Type.Extensions?.PatternErrorMessage; return { pattern, message: message ? String(message) : undefined }; } diff --git a/templates/templates/typescriptv2/includes/zod-templating-helpers.ts b/templates/templates/typescriptv2/includes/zod-templating-helpers.ts index e70278d83..a7509f1d0 100644 --- a/templates/templates/typescriptv2/includes/zod-templating-helpers.ts +++ b/templates/templates/typescriptv2/includes/zod-templating-helpers.ts @@ -31,7 +31,7 @@ const zodTemplating = { streamable: isMultipartFileField(field), constValue: field.Const, defaultValue: field.Default, - patternConstraint: requestParamPatternConstraint(field), + 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 62a72d0a7..736cb8c11 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -9,22 +9,10 @@ test("matchesPattern tests values against the pattern", () => { expect(matches("ABC")).toBe(false); }); -test("matchesPattern uses Unicode mode when the pattern allows it", () => { +test("matchesPattern uses Unicode mode", () => { expect(matchesPattern("^.$")("😀")).toBe(true); }); -test("matchesPattern falls back to legacy mode", () => { - // A class range from an escape is only a syntax error in Unicode mode. - const matches = matchesPattern("^[\\w-a]+$"); - - expect(matches("a_b-c")).toBe(true); - expect(matches("a b")).toBe(false); -}); - -test("matchesPattern accepts every value for an uncompilable pattern", () => { - expect(matchesPattern("(?i)abc")("anything")).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 index 96ada0d2a..f332d0ce9 100644 --- a/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts +++ b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts @@ -90,8 +90,16 @@ describe("request parameter patterns", () => { ); }); - test("enforces ECMAScript-only syntax such as lookaheads", async () => { - await expectRejected({ code: "abc", slug: "xyz" }, "Avoid the x prefix."); + 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 () => { 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 f115ecfa4..01f6ec6d5 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:a7a84c5c53c1c72b6779dcf8dfb41bec63e6d9fc + last_write_checksum: sha1:e474032285b35387e88e86b78547dadae9b8cdc3 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 021994418..b6a7c414d 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/primitives.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/primitives.ts @@ -165,17 +165,7 @@ export function isPlainObject( } } -// A pattern that this runtime cannot compile is left for the server to enforce. export function matchesPattern(pattern: string): (value: string) => boolean { - let re: RegExp; - try { - re = new RegExp(pattern, "u"); - } catch { - try { - re = new RegExp(pattern); - } catch { - return () => true; - } - } + const re = new RegExp(pattern, "u"); return (value) => re.test(value); } From 0a22c50f2caa91247ab314c315fc61dbdfbda144 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Fri, 13 Nov 2026 09:47:47 +1000 Subject: [PATCH 4/6] fix(typescript): generate pattern examples for the full portable subset --- templates/templates/common/common/examples.ts | 21 +-- templates/templates/common/common/patterns.ts | 137 ++++++++++++++++++ 2 files changed, 139 insertions(+), 19 deletions(-) diff --git a/templates/templates/common/common/examples.ts b/templates/templates/common/common/examples.ts index 702564adc..078cb3c87 100644 --- a/templates/templates/common/common/examples.ts +++ b/templates/templates/common/common/examples.ts @@ -2011,27 +2011,10 @@ function conformExampleToPattern(fieldDef: FieldDef, value: string): string { if (!pattern) { return value; } - const re = new RegExp(pattern, "u"); - if (re.test(value)) { + if (new RegExp(pattern, "u").test(value)) { return value; } - // fromRegExp treats anchors as literal characters. - let body = pattern.startsWith("^") ? pattern.slice(1) : pattern; - if (body.endsWith("$") && !body.endsWith("\\$")) { - body = body.slice(0, -1); - } - for (let attempt = 0; attempt < 5; attempt++) { - let candidate: string; - try { - candidate = faker.helpers.fromRegExp(body); - } catch { - return value; - } - if (re.test(candidate)) { - return candidate; - } - } - return value; + return exampleForPortablePattern(pattern) ?? value; } function templatePlaceholderString(arrayIdx?: number) { diff --git a/templates/templates/common/common/patterns.ts b/templates/templates/common/common/patterns.ts index 7c039b021..c46f6a669 100644 --- a/templates/templates/common/common/patterns.ts +++ b/templates/templates/common/common/patterns.ts @@ -72,6 +72,143 @@ function isPortablePattern(pattern: string): boolean { 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, + * unbounded repetition produces three items, and character sets draw from a + * small printable pool. + */ +function exampleForPortablePattern(pattern: string): 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, 3)); + 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 From 3824f15dfff1516fda2bc232aac0d1dae4108636 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Mon, 16 Nov 2026 14:26:33 +1000 Subject: [PATCH 5/6] fix(typescript): bound parameter pattern checks by maxLength --- templates/templates/common/common/examples.ts | 13 ++++- templates/templates/common/common/patterns.ts | 11 ++-- .../auxiliary/src/lib/primitives.ts | 28 ++++++++- .../templates/typescriptv2/includes/types.ts | 58 +++++++++++++++---- .../typescriptv2/tests/lib/primitives.test.ts | 27 ++++++++- .../parameter_patterns_additional.test.ts | 7 +++ zSDKs/sdk-typescriptv2/.speakeasy/gen.lock | 2 +- zSDKs/sdk-typescriptv2/src/lib/primitives.ts | 28 ++++++++- 8 files changed, 152 insertions(+), 22 deletions(-) diff --git a/templates/templates/common/common/examples.ts b/templates/templates/common/common/examples.ts index 078cb3c87..3d52cf520 100644 --- a/templates/templates/common/common/examples.ts +++ b/templates/templates/common/common/examples.ts @@ -2011,10 +2011,19 @@ function conformExampleToPattern(fieldDef: FieldDef, value: string): string { if (!pattern) { return value; } - if (new RegExp(pattern, "u").test(value)) { + const rawMaxLength = fieldDef.Type.Validations?.MaxLength; + const maxLength = rawMaxLength == null ? Infinity : Number(rawMaxLength); + const fits = (s: string) => [...s].length <= maxLength; + if (new RegExp(pattern, "u").test(value) && fits(value)) { return value; } - return exampleForPortablePattern(pattern) ?? 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) { diff --git a/templates/templates/common/common/patterns.ts b/templates/templates/common/common/patterns.ts index c46f6a669..343d32b8e 100644 --- a/templates/templates/common/common/patterns.ts +++ b/templates/templates/common/common/patterns.ts @@ -85,10 +85,13 @@ const patternLiteralEscapes: Record = { /** * A deterministic value matching a portable pattern (see isPortablePattern), * or undefined when none could be built. Alternation takes the first branch, - * unbounded repetition produces three items, and character sets draw from a - * small printable pool. + * repetition produces `repeat` items within the quantifier's bounds, and + * character sets draw from a small printable pool. */ -function exampleForPortablePattern(pattern: string): string | undefined { +function exampleForPortablePattern( + pattern: string, + repeat: number = 3, +): string | undefined { let i = 0; let picks = 0; @@ -184,7 +187,7 @@ function exampleForPortablePattern(pattern: string): string | undefined { const atom = parseAtom(); if (!atom) return undefined; const [min, max] = parseQuantifier(); - const count = Math.min(max, Math.max(min, 3)); + const count = Math.min(max, Math.max(min, repeat)); for (let n = 0; n < count; n++) out += atom(); } return out; diff --git a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts index 934dbfd3e..439f74b6a 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts +++ b/templates/templates/typescriptv2/auxiliary/src/lib/primitives.ts @@ -161,7 +161,31 @@ export function isPlainObject( } } -export function matchesPattern(pattern: string): (value: string) => boolean { +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) => re.test(value); + 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 3fc01f279..03803913a 100644 --- a/templates/templates/typescriptv2/includes/types.ts +++ b/templates/templates/typescriptv2/includes/types.ts @@ -83,7 +83,11 @@ function callImportTypesFunc(func: () => string): string { registerTemplateFunc("callImportTypesFunc", callImportTypesFunc); -type PatternConstraint = { pattern: string; message?: string }; +type PatternConstraint = { + pattern: string; + message?: string; + maxLength?: number; +}; function toOutbound(options: { usageLocation: string; @@ -434,13 +438,26 @@ function toOutbound(options: { let zod = z.string(); if (patternConstraint) { - const { pattern, message } = 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$(${literal(pattern)})`, + `matchesPattern$(${patternArgs})`, `{ message: ${literal(errorMessage)} }`, ); } @@ -462,6 +479,13 @@ function toOutbound(options: { "matchesPattern as matchesPattern$", usageLocation, ); + if (patternConstraint.maxLength !== undefined) { + addInternalImport( + "primitives", + "withinMaxLength as withinMaxLength$", + usageLocation, + ); + } } return addZodPackageImport(); }, @@ -1178,17 +1202,31 @@ function requestParamPatternConstraint( 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 - // pattern would fail every call that omits the parameter. + // constraints would fail every call that omits the parameter. const defaultValue = field.Default?.Value; - if ( - defaultValue != null && - !new RegExp(pattern, "u").test(String(defaultValue)) - ) { - return undefined; + if (defaultValue != null) { + const value = String(defaultValue); + if ( + !new RegExp(pattern, "u").test(value) || + (maxLength !== undefined && [...value].length > maxLength) + ) { + return undefined; + } } const message = field.Type.Extensions?.PatternErrorMessage; - return { pattern, message: message ? String(message) : undefined }; + return { + pattern, + message: message ? String(message) : undefined, + maxLength, + }; } function toInbound(options: { diff --git a/templates/templates/typescriptv2/tests/lib/primitives.test.ts b/templates/templates/typescriptv2/tests/lib/primitives.test.ts index 736cb8c11..9145312dc 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -1,5 +1,9 @@ import { test, expect } from "vitest"; -import { abortSignalAny, matchesPattern } 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-]+$"); @@ -13,6 +17,27 @@ 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); + + const start = Date.now(); + expect(matches(`${"a".repeat(64)}b`)).toBe(true); + expect(Date.now() - start).toBeLessThan(100); +}); + 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 index f332d0ce9..7ed45ef54 100644 --- a/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts +++ b/templates/templates/typescriptv2/tests/primary/parameter_patterns_additional.test.ts @@ -62,6 +62,13 @@ describe("request parameter patterns", () => { ); }); + 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" }, diff --git a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock index 01f6ec6d5..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:e474032285b35387e88e86b78547dadae9b8cdc3 + 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 b6a7c414d..e7b759088 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/primitives.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/primitives.ts @@ -165,7 +165,31 @@ export function isPlainObject( } } -export function matchesPattern(pattern: string): (value: string) => boolean { +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) => re.test(value); + return (value) => + (maxLength !== undefined && exceedsMaxLength(value, maxLength)) || + re.test(value); } From 15166b1bd8f0caf0c2c307ea95b68a1afe16bd3b Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Mon, 16 Nov 2026 15:28:32 +1000 Subject: [PATCH 6/6] fix(typescript): check maxLength before pattern for defaults and examples --- templates/templates/common/common/examples.ts | 2 +- templates/templates/typescriptv2/includes/types.ts | 4 ++-- templates/templates/typescriptv2/tests/lib/primitives.test.ts | 2 -- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/templates/templates/common/common/examples.ts b/templates/templates/common/common/examples.ts index 3d52cf520..bac0d9a93 100644 --- a/templates/templates/common/common/examples.ts +++ b/templates/templates/common/common/examples.ts @@ -2014,7 +2014,7 @@ function conformExampleToPattern(fieldDef: FieldDef, value: string): string { const rawMaxLength = fieldDef.Type.Validations?.MaxLength; const maxLength = rawMaxLength == null ? Infinity : Number(rawMaxLength); const fits = (s: string) => [...s].length <= maxLength; - if (new RegExp(pattern, "u").test(value) && fits(value)) { + if (fits(value) && new RegExp(pattern, "u").test(value)) { return value; } for (const repeat of [3, 1, 0]) { diff --git a/templates/templates/typescriptv2/includes/types.ts b/templates/templates/typescriptv2/includes/types.ts index 03803913a..ec8d7b6ff 100644 --- a/templates/templates/typescriptv2/includes/types.ts +++ b/templates/templates/typescriptv2/includes/types.ts @@ -1215,8 +1215,8 @@ function requestParamPatternConstraint( if (defaultValue != null) { const value = String(defaultValue); if ( - !new RegExp(pattern, "u").test(value) || - (maxLength !== undefined && [...value].length > maxLength) + (maxLength !== undefined && [...value].length > maxLength) || + !new RegExp(pattern, "u").test(value) ) { return undefined; } diff --git a/templates/templates/typescriptv2/tests/lib/primitives.test.ts b/templates/templates/typescriptv2/tests/lib/primitives.test.ts index 9145312dc..33c14a42d 100644 --- a/templates/templates/typescriptv2/tests/lib/primitives.test.ts +++ b/templates/templates/typescriptv2/tests/lib/primitives.test.ts @@ -33,9 +33,7 @@ test("matchesPattern skips the pattern for values over maxLength", () => { expect(matches("aaaa")).toBe(true); expect(matches("aaab")).toBe(false); - const start = Date.now(); expect(matches(`${"a".repeat(64)}b`)).toBe(true); - expect(Date.now() - start).toBeLessThan(100); }); test("abortSignalAny with one signal", () => {