Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(api): propagate deprecations to generated SDKs (#16673)

Hassieb Pakzad99e2ce926171
diff --git a/.github/workflows/sdk-api-spec.yml b/.github/workflows/sdk-api-spec.yml
index 472f49719d..08e5ee1920 100644
--- a/.github/workflows/sdk-api-spec.yml
+++ b/.github/workflows/sdk-api-spec.yml
@@ -5,7 +5,10 @@ on:
branches:
- main
paths:
+ - ".github/workflows/sdk-api-spec.yml"
- "fern/**"
+ - "web/scripts/python-sdk/patch-generated-deprecations.ts"
+ - "web/scripts/typescript-sdk/patch-generated-deprecations.ts"
workflow_dispatch:
concurrency:
@@ -50,6 +53,20 @@ jobs:
FERN_TOKEN: ${{ secrets.FERN_TOKEN }}
run: npx fern-api generate --api server --force
+ - name: Add Python SDK deprecation warnings
+ working-directory: web
+ run: >-
+ pnpm exec tsx scripts/python-sdk/patch-generated-deprecations.ts
+ --definition-root ../fern/apis/server/definition
+ --api-root ../generated/python
+
+ - name: Add TypeScript SDK deprecation warnings
+ working-directory: web
+ run: >-
+ pnpm exec tsx scripts/typescript-sdk/patch-generated-deprecations.ts
+ --definition-root ../fern/apis/server/definition
+ --api-root ../generated/typescript
+
- name: Install uv
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
@@ -75,7 +92,12 @@ jobs:
# (could not find the right option to prevent this in generation step)
rm -rf langfuse/api/tests
- # Install dependencies, preserve backwards-compatible score creation aliases, and format
+ # Declare the PEP 702 decorator dependency when the SDK does not
+ # already own a constraint, then install dependencies, preserve
+ # backwards-compatible score creation aliases, and format.
+ if ! sed -n '/^dependencies = \[/,/^\]/p' pyproject.toml | grep -Eqi '^[[:space:]]*"typing[-_.]extensions([<>=!~;@[:space:]]|")'; then
+ uv add --no-sync "typing-extensions>=4.12.2,<5"
+ fi
uv sync --all-extras --frozen
uv run python scripts/patch_generated_score_compat.py
uv run ruff format langfuse/api
diff --git a/web/scripts/python-sdk/patch-generated-deprecations.ts b/web/scripts/python-sdk/patch-generated-deprecations.ts
new file mode 100644
index 0000000000..8f046c7e08
--- /dev/null
+++ b/web/scripts/python-sdk/patch-generated-deprecations.ts
@@ -0,0 +1,307 @@
+import fs from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+import { fileURLToPath } from "node:url";
+import { parse } from "yaml";
+
+type FernAvailability =
+ | string
+ | {
+ status?: string;
+ message?: string;
+ };
+
+type FernDefinition = {
+ service?: {
+ endpoints?: Record<
+ string,
+ {
+ availability?: FernAvailability;
+ }
+ >;
+ };
+};
+
+export type FernPythonDeprecation = {
+ definitionPath: string;
+ endpointName: string;
+ resourcePath: string;
+ methodName: string;
+ message: string;
+};
+
+type PatchOptions = {
+ definitionDirectory: string;
+ apiRoot: string;
+};
+
+type PatchResult = {
+ changedFiles: number;
+ decoratedMethods: number;
+};
+
+function listYamlFiles(directory: string): string[] {
+ return fs
+ .readdirSync(directory, { withFileTypes: true })
+ .flatMap((entry) => {
+ const entryPath = path.join(directory, entry.name);
+
+ if (entry.isDirectory()) return listYamlFiles(entryPath);
+ if (entry.isFile() && /\.ya?ml$/.test(entry.name)) return [entryPath];
+ return [];
+ })
+ .sort();
+}
+
+function toSnakeCase(value: string): string {
+ return value
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
+ .replace(/([a-z\d])([A-Z])/g, "$1_$2")
+ .replace(/[^a-zA-Z\d]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .toLowerCase();
+}
+
+function isDeprecated(availability: FernAvailability | undefined): boolean {
+ return (
+ availability === "deprecated" ||
+ (typeof availability === "object" && availability.status === "deprecated")
+ );
+}
+
+function readDeprecationMessage(
+ availability: FernAvailability | undefined,
+): string {
+ if (
+ typeof availability !== "object" ||
+ typeof availability.message !== "string"
+ ) {
+ return "";
+ }
+
+ return availability.message.trim();
+}
+
+function generatedResourcePath(
+ definitionDirectory: string,
+ definitionPath: string,
+): string {
+ const relativePath = path.relative(definitionDirectory, definitionPath);
+ const parsedPath = path.parse(relativePath);
+ const segments = [
+ ...parsedPath.dir.split(path.sep).filter(Boolean),
+ parsedPath.name,
+ ];
+
+ return path.join(...segments.map(toSnakeCase));
+}
+
+export function getFernPythonDeprecations(
+ definitionDirectory: string,
+): FernPythonDeprecation[] {
+ const deprecations = listYamlFiles(definitionDirectory).flatMap(
+ (definitionPath) => {
+ const definition = parse(
+ fs.readFileSync(definitionPath, "utf8"),
+ ) as FernDefinition;
+ const endpoints = definition.service?.endpoints;
+
+ if (!endpoints) return [];
+
+ return Object.entries(endpoints).flatMap(
+ ([endpointName, endpoint]): FernPythonDeprecation[] => {
+ if (!isDeprecated(endpoint.availability)) return [];
+
+ const message = readDeprecationMessage(endpoint.availability);
+ if (!message) {
+ throw new Error(
+ `Deprecated endpoint "${endpointName}" in ${definitionPath} must define availability.message`,
+ );
+ }
+
+ return [
+ {
+ definitionPath,
+ endpointName,
+ resourcePath: generatedResourcePath(
+ definitionDirectory,
+ definitionPath,
+ ),
+ methodName: toSnakeCase(endpointName),
+ message,
+ },
+ ];
+ },
+ );
+ },
+ );
+
+ const seenMethods = new Set<string>();
+ for (const deprecation of deprecations) {
+ const key = `${deprecation.resourcePath}:${deprecation.methodName}`;
+ if (seenMethods.has(key)) {
+ throw new Error(
+ `Multiple Fern endpoint deprecations resolve to generated Python method ${key}`,
+ );
+ }
+ seenMethods.add(key);
+ }
+
+ return deprecations;
+}
+
+function pythonStringLiteral(value: string): string {
+ // JSON string literals use the same escaping for quotes, backslashes, and
+ // control characters as Python double-quoted strings.
+ return JSON.stringify(value);
+}
+
+function patchMethodPair(
+ contents: string,
+ deprecation: FernPythonDeprecation,
+ clientPath: string,
+): { contents: string; decoratedMethods: number } {
+ const matches = [
+ ...contents.matchAll(/^ (async )?def ([a-zA-Z_]\w*)\(/gm),
+ ].filter((match) => match[2] === deprecation.methodName);
+ const syncCount = matches.filter((match) => !match[1]).length;
+ const asyncCount = matches.filter((match) => Boolean(match[1])).length;
+
+ if (syncCount !== 1 || asyncCount !== 1) {
+ throw new Error(
+ `${clientPath}: expected one sync and one async ${deprecation.methodName} method for deprecated Fern endpoint "${deprecation.endpointName}", found ${syncCount} sync and ${asyncCount} async`,
+ );
+ }
+
+ // PEP 702 consumers still surface the message statically; category=None
+ // avoids duplicate runtime warnings when the public client calls raw_client.
+ const decorator = ` @typing_extensions.deprecated(${pythonStringLiteral(deprecation.message)}, category=None)`;
+ let decoratedMethods = 0;
+
+ for (const match of matches.reverse()) {
+ const methodStart = match.index;
+ const previousLineEnd = methodStart - 1;
+ const previousLineStart =
+ contents.lastIndexOf("\n", previousLineEnd - 1) + 1;
+ const previousLine = contents.slice(previousLineStart, previousLineEnd);
+
+ if (previousLine === decorator) continue;
+
+ if (previousLine.startsWith(" @typing_extensions.deprecated(")) {
+ contents = `${contents.slice(0, previousLineStart)}${decorator}${contents.slice(previousLineEnd)}`;
+ decoratedMethods += 1;
+ continue;
+ }
+
+ if (previousLine.trimStart().startsWith("@")) {
+ throw new Error(
+ `${clientPath}: refusing to insert a deprecation before the existing decorator ${previousLine.trim()}`,
+ );
+ }
+
+ contents = `${contents.slice(0, methodStart)}${decorator}\n${contents.slice(methodStart)}`;
+ decoratedMethods += 1;
+ }
+
+ return { contents, decoratedMethods };
+}
+
+function ensureTypingExtensionsImport(
+ contents: string,
+ clientPath: string,
+): string {
+ const existingImports =
+ contents.match(/^import typing_extensions\s*$/gm) ?? [];
+ if (existingImports.length === 1) return contents;
+ if (existingImports.length > 1) {
+ throw new Error(
+ `${clientPath}: expected at most one typing_extensions import, found ${existingImports.length}`,
+ );
+ }
+
+ const typingImports = [...contents.matchAll(/^import typing\s*$/gm)];
+ if (typingImports.length !== 1) {
+ throw new Error(
+ `${clientPath}: expected exactly one generated typing import, found ${typingImports.length}`,
+ );
+ }
+
+ const typingImport = typingImports[0];
+ const insertionPoint = typingImport.index + typingImport[0].length;
+ return `${contents.slice(0, insertionPoint)}\nimport typing_extensions${contents.slice(insertionPoint)}`;
+}
+
+export function patchGeneratedPythonDeprecations({
+ definitionDirectory,
+ apiRoot,
+}: PatchOptions): PatchResult {
+ const deprecations = getFernPythonDeprecations(definitionDirectory);
+ const pendingFiles = new Map<
+ string,
+ { originalContents: string; contents: string }
+ >();
+ let decoratedMethods = 0;
+
+ for (const deprecation of deprecations) {
+ for (const fileName of ["client.py", "raw_client.py"]) {
+ const clientPath = path.join(apiRoot, deprecation.resourcePath, fileName);
+ let pendingFile = pendingFiles.get(clientPath);
+ if (!pendingFile) {
+ const contents = fs.readFileSync(clientPath, "utf8");
+ pendingFile = { originalContents: contents, contents };
+ }
+ const patched = patchMethodPair(
+ pendingFile.contents,
+ deprecation,
+ clientPath,
+ );
+
+ pendingFile.contents = ensureTypingExtensionsImport(
+ patched.contents,
+ clientPath,
+ );
+ decoratedMethods += patched.decoratedMethods;
+ pendingFiles.set(clientPath, pendingFile);
+ }
+ }
+
+ let changedFiles = 0;
+ for (const [clientPath, pendingFile] of pendingFiles) {
+ if (pendingFile.contents === pendingFile.originalContents) continue;
+ fs.writeFileSync(clientPath, pendingFile.contents);
+ changedFiles += 1;
+ }
+
+ return { changedFiles, decoratedMethods };
+}
+
+function main() {
+ const { values } = parseArgs({
+ options: {
+ "definition-root": { type: "string" },
+ "api-root": { type: "string" },
+ },
+ strict: true,
+ });
+
+ if (!values["definition-root"] || !values["api-root"]) {
+ throw new Error("--definition-root and --api-root are required");
+ }
+
+ const result = patchGeneratedPythonDeprecations({
+ definitionDirectory: path.resolve(values["definition-root"]),
+ apiRoot: path.resolve(values["api-root"]),
+ });
+ console.log(
+ result.changedFiles === 0
+ ? "No Python SDK deprecation patch needed."
+ : `Patched ${result.decoratedMethods} Python SDK methods across ${result.changedFiles} generated client files.`,
+ );
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ main();
+}
diff --git a/web/scripts/typescript-sdk/patch-generated-deprecations.ts b/web/scripts/typescript-sdk/patch-generated-deprecations.ts
new file mode 100644
index 0000000000..0c5f837320
--- /dev/null
+++ b/web/scripts/typescript-sdk/patch-generated-deprecations.ts
@@ -0,0 +1,554 @@
+import fs from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+import { fileURLToPath } from "node:url";
+import { parse } from "yaml";
+
+type FernAvailability =
+ | string
+ | {
+ status?: string;
+ message?: string;
+ };
+
+type FernProperty = {
+ availability?: FernAvailability;
+};
+
+type FernEndpoint = {
+ availability?: FernAvailability;
+ request?: {
+ name?: string;
+ body?: {
+ properties?: Record<string, FernProperty>;
+ };
+ };
+};
+
+type FernDefinition = {
+ service?: {
+ endpoints?: Record<string, FernEndpoint>;
+ };
+};
+
+type FernTypeScriptEndpointDeprecation = {
+ kind: "endpoint";
+ definitionPath: string;
+ endpointName: string;
+ generatedPath: string;
+ methodName: string;
+ message: string;
+};
+
+type FernTypeScriptPropertyDeprecation = {
+ kind: "property";
+ definitionPath: string;
+ generatedPath: string;
+ typeName: string;
+ propertyName: string;
+ message: string;
+};
+
+export type FernTypeScriptDeprecation =
+ | FernTypeScriptEndpointDeprecation
+ | FernTypeScriptPropertyDeprecation;
+
+type PatchOptions = {
+ definitionDirectory: string;
+ apiRoot: string;
+};
+
+type PatchResult = {
+ changedFiles: number;
+ decoratedSymbols: number;
+};
+
+type PendingFile = {
+ originalContents: string;
+ contents: string;
+};
+
+function listYamlFiles(directory: string): string[] {
+ return fs
+ .readdirSync(directory, { withFileTypes: true })
+ .flatMap((entry) => {
+ const entryPath = path.join(directory, entry.name);
+
+ if (entry.isDirectory()) return listYamlFiles(entryPath);
+ if (entry.isFile() && /\.ya?ml$/.test(entry.name)) return [entryPath];
+ return [];
+ })
+ .sort();
+}
+
+function toLowerCamelCase(value: string): string {
+ const joined = value.replace(
+ /[^a-zA-Z\d]+([a-zA-Z\d])/g,
+ (_match, character: string) => character.toUpperCase(),
+ );
+ return joined ? `${joined[0].toLowerCase()}${joined.slice(1)}` : joined;
+}
+
+function definitionResourceSegments(
+ definitionDirectory: string,
+ definitionPath: string,
+): string[] {
+ const relativePath = path.relative(definitionDirectory, definitionPath);
+ const parsedPath = path.parse(relativePath);
+ return [
+ ...parsedPath.dir.split(path.sep).filter(Boolean),
+ parsedPath.name,
+ ].map(toLowerCamelCase);
+}
+
+function generatedResourceRoot(resourceSegments: string[]): string {
+ const nestedSegments = resourceSegments.flatMap((segment, index) =>
+ index === 0 ? [segment] : ["resources", segment],
+ );
+ return path.join("api", "resources", ...nestedSegments);
+}
+
+function isDeprecated(availability: FernAvailability | undefined): boolean {
+ return (
+ availability === "deprecated" ||
+ (typeof availability === "object" && availability.status === "deprecated")
+ );
+}
+
+function readDeprecationMessage(
+ availability: FernAvailability | undefined,
+ label: string,
+): string {
+ const message =
+ typeof availability === "object" && typeof availability.message === "string"
+ ? availability.message.trim()
+ : "";
+
+ if (!message) {
+ throw new Error(`${label} must define availability.message`);
+ }
+ if (/\r|\n/.test(message)) {
+ throw new Error(`${label} must use a single-line availability.message`);
+ }
+ if (message.includes("*/")) {
+ throw new Error(`${label} has an availability.message that closes JSDoc`);
+ }
+ return message;
+}
+
+function availabilityPathKey(segments: string[]): string {
+ return JSON.stringify(segments);
+}
+
+function deprecatedAvailabilityPaths(
+ value: unknown,
+ prefix: string[] = [],
+): string[][] {
+ if (!value || typeof value !== "object") return [];
+
+ return Object.entries(value).flatMap(([key, child]) => {
+ const childPath = [...prefix, key];
+ const ownPath =
+ key === "availability" &&
+ isDeprecated(child as FernAvailability | undefined)
+ ? [childPath]
+ : [];
+ return [...ownPath, ...deprecatedAvailabilityPaths(child, childPath)];
+ });
+}
+
+function propertyGeneratedPath(resourceRoot: string, typeName: string): string {
+ return path.join(resourceRoot, "client", "requests", `${typeName}.ts`);
+}
+
+export function getFernTypeScriptDeprecations(
+ definitionDirectory: string,
+): FernTypeScriptDeprecation[] {
+ const deprecations: FernTypeScriptDeprecation[] = [];
+
+ for (const definitionPath of listYamlFiles(definitionDirectory)) {
+ const definition = parse(
+ fs.readFileSync(definitionPath, "utf8"),
+ ) as FernDefinition;
+ const resourceRoot = generatedResourceRoot(
+ definitionResourceSegments(definitionDirectory, definitionPath),
+ );
+ const handledAvailabilityPaths = new Set<string>();
+
+ for (const [endpointName, endpoint] of Object.entries(
+ definition.service?.endpoints ?? {},
+ )) {
+ const endpointAvailabilityPath = [
+ "service",
+ "endpoints",
+ endpointName,
+ "availability",
+ ];
+ if (isDeprecated(endpoint.availability)) {
+ handledAvailabilityPaths.add(
+ availabilityPathKey(endpointAvailabilityPath),
+ );
+
+ deprecations.push({
+ kind: "endpoint",
+ definitionPath,
+ endpointName,
+ generatedPath: path.join(resourceRoot, "client", "Client.ts"),
+ methodName: toLowerCamelCase(endpointName),
+ message: readDeprecationMessage(
+ endpoint.availability,
+ `Deprecated endpoint "${endpointName}" in ${definitionPath}`,
+ ),
+ });
+ }
+
+ for (const [propertyName, property] of Object.entries(
+ endpoint.request?.body?.properties ?? {},
+ )) {
+ if (!isDeprecated(property.availability)) continue;
+
+ const propertyAvailabilityPath = [
+ "service",
+ "endpoints",
+ endpointName,
+ "request",
+ "body",
+ "properties",
+ propertyName,
+ "availability",
+ ];
+ handledAvailabilityPaths.add(
+ availabilityPathKey(propertyAvailabilityPath),
+ );
+ const requestName = endpoint.request?.name;
+ if (!requestName) {
+ throw new Error(
+ `Deprecated request property "${propertyName}" on endpoint "${endpointName}" in ${definitionPath} requires request.name`,
+ );
+ }
+
+ deprecations.push({
+ kind: "property",
+ definitionPath,
+ generatedPath: propertyGeneratedPath(resourceRoot, requestName),
+ typeName: requestName,
+ propertyName: toLowerCamelCase(propertyName),
+ message: readDeprecationMessage(
+ property.availability,
+ `Deprecated request property "${propertyName}" on endpoint "${endpointName}" in ${definitionPath}`,
+ ),
+ });
+ }
+ }
+
+ const unsupported = deprecatedAvailabilityPaths(definition).filter(
+ (segments) =>
+ !handledAvailabilityPaths.has(availabilityPathKey(segments)),
+ );
+ if (unsupported.length > 0) {
+ throw new Error(
+ `Unsupported deprecated availability in ${definitionPath} at ${unsupported
+ .map((segments) => segments.join("."))
+ .join(", ")}`,
+ );
+ }
+ }
+
+ const generatedSymbols = new Set<string>();
+ for (const deprecation of deprecations) {
+ const symbol =
+ deprecation.kind === "endpoint"
+ ? `${deprecation.generatedPath}:method:${deprecation.methodName}`
+ : `${deprecation.generatedPath}:property:${deprecation.typeName}.${deprecation.propertyName}`;
+ if (generatedSymbols.has(symbol)) {
+ throw new Error(
+ `Multiple Fern deprecations resolve to generated TypeScript symbol ${symbol}`,
+ );
+ }
+ generatedSymbols.add(symbol);
+ }
+
+ return deprecations;
+}
+
+function occurrenceCount(contents: string, value: string): number {
+ return contents.split(value).length - 1;
+}
+
+function leadingJsDoc(
+ contents: string,
+ declarationStart: number,
+ indent: string,
+ label: string,
+): { start: number; end: number; contents: string } {
+ const prefix = contents.slice(0, declarationStart);
+ const docStart = prefix.lastIndexOf(`${indent}/**`);
+ if (docStart < 0) {
+ throw new Error(`${label}: generated declaration has no JSDoc`);
+ }
+
+ const docContents = prefix.slice(docStart);
+ const isMultiline =
+ docContents.startsWith(`${indent}/**\n`) &&
+ docContents.endsWith(`${indent} */\n`);
+ const isSingleLine =
+ docContents.startsWith(`${indent}/** `) &&
+ docContents.endsWith(" */\n") &&
+ !docContents.slice(0, -1).includes("\n");
+ if (!isMultiline && !isSingleLine) {
+ throw new Error(
+ `${label}: expected one JSDoc immediately before the generated declaration`,
+ );
+ }
+
+ return {
+ start: docStart,
+ end: declarationStart,
+ contents: docContents,
+ };
+}
+
+function patchJsDoc(
+ doc: string,
+ message: string,
+ indent: string,
+ label: string,
+): { contents: string; changed: boolean } {
+ const star = `${indent} *`;
+ const canonicalTag = `${star} @deprecated ${message}`;
+ const inlinePrefix = `${indent}/** `;
+ if (
+ doc.startsWith(inlinePrefix) &&
+ doc.endsWith(" */\n") &&
+ !doc.slice(0, -1).includes("\n")
+ ) {
+ const inlineContents = doc.slice(inlinePrefix.length, -4);
+ const description = inlineContents.startsWith("@deprecated")
+ ? []
+ : [`${star} ${inlineContents}`, star];
+ return {
+ contents: [
+ `${indent}/**`,
+ ...description,
+ canonicalTag,
+ `${indent} */`,
+ "",
+ ].join("\n"),
+ changed: inlineContents !== `@deprecated ${message}`,
+ };
+ }
+
+ const tags = [...doc.matchAll(/^([ ]*)\* @deprecated(?:\s+.*)?$/gm)].filter(
+ (match) => match[1] === `${indent} `,
+ );
+ if (tags.length > 1) {
+ throw new Error(`${label}: found multiple @deprecated tags`);
+ }
+ if (tags.length === 1) {
+ const tag = tags[0];
+ if (tag[0] === canonicalTag) return { contents: doc, changed: false };
+ return {
+ contents: `${doc.slice(0, tag.index)}${canonicalTag}${doc.slice(tag.index + tag[0].length)}`,
+ changed: true,
+ };
+ }
+
+ const firstTag = [...doc.matchAll(/^([ ]*)\* @/gm)].find(
+ (match) => match[1] === `${indent} `,
+ );
+ if (firstTag?.index !== undefined) {
+ return {
+ contents: `${doc.slice(0, firstTag.index)}${canonicalTag}\n${star}\n${doc.slice(firstTag.index)}`,
+ changed: true,
+ };
+ }
+
+ const close = doc.lastIndexOf(`${indent} */`);
+ if (close < 0) throw new Error(`${label}: malformed generated JSDoc`);
+ const beforeClose = doc.slice(0, close);
+ const separator = beforeClose.endsWith(`${star}\n`) ? "" : `${star}\n`;
+ return {
+ contents: `${beforeClose}${separator}${canonicalTag}\n${doc.slice(close)}`,
+ changed: true,
+ };
+}
+
+function replaceJsDoc(
+ contents: string,
+ jsDoc: ReturnType<typeof leadingJsDoc>,
+ message: string,
+ indent: string,
+ label: string,
+): { contents: string; changed: boolean } {
+ const patched = patchJsDoc(jsDoc.contents, message, indent, label);
+ if (!patched.changed) return { contents, changed: false };
+ return {
+ contents: `${contents.slice(0, jsDoc.start)}${patched.contents}${contents.slice(jsDoc.end)}`,
+ changed: true,
+ };
+}
+
+function patchEndpointMethod(
+ contents: string,
+ deprecation: FernTypeScriptEndpointDeprecation,
+ clientPath: string,
+): { contents: string; changed: boolean } {
+ const publicMethods = [
+ ...contents.matchAll(/^([ ]+)public ([a-zA-Z_$][\w$]*)\($/gm),
+ ].filter((match) => match[2] === deprecation.methodName);
+ const privateMethods = [
+ ...contents.matchAll(/^([ ]+)private async __([a-zA-Z_$][\w$]*)\($/gm),
+ ].filter((match) => match[2] === deprecation.methodName);
+ if (publicMethods.length !== 1 || privateMethods.length !== 1) {
+ throw new Error(
+ `${clientPath}: expected one public ${deprecation.methodName} and one private __${deprecation.methodName} method, found ${publicMethods.length} public and ${privateMethods.length} private`,
+ );
+ }
+
+ const publicStart = publicMethods[0].index;
+ const privateStart = privateMethods[0].index;
+ const publicIndent = publicMethods[0][1];
+ const privateIndent = privateMethods[0][1];
+ if (publicIndent !== privateIndent) {
+ throw new Error(
+ `${clientPath}: public ${deprecation.methodName} and private __${deprecation.methodName} use different indentation`,
+ );
+ }
+ if (privateStart <= publicStart) {
+ throw new Error(
+ `${clientPath}: private __${deprecation.methodName} does not follow its public method`,
+ );
+ }
+ const delegation = `this.__${deprecation.methodName}(`;
+ if (
+ occurrenceCount(contents.slice(publicStart, privateStart), delegation) !== 1
+ ) {
+ throw new Error(
+ `${clientPath}: public ${deprecation.methodName} must delegate exactly once to private __${deprecation.methodName}`,
+ );
+ }
+
+ const label = `${clientPath}: public ${deprecation.methodName}`;
+ return replaceJsDoc(
+ contents,
+ leadingJsDoc(contents, publicStart, publicIndent, label),
+ deprecation.message,
+ publicIndent,
+ label,
+ );
+}
+
+function patchProperty(
+ contents: string,
+ deprecation: FernTypeScriptPropertyDeprecation,
+ generatedFilePath: string,
+): { contents: string; changed: boolean } {
+ const interfaces = [
+ ...contents.matchAll(/^export interface ([a-zA-Z_$][\w$]*) \{$/gm),
+ ].filter((match) => match[1] === deprecation.typeName);
+ if (interfaces.length !== 1) {
+ throw new Error(
+ `${generatedFilePath}: expected one ${deprecation.typeName} interface, found ${interfaces.length}`,
+ );
+ }
+
+ const interfaceStart = interfaces[0].index;
+ const interfaceEnd = contents.indexOf("\n}", interfaceStart);
+ if (interfaceEnd < 0) {
+ throw new Error(
+ `${generatedFilePath}: could not determine the end of ${deprecation.typeName}`,
+ );
+ }
+ const properties = [
+ ...contents
+ .slice(interfaceStart, interfaceEnd)
+ .matchAll(/^([ ]+)([a-zA-Z_$][\w$]*)\??:/gm),
+ ].filter((match) => match[2] === deprecation.propertyName);
+ if (properties.length !== 1) {
+ throw new Error(
+ `${generatedFilePath}: expected one ${deprecation.propertyName} property on ${deprecation.typeName}, found ${properties.length}`,
+ );
+ }
+
+ const propertyStart = interfaceStart + properties[0].index;
+ const propertyIndent = properties[0][1];
+ const label = `${generatedFilePath}: ${deprecation.typeName}.${deprecation.propertyName}`;
+ return replaceJsDoc(
+ contents,
+ leadingJsDoc(contents, propertyStart, propertyIndent, label),
+ deprecation.message,
+ propertyIndent,
+ label,
+ );
+}
+
+export function patchGeneratedTypeScriptDeprecations({
+ definitionDirectory,
+ apiRoot,
+}: PatchOptions): PatchResult {
+ const deprecations = getFernTypeScriptDeprecations(definitionDirectory);
+ const pendingFiles = new Map<string, PendingFile>();
+ let decoratedSymbols = 0;
+
+ for (const deprecation of deprecations) {
+ const generatedFilePath = path.join(apiRoot, deprecation.generatedPath);
+ const pendingFile =
+ pendingFiles.get(generatedFilePath) ??
+ (() => {
+ const contents = fs.readFileSync(generatedFilePath, "utf8");
+ return { originalContents: contents, contents };
+ })();
+ const patched =
+ deprecation.kind === "endpoint"
+ ? patchEndpointMethod(
+ pendingFile.contents,
+ deprecation,
+ generatedFilePath,
+ )
+ : patchProperty(pendingFile.contents, deprecation, generatedFilePath);
+
+ if (patched.changed) decoratedSymbols += 1;
+ pendingFile.contents = patched.contents;
+ pendingFiles.set(generatedFilePath, pendingFile);
+ }
+
+ let changedFiles = 0;
+ for (const [generatedFilePath, pendingFile] of pendingFiles) {
+ if (pendingFile.contents === pendingFile.originalContents) continue;
+ fs.writeFileSync(generatedFilePath, pendingFile.contents);
+ changedFiles += 1;
+ }
+
+ return { changedFiles, decoratedSymbols };
+}
+
+function main(): void {
+ const { values } = parseArgs({
+ options: {
+ "definition-root": { type: "string" },
+ "api-root": { type: "string" },
+ },
+ strict: true,
+ });
+
+ if (!values["definition-root"] || !values["api-root"]) {
+ throw new Error("--definition-root and --api-root are required");
+ }
+
+ const result = patchGeneratedTypeScriptDeprecations({
+ definitionDirectory: path.resolve(values["definition-root"]),
+ apiRoot: path.resolve(values["api-root"]),
+ });
+ console.log(
+ result.changedFiles === 0
+ ? "No TypeScript SDK deprecation patch needed."
+ : `Patched ${result.decoratedSymbols} TypeScript SDK symbols across ${result.changedFiles} generated files.`,
+ );
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ main();
+}
diff --git a/web/src/__tests__/server/unit/python-sdk-deprecations.servertest.ts b/web/src/__tests__/server/unit/python-sdk-deprecations.servertest.ts
new file mode 100644
index 0000000000..6d92c99f44
--- /dev/null
+++ b/web/src/__tests__/server/unit/python-sdk-deprecations.servertest.ts
@@ -0,0 +1,216 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import {
+ getFernPythonDeprecations,
+ patchGeneratedPythonDeprecations,
+} from "../../../../scripts/python-sdk/patch-generated-deprecations";
+
+const GENERATED_CLIENT = `# This file was auto-generated by Fern from our API Definition.
+
+import typing
+
+
+class WidgetClient:
+ def get_thing(self) -> None:
+ pass
+
+
+class AsyncWidgetClient:
+ async def get_thing(self) -> None:
+ pass
+`;
+
+const GENERATED_RAW_CLIENT = `# This file was auto-generated by Fern from our API Definition.
+
+import typing
+from json.decoder import JSONDecodeError
+
+
+class RawWidgetClient:
+ def get_thing(self) -> None:
+ pass
+
+
+class AsyncRawWidgetClient:
+ async def get_thing(self) -> None:
+ pass
+`;
+
+function withFixture(
+ availability: string,
+ assertions: (definitionDirectory: string, apiRoot: string) => void,
+) {
+ const root = fs.mkdtempSync(
+ path.join(os.tmpdir(), "python-sdk-deprecations-"),
+ );
+ const definitionDirectory = path.join(root, "definition");
+ const resourceDirectory = path.join(root, "api", "legacy", "widget_client");
+
+ try {
+ fs.mkdirSync(path.join(definitionDirectory, "legacy"), {
+ recursive: true,
+ });
+ fs.mkdirSync(resourceDirectory, { recursive: true });
+ fs.writeFileSync(path.join(definitionDirectory, "api.yml"), "name: api\n");
+ fs.writeFileSync(
+ path.join(definitionDirectory, "legacy", "widget-client.yml"),
+ [
+ "service:",
+ " endpoints:",
+ " getThing:",
+ " availability:",
+ ...availability.split("\n").map((line) => ` ${line}`),
+ " method: GET",
+ " path: /widgets/{widgetId}",
+ " request:",
+ " body:",
+ " properties:",
+ " oldField:",
+ " type: optional<string>",
+ " availability:",
+ " status: deprecated",
+ " message: This field-level marker is not an endpoint.",
+ "",
+ ].join("\n"),
+ );
+ fs.writeFileSync(
+ path.join(resourceDirectory, "client.py"),
+ GENERATED_CLIENT,
+ );
+ fs.writeFileSync(
+ path.join(resourceDirectory, "raw_client.py"),
+ GENERATED_RAW_CLIENT,
+ );
+
+ assertions(definitionDirectory, path.join(root, "api"));
+ } finally {
+ fs.rmSync(root, { recursive: true });
+ }
+}
+
+describe("Python SDK deprecations", () => {
+ it("maps the current Fern endpoint deprecations to Python resource methods", () => {
+ const definitionDirectory = path.resolve(
+ process.cwd(),
+ "../fern/apis/server/definition",
+ );
+
+ expect(
+ getFernPythonDeprecations(definitionDirectory).map(
+ ({ resourcePath, methodName }) =>
+ `${resourcePath.replaceAll(path.sep, "/")}:${methodName}`,
+ ),
+ ).toEqual([
+ "dataset_run_items:create",
+ "dataset_run_items:list",
+ "datasets:get_run",
+ "datasets:delete_run",
+ "datasets:get_runs",
+ "ingestion:batch",
+ "legacy/metrics_v1:metrics",
+ "legacy/observations_v1:get",
+ "legacy/observations_v1:get_many",
+ "scores:get_many",
+ "scores:get_by_id",
+ "sessions:list",
+ "sessions:get",
+ "trace:get",
+ "trace:list",
+ ]);
+ });
+
+ it("decorates sync, async, raw, and async-raw endpoint methods", () => {
+ const message =
+ 'Use "new_api" at C:\\sdk instead.\nThen call the client\'s replacement.';
+
+ withFixture(
+ [
+ "status: deprecated",
+ "message: |-",
+ ' Use "new_api" at C:\\sdk instead.',
+ " Then call the client's replacement.",
+ ].join("\n"),
+ (definitionDirectory, apiRoot) => {
+ expect(getFernPythonDeprecations(definitionDirectory)).toEqual([
+ {
+ definitionPath: path.join(
+ definitionDirectory,
+ "legacy",
+ "widget-client.yml",
+ ),
+ endpointName: "getThing",
+ resourcePath: path.join("legacy", "widget_client"),
+ methodName: "get_thing",
+ message,
+ },
+ ]);
+
+ expect(
+ patchGeneratedPythonDeprecations({ definitionDirectory, apiRoot }),
+ ).toEqual({ changedFiles: 2, decoratedMethods: 4 });
+
+ const decorator = ` @typing_extensions.deprecated(${JSON.stringify(message)}, category=None)`;
+ for (const fileName of ["client.py", "raw_client.py"]) {
+ const contents = fs.readFileSync(
+ path.join(apiRoot, "legacy", "widget_client", fileName),
+ "utf8",
+ );
+
+ expect(contents.match(/import typing_extensions/g)).toHaveLength(1);
+ expect(
+ contents.match(/@typing_extensions\.deprecated\(/g),
+ ).toHaveLength(2);
+ expect(contents).toContain(`${decorator}\n def get_thing(`);
+ expect(contents).toContain(`${decorator}\n async def get_thing(`);
+ }
+
+ expect(
+ patchGeneratedPythonDeprecations({ definitionDirectory, apiRoot }),
+ ).toEqual({ changedFiles: 0, decoratedMethods: 0 });
+ },
+ );
+ });
+
+ it("refuses an endpoint deprecation without a customer-facing message", () => {
+ withFixture("status: deprecated", (definitionDirectory) => {
+ expect(() => getFernPythonDeprecations(definitionDirectory)).toThrow(
+ /must define availability\.message/,
+ );
+ });
+ });
+
+ it("refuses to patch an incomplete generated client surface", () => {
+ withFixture(
+ "status: deprecated\nmessage: Use the replacement endpoint.",
+ (definitionDirectory, apiRoot) => {
+ const clientPath = path.join(
+ apiRoot,
+ "legacy",
+ "widget_client",
+ "client.py",
+ );
+ const rawClientPath = path.join(
+ apiRoot,
+ "legacy",
+ "widget_client",
+ "raw_client.py",
+ );
+ const incompleteRawClient = GENERATED_RAW_CLIENT.replace(
+ " async def get_thing(",
+ " async def other(",
+ );
+ fs.writeFileSync(rawClientPath, incompleteRawClient);
+
+ expect(() =>
+ patchGeneratedPythonDeprecations({ definitionDirectory, apiRoot }),
+ ).toThrow(/expected one sync and one async get_thing method/);
+ expect(fs.readFileSync(clientPath, "utf8")).toBe(GENERATED_CLIENT);
+ expect(fs.readFileSync(rawClientPath, "utf8")).toBe(
+ incompleteRawClient,
+ );
+ },
+ );
+ });
+});
diff --git a/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts b/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts
new file mode 100644
index 0000000000..9ee7ac7ca1
--- /dev/null
+++ b/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts
@@ -0,0 +1,261 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import {
+ getFernTypeScriptDeprecations,
+ patchGeneratedTypeScriptDeprecations,
+} from "../../../../scripts/typescript-sdk/patch-generated-deprecations";
+
+const DEFINITION = `service:
+ endpoints:
+ getThing:
+ availability:
+ status: deprecated
+ message: "Use getNewThing() instead."
+ method: GET
+ path: /widgets/{widgetId}
+ request:
+ name: GetThingRequest
+ body:
+ properties:
+ password:
+ docs: Accepted for compatibility.
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: This field is ignored; use SSO instead.
+ listThings:
+ availability:
+ status: deprecated
+ message: Use listNewThings() instead.
+ method: GET
+ path: /widgets
+`;
+
+const GENERATED_CLIENT = `export class GeneratedClient {
+ /**
+ * Get a thing.
+ *
+ * @param request Generated request.
+ */
+ public getThing(
+ request?: unknown,
+ ): core.HttpResponsePromise<unknown> {
+ return core.HttpResponsePromise.fromPromise(this.__getThing(request));
+ }
+
+ private async __getThing(
+ request?: unknown,
+ ): Promise<core.WithRawResponse<unknown>> {
+ return { data: request, rawResponse: undefined };
+ }
+
+ /**
+ * List things.
+ */
+ public listThings(
+ request?: unknown,
+ ): core.HttpResponsePromise<unknown> {
+ return core.HttpResponsePromise.fromPromise(this.__listThings(request));
+ }
+
+ private async __listThings(
+ request?: unknown,
+ ): Promise<core.WithRawResponse<unknown>> {
+ return { data: request, rawResponse: undefined };
+ }
+}
+`;
+
+const GENERATED_REQUEST = `export interface GetThingRequest {
+ /** Existing password docs. */
+ password?: string;
+}
+`;
+
+type Fixture = {
+ definitionDirectory: string;
+ apiRoot: string;
+ clientPath: string;
+ requestPath: string;
+};
+
+function withFixture(
+ definition: string,
+ assertions: (fixture: Fixture) => void,
+): void {
+ const root = fs.mkdtempSync(
+ path.join(os.tmpdir(), "typescript-sdk-deprecations-"),
+ );
+ const definitionDirectory = path.join(root, "definition");
+ const apiRoot = path.join(root, "generated");
+ const resourceRoot = path.join(apiRoot, "api/resources/widgetService");
+ const clientPath = path.join(resourceRoot, "client/Client.ts");
+ const requestPath = path.join(
+ resourceRoot,
+ "client/requests/GetThingRequest.ts",
+ );
+
+ try {
+ fs.mkdirSync(definitionDirectory, { recursive: true });
+ fs.mkdirSync(path.dirname(clientPath), { recursive: true });
+ fs.mkdirSync(path.dirname(requestPath), { recursive: true });
+ fs.writeFileSync(path.join(definitionDirectory, "api.yml"), "name: api\n");
+ fs.writeFileSync(
+ path.join(definitionDirectory, "widget-service.yml"),
+ definition,
+ );
+ fs.writeFileSync(clientPath, GENERATED_CLIENT);
+ fs.writeFileSync(requestPath, GENERATED_REQUEST);
+
+ assertions({ definitionDirectory, apiRoot, clientPath, requestPath });
+ } finally {
+ fs.rmSync(root, { recursive: true });
+ }
+}
+
+describe("TypeScript SDK deprecations", () => {
+ it("maps all current Fern endpoint and property deprecations", () => {
+ const definitionDirectory = path.resolve(
+ process.cwd(),
+ "../fern/apis/server/definition",
+ );
+ const deprecations = getFernTypeScriptDeprecations(definitionDirectory);
+
+ expect(
+ deprecations
+ .filter((entry) => entry.kind === "endpoint")
+ .map(
+ ({ generatedPath, methodName }) =>
+ `${generatedPath.replaceAll(path.sep, "/")}:${methodName}`,
+ ),
+ ).toEqual([
+ "api/resources/datasetRunItems/client/Client.ts:create",
+ "api/resources/datasetRunItems/client/Client.ts:list",
+ "api/resources/datasets/client/Client.ts:getRun",
+ "api/resources/datasets/client/Client.ts:deleteRun",
+ "api/resources/datasets/client/Client.ts:getRuns",
+ "api/resources/ingestion/client/Client.ts:batch",
+ "api/resources/legacy/resources/metricsV1/client/Client.ts:metrics",
+ "api/resources/legacy/resources/observationsV1/client/Client.ts:get",
+ "api/resources/legacy/resources/observationsV1/client/Client.ts:getMany",
+ "api/resources/scores/client/Client.ts:getMany",
+ "api/resources/scores/client/Client.ts:getById",
+ "api/resources/sessions/client/Client.ts:list",
+ "api/resources/sessions/client/Client.ts:get",
+ "api/resources/trace/client/Client.ts:get",
+ "api/resources/trace/client/Client.ts:list",
+ ]);
+ expect(
+ deprecations
+ .filter((entry) => entry.kind === "property")
+ .map(
+ ({ generatedPath, typeName, propertyName }) =>
+ `${generatedPath.replaceAll(path.sep, "/")}:${typeName}.${propertyName}`,
+ ),
+ ).toEqual([
+ "api/resources/scim/client/requests/CreateUserRequest.ts:CreateUserRequest.password",
+ ]);
+ });
+
+ it("patches exact messages across one shared client and is byte-idempotent", () => {
+ withFixture(
+ DEFINITION,
+ ({ definitionDirectory, apiRoot, clientPath, requestPath }) => {
+ expect(
+ patchGeneratedTypeScriptDeprecations({
+ definitionDirectory,
+ apiRoot,
+ }),
+ ).toEqual({ changedFiles: 2, decoratedSymbols: 3 });
+
+ const client = fs.readFileSync(clientPath, "utf8");
+ const request = fs.readFileSync(requestPath, "utf8");
+ expect(client.match(/@deprecated/g)).toHaveLength(2);
+ expect(client).toContain("@deprecated Use getNewThing() instead.");
+ expect(client).toContain("@deprecated Use listNewThings() instead.");
+ expect(request).toContain(
+ [
+ " /**",
+ " * Existing password docs.",
+ " *",
+ " * @deprecated This field is ignored; use SSO instead.",
+ " */",
+ " password?: string;",
+ ].join("\n"),
+ );
+
+ expect(
+ patchGeneratedTypeScriptDeprecations({
+ definitionDirectory,
+ apiRoot,
+ }),
+ ).toEqual({ changedFiles: 0, decoratedSymbols: 0 });
+ expect(fs.readFileSync(clientPath, "utf8")).toBe(client);
+ expect(fs.readFileSync(requestPath, "utf8")).toBe(request);
+ },
+ );
+ });
+
+ it("fails closed for missing, multiline, and unsupported messages", () => {
+ withFixture(
+ DEFINITION.replace(
+ ' message: "Use getNewThing() instead."\n',
+ "",
+ ),
+ ({ definitionDirectory }) => {
+ expect(() =>
+ getFernTypeScriptDeprecations(definitionDirectory),
+ ).toThrow(/must define availability\.message/);
+ },
+ );
+
+ withFixture(
+ DEFINITION.replace(
+ ' message: "Use getNewThing() instead."',
+ [
+ " message: |-",
+ " Use getNewThing() instead.",
+ " See the migration guide.",
+ ].join("\n"),
+ ),
+ ({ definitionDirectory }) => {
+ expect(() =>
+ getFernTypeScriptDeprecations(definitionDirectory),
+ ).toThrow(/must use a single-line availability\.message/);
+ },
+ );
+
+ withFixture(
+ `${DEFINITION}\ntypes:\n Widget:\n properties:\n oldValue:\n type: optional<string>\n availability:\n status: deprecated\n message: Use the current value.\n`,
+ ({ definitionDirectory }) => {
+ expect(() =>
+ getFernTypeScriptDeprecations(definitionDirectory),
+ ).toThrow(/Unsupported deprecated availability/);
+ },
+ );
+ });
+
+ it("does not partially write when a generated target is incomplete", () => {
+ withFixture(
+ DEFINITION,
+ ({ definitionDirectory, apiRoot, clientPath, requestPath }) => {
+ const incompleteRequest = GENERATED_REQUEST.replace(
+ " password?: string;",
+ " anotherField?: string;",
+ );
+ fs.writeFileSync(requestPath, incompleteRequest);
+
+ expect(() =>
+ patchGeneratedTypeScriptDeprecations({
+ definitionDirectory,
+ apiRoot,
+ }),
+ ).toThrow(/expected one password property/);
+ expect(fs.readFileSync(clientPath, "utf8")).toBe(GENERATED_CLIENT);
+ expect(fs.readFileSync(requestPath, "utf8")).toBe(incompleteRequest);
+ },
+ );
+ });
+});