Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(web): export OpenAPI mapper types and compatible contract subpaths (#44915)
Stephen Zhou04ba877c1ab5
diff --git a/.github/workflows/web-tests.yml b/.github/workflows/web-tests.ymlindex af1d67b8063..82697e50d12 100644--- a/.github/workflows/web-tests.yml+++ b/.github/workflows/web-tests.yml@@ -43,7 +43,7 @@ jobs:run: pnpm --filter @dify/openapi-content-mapper test:next- name: Verify standalone Console imports, error maps and editor support- run: pnpm --filter @dify/openapi-content-mapper exec node --test --test-concurrency=1 integration/knowledge-fs-console.test.mjs integration/orpc-errors.test.mjs integration/console-preparation.test.mjs integration/console-editor.test.mjs+ run: pnpm --filter @dify/openapi-content-mapper exec node --test --test-concurrency=1 integration/knowledge-fs-console.test.mjs integration/orpc-errors.test.mjs integration/console-preparation.test.mjs integration/console-editor.test.mjs integration/type-navigation.test.mjs- name: Check all Console types against the reviewed migration differencesrun: pnpm --filter @dify/openapi-content-mapper check:consolediff --git a/api/controllers/common/schema.py b/api/controllers/common/schema.pyindex efe14090bae..f520345fcca 100644--- a/api/controllers/common/schema.py+++ b/api/controllers/common/schema.py@@ -83,6 +83,11 @@ _registered_schemas: WeakKeyDictionary[Namespace, dict[str, tuple[str, str, dict_NON_ALPHANUMERIC = re.compile(r"[^a-z0-9]")+def registered_schema_sources(namespace: Namespace) -> dict[str, str]:+ """Return component identities for editor tooling without exposing mutable schemas."""+ return {name: source for name, source, _ in _registered_schemas.get(namespace, {}).values()}++def _normalized_schema_name(name: str) -> str:"""Fold names that client code generators turn into the same identifier (`JSONValue` / `JsonValue`)."""diff --git a/api/dev/cached_console_openapi.py b/api/dev/cached_console_openapi.pyindex 5268969ff2b..f8a8debe30e 100644--- a/api/dev/cached_console_openapi.py+++ b/api/dev/cached_console_openapi.py@@ -27,6 +27,8 @@ from pathlib import Pathfrom typing import Any, NeverAPI_ROOT = Path(__file__).resolve().parents[1]+SOURCE_ROOTS = (API_ROOT, API_ROOT.parent / "dify-agent/src")+PACKAGE_INPUTS = (API_ROOT / "pyproject.toml", API_ROOT / "uv.lock", API_ROOT.parent / "dify-agent/pyproject.toml")TIMEOUT = 90IDLE_TIMEOUT = 120MAX_BYTES = 64 * 1024 * 1024@@ -38,7 +40,7 @@ def source_imports() -> None:def get_code(self: importlib.machinery.SourceFileLoader, fullname: str):path = Path(self.path)- if path.is_relative_to(API_ROOT) and ".venv" not in path.parts:+ if any(path.is_relative_to(root) for root in SOURCE_ROOTS) and ".venv" not in path.parts:return self.source_to_code(self.get_data(self.path), self.path)return original(self, fullname)@@ -48,12 +50,13 @@ def source_imports() -> None:def source_state() -> dict[str, tuple[int, int, int]]:"""Match the Console descriptor's inputs, excluding tests and local environments."""- files = [API_ROOT / "pyproject.toml", API_ROOT / "uv.lock", Path.cwd() / ".env"]- for directory, children, names in os.walk(API_ROOT):- children[:] = [name for name in children if name not in {".venv", ".git", "__pycache__"}]- if Path(directory) == API_ROOT:- children[:] = [name for name in children if name != "tests"]- files.extend(Path(directory) / name for name in names if name.endswith(".py"))+ files = [*PACKAGE_INPUTS, Path.cwd() / ".env"]+ for root in SOURCE_ROOTS:+ for directory, children, names in os.walk(root):+ children[:] = [name for name in children if name not in {".venv", ".git", "__pycache__"}]+ if Path(directory) == API_ROOT:+ children[:] = [name for name in children if name != "tests"]+ files.extend(Path(directory) / name for name in names if name.endswith(".py"))return {str(file): file_stamp(file) for file in files}@@ -141,7 +144,7 @@ def preload() -> tuple[bool, dict[str, tuple[int, int, int]]]:filename = getattr(module, "__file__", None) # guard-ignore: no-new-getattr -- optional module source metadataif isinstance(filename, str):dependencies[str(Path(filename).resolve())] = file_stamp(Path(filename))- for filename in (API_ROOT / "pyproject.toml", API_ROOT / "uv.lock", Path.cwd() / ".env"):+ for filename in (*PACKAGE_INPUTS, Path.cwd() / ".env"):dependencies[str(filename)] = file_stamp(filename)return safe, dependenciesdiff --git a/api/dev/export_console_openapi.py b/api/dev/export_console_openapi.pyindex a7ac8ca102d..809c1544791 100644--- a/api/dev/export_console_openapi.py+++ b/api/dev/export_console_openapi.py@@ -10,24 +10,74 @@ from pathlib import Pathfrom typing import Any-def attach_source_location(document: dict[str, Any], path: str, method: str, handler: Any) -> None:- """Attach editor-only origins to exported operations, leaving live schemas unchanged."""- operation = document["paths"].get(path, {}).get(method.lower())- if not isinstance(operation, dict) or handler is None:- return+def source_location(target: Any) -> dict[str, Any] | None:+ """Locate the actual class or function definition, skipping decorators."""try:- handler = inspect.unwrap(handler)- filename = inspect.getsourcefile(handler)- lines, start = inspect.getsourcelines(handler)+ target = inspect.unwrap(target)+ filename = inspect.getsourcefile(target)+ lines, start = inspect.getsourcelines(target)definition = ast.parse(textwrap.dedent("".join(lines))).body[0]except (OSError, TypeError, ValueError, SyntaxError):# Dynamically created or native handlers have no navigable Python source.- return- if filename and isinstance(definition, (ast.FunctionDef, ast.AsyncFunctionDef)):- operation["x-source-location"] = {+ return None+ if filename and isinstance(definition, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):+ return {"file": str(Path(filename).resolve()),"line": start + definition.lineno - 1,}+ return None+++def resolve_source_type(source: str) -> Any:+ """Resolve registered identities only, including nested classes and generic origins."""+ parts = source.split("[", 1)[0].split(".")+ for end in range(len(parts) - 1, 0, -1):+ target = sys.modules.get(".".join(parts[:end]))+ if target is None:+ continue+ for part in parts[end:]:+ if not inspect.ismodule(target) and not inspect.isclass(target):+ return None+ target = vars(target).get(part)+ return target if inspect.isclass(target) else None+ return None+++def attach_source_location(document: dict[str, Any], path: str, method: str, handler: Any) -> None:+ """Attach editor-only origins to exported operations, leaving live schemas unchanged."""+ operation = document["paths"].get(path, {}).get(method.lower())+ if isinstance(operation, dict) and (location := source_location(handler)):+ operation["x-source-location"] = location+++def attach_api_sources(document: dict[str, Any], api: Any) -> None:+ """Annotate exported RESTX models and operations from their registered Python owners."""+ from flask_restx.swagger import extract_path++ from controllers.common.schema import registered_schema_sources++ schemas = document.get("components", {}).get("schemas", {})+ for namespace in api.namespaces:+ for name, source in registered_schema_sources(namespace).items():+ if name in schemas and (location := source_location(resolve_source_type(source))):+ schemas[name]["x-source-location"] = location+ for resource in namespace.resources:+ cls = resource.resource+ for url in api.ns_urls(namespace, resource.urls):+ for method in cls.methods:+ handler = getattr(cls, method.lower(), None) # guard-ignore: no-new-getattr -- HTTP method+ attach_source_location(document, extract_path(url), method, handler)+++def export_all_with_sources() -> dict[str, dict[str, Any]]:+ """Export every RESTX surface with editor metadata, without writing spec files."""+ from dev.generate_swagger_specs import SPEC_TARGETS, _target_apis, export_specs++ documents = export_specs()+ apis = _target_apis()+ for target in SPEC_TARGETS:+ attach_api_sources(documents[target.filename], apis[target.route])+ return documentsdef main() -> None:@@ -41,19 +91,10 @@ def main() -> None:"console": export_console_spec(),"fast": export_fastopenapi_specs()["fastopenapi-console-openapi.json"],}- from flask_restx.swagger import extract_path-from controllers.console import apifrom controllers.fastopenapi import console_router- for namespace in api.namespaces:- for resource in namespace.resources:- cls = resource.resource- for url in api.ns_urls(namespace, resource.urls):- path = extract_path(url)- for method in cls.methods:- handler = getattr(cls, method.lower(), None) # guard-ignore: no-new-getattr -- HTTP method- attach_source_location(documents["console"], path, method, handler)+ attach_api_sources(documents["console"], api)for path, method, handler in console_router.get_routes():attach_source_location(documents["fast"], f"/console/api{path}", method, handler)json.dump(documents, sys.stdout, sort_keys=True)diff --git a/api/tests/unit_tests/dev/test_cached_console_openapi.py b/api/tests/unit_tests/dev/test_cached_console_openapi.pyindex bfba72aadb7..825ac943c98 100644--- a/api/tests/unit_tests/dev/test_cached_console_openapi.py+++ b/api/tests/unit_tests/dev/test_cached_console_openapi.py@@ -3,6 +3,7 @@import concurrent.futuresimport jsonimport os+import py_compileimport shutilimport subprocessimport sys@@ -147,6 +148,36 @@ def test_environment_and_file_additions_invalidate_memory_cache(backend: CacheClassert call()["snapshot"] != added["snapshot"]+def test_sibling_python_models_refresh_cached_exports_without_stale_bytecode(backend: CacheClient) -> None:+ package = backend.api.parent / "dify-agent/src/citation_fixture"+ package.mkdir(parents=True)+ (package / "__init__.py").touch()+ model = package / "model.py"+ model.write_text("FIELD = 'string'\n")+ compiled = py_compile.compile(str(model), doraise=True)+ assert compiled is not None+ bytecode = Path(compiled).read_bytes()+ # This module is imported by the export worker, not by the preloaded snapshot.+ (backend.api / "controllers/fixture.py").write_text("from citation_fixture.model import FIELD\n")+ backend.env["PYTHONPATH"] = os.pathsep.join([str(backend.api), str(package.parent)])+ first = backend.export()+ assert first["field"] == "string"+ assert backend.export() == first+ stat = model.stat()+ model.write_text("FIELD = 'number'\n")+ os.utime(model, ns=(stat.st_atime_ns, stat.st_mtime_ns))+ changed = backend.export()+ assert changed["field"] == "number"+ assert changed["pid"] != first["pid"]+ added = package / "new_model.py"+ added.write_text("VALUE = 1\n")+ with_added = backend.export()+ assert with_added["pid"] != changed["pid"]+ added.unlink()+ assert backend.export()["pid"] != with_added["pid"]+ assert Path(compiled).read_bytes() == bytecode++def test_native_threads_use_fresh_exports_and_propagate_failures(backend: CacheClient) -> None:model = backend.api / "models.py"model.write_text(diff --git a/api/tests/unit_tests/dev/test_openapi_source_locations.py b/api/tests/unit_tests/dev/test_openapi_source_locations.pynew file mode 100644index 00000000000..a2192871dfa--- /dev/null+++ b/api/tests/unit_tests/dev/test_openapi_source_locations.py@@ -0,0 +1,75 @@+"""Editor metadata must follow registered Python identities without changing live schemas."""++import inspect+from collections.abc import Callable+from copy import deepcopy+from functools import wraps+from pathlib import Path++from flask_restx import Api, Namespace, Resource+from pydantic import BaseModel++from controllers.common.schema import register_schema_model, registered_schema_sources+from dev.export_console_openapi import attach_api_sources, resolve_source_type, source_location+++class NavigationPayload(BaseModel):+ name: str+++class Container:+ class Nested(BaseModel):+ value: str+++def decorated[**P, R](handler: Callable[P, R]) -> Callable[P, R]:+ @wraps(handler)+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:+ return handler(*args, **kwargs)++ return wrapper+++class NavigationResource(Resource):+ @decorated+ def post(self) -> dict[str, str]:+ return {}+++def test_registered_models_and_decorated_operations_have_exact_origins() -> None:+ namespace = Namespace("navigation", path="/navigation")+ register_schema_model(namespace, NavigationPayload)+ namespace.add_resource(NavigationResource, "")+ api = Api()+ api.add_namespace(namespace)+ live_schema = deepcopy(namespace.models["NavigationPayload"].__schema__)+ document = {+ "components": {"schemas": {"NavigationPayload": deepcopy(live_schema), "Synthetic": {"type": "object"}}},+ "paths": {"/navigation": {"post": {"description": "Create"}}},+ }++ attach_api_sources(document, api)++ model_source = document["components"]["schemas"]["NavigationPayload"]["x-source-location"]+ assert model_source == {"file": str(Path(__file__).resolve()), "line": inspect.getsourcelines(NavigationPayload)[1]}+ operation_source = document["paths"]["/navigation"]["post"]["x-source-location"]+ expected_line = next(+ line+ for line, text in enumerate(Path(__file__).read_text().splitlines(), 1)+ if text.strip() == "def post(self) -> dict[str, str]:"+ )+ assert operation_source == {"file": str(Path(__file__).resolve()), "line": expected_line}+ assert "x-source-location" not in document["components"]["schemas"]["Synthetic"]+ assert namespace.models["NavigationPayload"].__schema__ == live_schema+ sources = registered_schema_sources(namespace)+ sources.clear()+ assert registered_schema_sources(namespace)["NavigationPayload"].endswith(".NavigationPayload")+++def test_exact_nested_and_generic_identities_resolve_without_name_guessing() -> None:+ assert resolve_source_type(f"{__name__}.Container.Nested") is Container.Nested+ assert resolve_source_type(f"{__name__}.Container.Nested[builtins.str]") is Container.Nested+ assert resolve_source_type("unknown.module.NavigationPayload") is None+ assert resolve_source_type(f"{__name__}.Missing.NavigationPayload") is None+ assert source_location(None) is None+ assert source_location(str) is Nonediff --git a/packages/contracts/api-documents.ts b/packages/contracts/api-documents.tsnew file mode 100644index 00000000000..0f95b924926--- /dev/null+++ b/packages/contracts/api-documents.ts@@ -0,0 +1,458 @@+type JsonObject = Record<string, unknown>++export type SwaggerSchema = JsonObject & {+ $ref?: string+}++type OpenApiMediaType = JsonObject & {+ schema?: SwaggerSchema+}++type OpenApiResponse = JsonObject & {+ content?: Record<string, OpenApiMediaType>+}++type OpenApiComponents = JsonObject & {+ schemas?: Record<string, SwaggerSchema>+}++export type SwaggerOperation = JsonObject & {+ operationId?: string+ responses?: Record<string, OpenApiResponse>+}++export type SwaggerDocument = JsonObject & {+ components?: OpenApiComponents+ openapi?: string+ paths?: Record<string, Record<string, unknown>>+}++export type ApiSpec = {+ filename: string+ name: string+}++type ApiContractOperation = {+ method: string+ path: string+}++export const operationMethods = new Set(['delete', 'get', 'patch', 'post', 'put'])+export const fastOpenApiConsoleSpecFilename = 'fastopenapi-console-openapi.json'+const fastOpenApiConsolePathPrefix = '/console/api'++export const apiSpecs: ApiSpec[] = [+ { filename: 'console-openapi.json', name: 'console' },+ { filename: 'web-openapi.json', name: 'web' },+ { filename: 'service-openapi.json', name: 'service' },+ { filename: 'openapi-openapi.json', name: 'openapi' },+]++export const isObject = (value: unknown): value is JsonObject => {+ return !!value && typeof value === 'object' && !Array.isArray(value)+}++const toWords = (value: string) => {+ return value+ .replace(/[{}]/g, '')+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .split(/[^a-z0-9]+/i)+ .filter(Boolean)+}++const toPascalCase = (words: string[]) => {+ return words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')+}++export const toCamelCase = (words: string[]) => {+ const pascal = toPascalCase(words)+ return `${pascal.charAt(0).toLowerCase()}${pascal.slice(1)}`+}++export const toKebabCase = (value: string) => {+ return toWords(value).join('-').toLowerCase()+}++export const segmentWords = (segment: string) => {+ if (segment.startsWith('{') && segment.endsWith('}')) return ['by', ...toWords(segment)]++ return toWords(segment)+}++// Split on `:` too so custom methods nest as their own node (apps.byAppId.run), not apps.appIdRun.+const routeNamingSegments = (routePath: string) => routePath.split(/[/:]/).filter(Boolean)++const routeWords = (routePath: string) => {+ return routeNamingSegments(routePath).flatMap(segmentWords)+}++const operationId = (method: string, routePath: string) => {+ return toCamelCase([+ method,+ ...(routeWords(routePath).length > 0 ? routeWords(routePath) : ['root']),+ ])+}++export const contractPathSegments = (operation: ApiContractOperation) => {+ const segments = routeNamingSegments(operation.path).map((segment) =>+ toCamelCase(segmentWords(segment)),+ )++ return [...(segments.length > 0 ? segments : ['root']), operation.method.toLowerCase()]+}++const clone = <T>(value: T): T => {+ return JSON.parse(JSON.stringify(value)) as T+}++const componentSchemaRefPrefix = '#/components/schemas/'++export const schemaNameFromRef = (ref: string) => {+ if (ref.startsWith(componentSchemaRefPrefix)) return ref.slice(componentSchemaRefPrefix.length)+ return undefined+}++export const getDocumentSchemas = (document: SwaggerDocument) => {+ const components = (document.components ??= {})+ return (components.schemas ??= {})+}++const collectSchemaRefs = (value: unknown, refs: Set<string>, visited = new WeakSet<object>()) => {+ if (!value || typeof value !== 'object') return++ if (visited.has(value)) return++ visited.add(value)++ if (Array.isArray(value)) {+ value.forEach((item) => collectSchemaRefs(item, refs, visited))+ return+ }++ const objectValue = value as JsonObject+ const ref = objectValue.$ref+ if (typeof ref === 'string') {+ const refName = schemaNameFromRef(ref)+ if (refName) refs.add(refName)+ }++ Object.values(objectValue).forEach((item) => collectSchemaRefs(item, refs, visited))+}++const addOperationIds = (document: SwaggerDocument) => {+ for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {+ for (const [method, operation] of Object.entries(pathItem)) {+ if (!operationMethods.has(method) || !isObject(operation)) continue++ const swaggerOperation = operation as SwaggerOperation+ swaggerOperation.operationId = operationId(method, routePath)+ }+ }+}++const normalizeOpaqueContractResponses = (document: SwaggerDocument) => {+ // This runs before contract filtering. Flask-RESTX often emits plain success responses+ // without a body schema; give those routes an opaque output so they stay in oRPC.+ for (const pathItem of Object.values(document.paths ?? {})) {+ for (const [method, operation] of Object.entries(pathItem)) {+ if (!operationMethods.has(method) || !isObject(operation)) continue++ const swaggerOperation = operation as SwaggerOperation+ for (const [status, response] of Object.entries(swaggerOperation.responses ?? {})) {+ // Ignore non-2xx or 204 or those w/o a response field+ if (!/^2\d\d$/.test(status) || status === '204' || !isObject(response)) continue++ const content = response.content+ if (!isObject(content) || Object.keys(content).length === 0) {+ // No response specification, fill a dummy opaque resp+ response.content = {+ 'application/json': {+ schema: {+ additionalProperties: true,+ type: 'object',+ },+ },+ }+ continue+ }++ for (const [mediaType, media] of Object.entries(content)) {+ if (mediaType !== 'application/json' && mediaType !== 'text/event-stream') continue+ if (!isObject(media) || isObject(media.schema)) continue++ // JSON/SSE media without a schema traps heyapi. Patch only that media entry so+ // sibling binary media keeps heyapi's Blob | File inference.+ // Still a dummy opaque resp+ media.schema = {+ additionalProperties: true,+ type: 'object',+ }+ }+ }+ }+ }+}++const hasSuccessResponse = (operation: SwaggerOperation) => {+ return Object.entries(operation.responses ?? {}).some(([status, response]) => {+ if (!/^2\d\d$/.test(status)) return false+ if (!isObject(response)) return false+ const content = (response as JsonObject).content+ // 204 No Content is a valid success response without a body+ if (!isObject(content) || Object.keys(content).length === 0) return status === '204'+ return true+ })+}++const filterContractOperations = (document: SwaggerDocument) => {+ for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {+ for (const [method, operation] of Object.entries(pathItem)) {+ if (!operationMethods.has(method) || !isObject(operation)) continue++ if (!hasSuccessResponse(operation as SwaggerOperation)) delete pathItem[method]+ }++ const hasOperations = Object.entries(pathItem).some(+ ([method, operation]) => operationMethods.has(method) && isObject(operation),+ )++ if (!hasOperations) delete document.paths?.[routePath]+ }+}++const includeMultipartRequestSchemas = (document: SwaggerDocument) => {+ for (const pathItem of Object.values(document.paths ?? {})) {+ for (const [method, operation] of Object.entries(pathItem)) {+ if (!operationMethods.has(method) || !isObject(operation) || !isObject(operation.requestBody))+ continue+ const content = operation.requestBody.content+ if (!isObject(content)) continue+ const json = content['application/json']+ const multipart = content['multipart/form-data']+ if (+ !isObject(json) ||+ !isObject(json.schema) ||+ !isObject(multipart) ||+ !isObject(multipart.schema)+ )+ continue++ // hey-api selects JSON for mixed request media; retain the multipart shape+ // so the generated client can serialize File values as FormData.+ json.schema = { anyOf: [json.schema, multipart.schema] }+ }+ }+}++const includeNonJsonResponseSchemas = (document: SwaggerDocument) => {+ for (const pathItem of Object.values(document.paths ?? {})) {+ for (const [method, operation] of Object.entries(pathItem)) {+ if (!operationMethods.has(method) || !isObject(operation)) continue++ for (const [status, response] of Object.entries(+ (operation as SwaggerOperation).responses ?? {},+ )) {+ if (!/^2\d\d$/.test(status) || !isObject(response) || !isObject(response.content)) continue++ const jsonMedia = response.content['application/json']+ if (!isObject(jsonMedia) || !isObject(jsonMedia.schema)) continue++ const alternatives: SwaggerSchema[] = []+ for (const [mediaType, media] of Object.entries(response.content)) {+ if (mediaType === 'application/json' || !isObject(media) || !isObject(media.schema))+ continue+ if (mediaType === 'text/event-stream' || media.schema.format === 'binary')+ alternatives.push(media.schema)+ }+ if (alternatives.length === 0) continue++ // hey-api selects the JSON schema when one status advertises multiple+ // response media types. Preserve SSE and binary transports in the generated+ // TypeScript and Zod contracts by making that selected schema a union.+ jsonMedia.schema = {+ anyOf: [jsonMedia.schema, ...alternatives],+ }+ }+ }+ }+}++const normalizeCodegenSchemas = (document: SwaggerDocument) => {+ const visitedSchemas = new WeakSet<object>()++ const visitSchema = (value: unknown) => {+ if (!isObject(value) || visitedSchemas.has(value)) return++ visitedSchemas.add(value)+ if (value.default === null) delete value.default+ // Dify serializes int64 fields as JSON numbers. hey-api maps int64 to+ // bigint in Zod, which disagrees with both the wire value and its own+ // generated TypeScript type. Keep int64 in the published OpenAPI specs,+ // but generate number-based client validators from this in-memory copy.+ if (value.type === 'integer' && value.format === 'int64') delete value.format++ for (const key of [+ 'additionalProperties',+ 'contains',+ 'else',+ 'if',+ 'items',+ 'not',+ 'propertyNames',+ 'then',+ 'unevaluatedItems',+ 'unevaluatedProperties',+ ]) {+ visitSchema(value[key])+ }++ for (const key of ['allOf', 'anyOf', 'oneOf', 'prefixItems']) {+ const schemas = value[key]+ if (Array.isArray(schemas)) schemas.forEach(visitSchema)+ }++ for (const key of [+ '$defs',+ 'definitions',+ 'dependentSchemas',+ 'patternProperties',+ 'properties',+ ]) {+ const schemas = value[key]+ if (isObject(schemas)) Object.values(schemas).forEach(visitSchema)+ }+ }++ const visitedDocumentObjects = new WeakSet<object>()+ const findSchemas = (value: unknown, parentKey?: string) => {+ if (!value || typeof value !== 'object' || visitedDocumentObjects.has(value)) return++ visitedDocumentObjects.add(value)+ if (parentKey === 'schema') {+ visitSchema(value)+ return+ }+ if (parentKey === 'schemas' && isObject(value)) {+ Object.values(value).forEach(visitSchema)+ return+ }+ if (parentKey === 'example' || parentKey === 'examples') return++ if (Array.isArray(value)) {+ value.forEach((item) => findSchemas(item))+ return+ }++ Object.entries(value).forEach(([key, item]) => findSchemas(item, key))+ }++ findSchemas(document)+}++export const normalizeApiSwagger = (document: SwaggerDocument) => {+ normalizeOpaqueContractResponses(document)+ filterContractOperations(document)+ addOperationIds(document)+ includeMultipartRequestSchemas(document)+ includeNonJsonResponseSchemas(document)+ // OpenAPI defaults describe server behavior. Keep them in the exported specs,+ // but do not let Zod synthesize omitted transport fields during client-side+ // request or response validation. Non-null defaults remain useful for query+ // parameter ergonomics and preserve the existing generated contract behavior.+ normalizeCodegenSchemas(document)++ return document+}++export const mergeFastOpenApiConsoleSwagger = (+ document: SwaggerDocument,+ fastOpenApiDocument: SwaggerDocument,+) => {+ const targetPaths = (document.paths ??= {})++ for (const [routePath, pathItem] of Object.entries(fastOpenApiDocument.paths ?? {})) {+ const contractPath = routePath.startsWith(fastOpenApiConsolePathPrefix)+ ? routePath.slice(fastOpenApiConsolePathPrefix.length) || '/'+ : routePath++ if (targetPaths[contractPath])+ throw new Error(`Duplicate console API path after FastOpenAPI merge: ${contractPath}`)++ targetPaths[contractPath] = pathItem+ }++ const targetSchemas = getDocumentSchemas(document)+ const sourceSchemas = getDocumentSchemas(fastOpenApiDocument)+ for (const [schemaName, schema] of Object.entries(sourceSchemas)) {+ if (targetSchemas[schemaName])+ throw new Error(`Duplicate console API schema after FastOpenAPI merge: ${schemaName}`)++ targetSchemas[schemaName] = schema+ }++ return document+}++export const topLevelPathSegment = (routePath: string) => {+ return routePath.split('/').filter(Boolean)[0] ?? 'root'+}++export const groupConsolePaths = (document: SwaggerDocument) => {+ const groups = new Map<string, Record<string, Record<string, unknown>>>()+ for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {+ const segment = topLevelPathSegment(routePath)+ const paths = groups.get(segment) ?? {}+ paths[routePath] = pathItem+ groups.set(segment, paths)+ }+ return groups+}++const selectReferencedSchemas = (+ schemas: Record<string, SwaggerSchema>,+ paths: Record<string, Record<string, unknown>>,+) => {+ const selectedSchemas: Record<string, SwaggerSchema> = {}+ const pendingRefs = new Set<string>()+ collectSchemaRefs(paths, pendingRefs)++ while (pendingRefs.size > 0) {+ const refName = pendingRefs.values().next().value+ if (!refName) break++ pendingRefs.delete(refName)++ if (selectedSchemas[refName]) continue++ const schema = schemas[refName]+ if (!schema) throw new Error(`Missing referenced schema: ${refName}`)++ selectedSchemas[refName] = schema++ const nestedRefs = new Set<string>()+ collectSchemaRefs(selectedSchemas[refName], nestedRefs)+ for (const nestedRef of nestedRefs) {+ if (!selectedSchemas[nestedRef]) pendingRefs.add(nestedRef)+ }+ }++ return selectedSchemas+}++export const cloneDocumentWithPaths = (+ document: SwaggerDocument,+ paths: Record<string, Record<string, unknown>>,+) => {+ const { components: _components, paths: _paths, ...metadata } = document+ const clonedPaths = clone(paths)+ const components = clone(document.components ?? {})+ const sourceSchemas = getDocumentSchemas(document)++ components.schemas = selectReferencedSchemas(sourceSchemas, clonedPaths)++ return {+ ...clone(metadata),+ components,+ paths: clonedPaths,+ } satisfies SwaggerDocument+}diff --git a/packages/contracts/compatibility-types.test.ts b/packages/contracts/compatibility-types.test.tsnew file mode 100644index 00000000000..9f24f8b3c6e--- /dev/null+++ b/packages/contracts/compatibility-types.test.ts@@ -0,0 +1,237 @@+import {+ existsSync,+ globSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs'+import { tmpdir } from 'node:os'+import { resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { describe, expect, it } from 'vite-plus/test'+import { normalizeApiSwagger } from './api-documents.ts'+import {+ renderCompatibilityTypes,+ selectCommunityDocument,+} from './scripts/export-compatibility-types.ts'+import { generateCompatibilitySources } from './scripts/generate-compatibility-sources.ts'++const root = import.meta.dirname++describe('compatible contracts exports', () => {+ it('keeps exact backend origins on renamed models and every operation envelope', async () => {+ const file = resolve(root, 'backend (models)*/models.py')+ const source = { file, line: 17 }+ const document = normalizeApiSwagger({+ openapi: '3.1.0',+ info: { title: 'Navigation', version: '1' },+ paths: {+ '/pets': {+ post: {+ 'x-source-location': { file, line: 42 },+ requestBody: {+ content: {+ 'application/json': { schema: { $ref: '#/components/schemas/pet-model' } },+ },+ },+ responses: {+ 200: {+ content: {+ 'application/json': { schema: { $ref: '#/components/schemas/pet-model' } },+ },+ },+ 400: { content: { 'application/json': { schema: { type: 'string' } } } },+ },+ },+ },+ },+ components: {+ schemas: {+ 'pet-model': { type: 'object', 'x-source-location': source },+ Missing: { type: 'string' },+ Relative: { type: 'string', 'x-source-location': { file: 'models.py', line: 1 } },+ Invalid: { type: 'string', 'x-source-location': { file, line: 0 } },+ },+ },+ })+ const output = await renderCompatibilityTypes(document)+ const href = pathToFileURL(file)+ .href.replaceAll('*', '%2A')+ .replaceAll('(', '%28')+ .replaceAll(')', '%29')+ expect(output).toContain(+ `/** [Open backend implementation](${href}#L17) */\nexport type PetModel`,+ )+ for (const suffix of ['Data', 'Responses', 'Response', 'Errors', 'Error'])+ expect(output).toContain(+ `/** [Open backend implementation](${href}#L42) */\nexport type PostPets${suffix} =`,+ )+ expect(output.match(/Open backend implementation/g)).toHaveLength(6)+ })++ it('generates subpath entries, preserves no-op mtimes and removes obsolete generated files', async () => {+ const directory = mkdtempSync(resolve(tmpdir(), 'dify-contracts-descriptors-'))+ try {+ const generated = resolve(directory, 'generated/api/console/new-feature')+ const descriptor = resolve(directory, 'mapper/console/new-feature.openapi-types')+ const declaration = resolve(directory, 'mapper/console/new-feature.d.ts')+ mkdirSync(generated, { recursive: true })+ writeFileSync(resolve(generated, 'types.gen.ts'), 'export type NewFeature = string')+ await generateCompatibilitySources(directory, resolve(directory, 'mapper'))+ expect(JSON.parse(readFileSync(descriptor, 'utf8')).args[0]).toBe('api/console/new-feature')+ expect(readFileSync(declaration, 'utf8')).toContain(+ "export type * from './new-feature.openapi-types'",+ )+ const files = [+ descriptor,+ resolve(directory, 'mapper/community.source.json'),+ resolve(directory, 'mapper/enterprise.source.json'),+ declaration,+ ]+ const timestamps = files.map((file) => statSync(file).mtimeMs)+ expect(readFileSync(files[1]!, 'utf8')).toContain(+ '"command": ["node", "packages/contracts/scripts/export-compatibility-types.ts"]',+ )+ await generateCompatibilitySources(directory, resolve(directory, 'mapper'))+ expect(files.map((file) => statSync(file).mtimeMs)).toEqual(timestamps)+ rmSync(resolve(generated, 'types.gen.ts'))+ await generateCompatibilitySources(directory, resolve(directory, 'mapper'))+ expect(existsSync(descriptor)).toBe(false)+ expect(existsSync(declaration)).toBe(false)+ } finally {+ rmSync(directory, { recursive: true, force: true })+ }+ })+ it('exposes all generated types through mapper subpaths with shared descriptors', () => {+ const mapper = resolve(root, '../openapi-content-mapper')+ const pkg = JSON.parse(readFileSync(resolve(mapper, 'package.json'), 'utf8'))+ const legacy = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'))+ expect(Object.keys(legacy.exports)).toEqual([+ './marketplace',+ './console',+ './api/*',+ './enterprise/*',+ './enterprise-app-deploy/*',+ ])+ const modules = globSync('generated/**/types.gen.ts', { cwd: root })+ expect(modules.length).toBeGreaterThan(50)+ for (const file of modules) {+ const module = file.slice('generated/'.length, -'/types.gen.ts'.length)+ const subpath = module.replace(/^api\//, '')+ const key = subpath.startsWith('console/') ? './console/*' : `./${subpath}`+ const entry = pkg.exports[key]+ expect(Object.keys(entry)).toEqual(['types'])+ const declarationPath = resolve(+ mapper,+ entry.types.replace('*', subpath.slice('console/'.length)),+ )+ expect(declarationPath).toMatch(/\.d\.ts$/)+ const descriptorPath = declarationPath.replace(/\.d\.ts$/, '.openapi-types')+ expect(readFileSync(declarationPath, 'utf8')).toContain(+ `export type * from './${subpath.split('/').at(-1)}.openapi-types'`,+ )+ const descriptor = JSON.parse(readFileSync(descriptorPath, 'utf8'))+ expect(Object.keys(descriptor)).toEqual(['extends', 'args'])+ expect(descriptor.args).toEqual([module])+ const base = JSON.parse(+ readFileSync(resolve(descriptorPath, '..', descriptor.extends), 'utf8'),+ )+ expect(base.command).toEqual([+ 'node',+ 'packages/contracts/scripts/export-compatibility-types.ts',+ ])+ // Repository-specific exports must not leak broken paths into the public SDK tarball.+ expect(pkg.publishConfig.exports[key]).toBeUndefined()+ }+ })++ it('automatically exports new models, legacy envelopes, status maps, unions and recursive schemas', async () => {+ const reference = { $ref: '#/components/schemas/Tree' }+ const document = normalizeApiSwagger({+ openapi: '3.1.0',+ info: { title: 'Compatibility', version: '1' },+ paths: {+ '/trees/{id}': {+ parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }],+ post: {+ requestBody: { required: true, content: { 'application/json': { schema: reference } } },+ responses: {+ 201: { content: { 'application/json': { schema: reference } } },+ 204: { description: 'Empty' },+ 409: {+ content: { 'application/json': { schema: { type: 'string', const: 'conflict' } } },+ },+ default: { content: { 'application/json': { schema: { type: 'string' } } } },+ },+ },+ },+ },+ components: {+ schemas: {+ Tree: {+ type: 'object',+ required: ['children'],+ properties: { children: { type: 'array', items: reference } },+ },+ },+ },+ })+ const output = await renderCompatibilityTypes(document)+ for (const name of [+ 'ClientOptions',+ 'Tree',+ 'PostTreesByIdData',+ 'PostTreesByIdResponses',+ 'PostTreesByIdResponse',+ 'PostTreesByIdErrors',+ 'PostTreesByIdError',+ ])+ expect(output).toContain(`export type ${name} =`)+ expect(output).toMatch(/path: \{\s*id: string;/)+ expect(output).toContain("url: '/trees/{id}'")+ expect(output).toContain('201: Tree')+ expect(output).toContain('204: void')+ expect(output).toContain("409: 'conflict'")+ expect(output).toContain('default: string')+ expect(output).toContain('children: Array<Tree>')+ expect(existsSync(resolve(root, '.compatibility-output'))).toBe(false)+ })++ it('shares Console normalization, FastOpenAPI merge and module splitting with code generation', () => {+ const documents = {+ 'console-openapi.json': {+ openapi: '3.1.0',+ paths: { '/pets': { get: { responses: { 200: { description: 'Opaque' } } } } },+ },+ 'fastopenapi-console-openapi.json': {+ openapi: '3.1.0',+ paths: {+ '/console/api/knowledge-fs/health': {+ get: { responses: { 204: { description: 'Healthy' } } },+ },+ },+ },+ }+ const pets = selectCommunityDocument('api/console/pets', documents)+ expect(Object.keys(pets.paths!)).toEqual(['/pets'])+ expect(pets.paths!['/pets']!.get).toMatchObject({+ operationId: 'getPets',+ responses: {+ 200: {+ content: {+ 'application/json': { schema: { type: 'object', additionalProperties: true } },+ },+ },+ },+ })+ const health = selectCommunityDocument('api/console/knowledge-fs', documents)+ expect(Object.keys(health.paths!)).toEqual(['/knowledge-fs/health'])+ expect(documents['console-openapi.json'].paths['/pets'].get).not.toHaveProperty('operationId')+ expect(() => selectCommunityDocument('api/console/missing', documents)).toThrow(+ 'No Console operations',+ )+ })+})diff --git a/packages/contracts/openapi-ts.api.config.ts b/packages/contracts/openapi-ts.api.config.tsindex 6fbe97775ad..3b2f0b83ae0 100644--- a/packages/contracts/openapi-ts.api.config.ts+++ b/packages/contracts/openapi-ts.api.config.ts@@ -1,43 +1,27 @@import type { DefinePlugin, UserConfig } from '@hey-api/openapi-ts'+import type { ApiSpec, SwaggerDocument, SwaggerOperation, SwaggerSchema } from './api-documents.ts'import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'import { $, defineConfig, definePluginConfig } from '@hey-api/openapi-ts'import ts from 'typescript'--type JsonObject = Record<string, unknown>--type SwaggerSchema = JsonObject & {- $ref?: string-}--type OpenApiMediaType = JsonObject & {- schema?: SwaggerSchema-}--type OpenApiResponse = JsonObject & {- content?: Record<string, OpenApiMediaType>-}--type OpenApiComponents = JsonObject & {- schemas?: Record<string, SwaggerSchema>-}--type SwaggerOperation = JsonObject & {- operationId?: string- responses?: Record<string, OpenApiResponse>-}--type SwaggerDocument = JsonObject & {- components?: OpenApiComponents- openapi?: string- paths?: Record<string, Record<string, unknown>>-}--type ApiSpec = {- filename: string- name: string-}+import {+ apiSpecs,+ cloneDocumentWithPaths,+ contractPathSegments,+ fastOpenApiConsoleSpecFilename,+ getDocumentSchemas,+ groupConsolePaths,+ isObject,+ mergeFastOpenApiConsoleSwagger,+ normalizeApiSwagger,+ operationMethods,+ schemaNameFromRef,+ segmentWords,+ toCamelCase,+ toKebabCase,+} from './api-documents.ts'+import { typescriptPlugin } from './typescript-generation.ts'type ApiJob = {document: SwaggerDocument@@ -51,15 +35,6 @@ type ApiJob = {}}-type ApiContractOperation = {- method: string- path: string-}--const currentDir = path.dirname(fileURLToPath(import.meta.url))-const apiOpenApiDir = path.resolve(currentDir, 'openapi')--const operationMethods = new Set(['delete', 'get', 'patch', 'post', 'put'])const strictZodSchemaNames = new Set(['AccountProfilePatchPayload','Parameters',@@ -72,68 +47,9 @@ const strictZodSchemaNames = new Set([])const pydanticDecimalStringPattern = '^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$'const codegenSafeDecimalStringPattern = '^(?![-+.]*$)[+-]?0*\\d*\\.?\\d*$'-const fastOpenApiConsoleSpecFilename = 'fastopenapi-console-openapi.json'-const fastOpenApiConsolePathPrefix = '/console/api'--const apiSpecs: ApiSpec[] = [- { filename: 'console-openapi.json', name: 'console' },- { filename: 'web-openapi.json', name: 'web' },- { filename: 'service-openapi.json', name: 'service' },- { filename: 'openapi-openapi.json', name: 'openapi' },-]--const isObject = (value: unknown): value is JsonObject => {- return !!value && typeof value === 'object' && !Array.isArray(value)-}-const toWords = (value: string) => {- return value- .replace(/[{}]/g, '')- .replace(/([a-z0-9])([A-Z])/g, '$1 $2')- .split(/[^a-z0-9]+/i)- .filter(Boolean)-}--const toPascalCase = (words: string[]) => {- return words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')-}--const toCamelCase = (words: string[]) => {- const pascal = toPascalCase(words)- return `${pascal.charAt(0).toLowerCase()}${pascal.slice(1)}`-}--const toKebabCase = (value: string) => {- return toWords(value).join('-').toLowerCase()-}--const segmentWords = (segment: string) => {- if (segment.startsWith('{') && segment.endsWith('}')) return ['by', ...toWords(segment)]-- return toWords(segment)-}--// Split on `:` too so custom methods nest as their own node (apps.byAppId.run), not apps.appIdRun.-const routeNamingSegments = (routePath: string) => routePath.split(/[/:]/).filter(Boolean)--const routeWords = (routePath: string) => {- return routeNamingSegments(routePath).flatMap(segmentWords)-}--const operationId = (method: string, routePath: string) => {- return toCamelCase([- method,- ...(routeWords(routePath).length > 0 ? routeWords(routePath) : ['root']),- ])-}--const contractPathSegments = (operation: ApiContractOperation) => {- const segments = routeNamingSegments(operation.path).map((segment) =>- toCamelCase(segmentWords(segment)),- )-- return [...(segments.length > 0 ? segments : ['root']), operation.method.toLowerCase()]-}+const currentDir = path.dirname(fileURLToPath(import.meta.url))+const apiOpenApiDir = path.resolve(currentDir, 'openapi')const readApiSwagger = (filename: string): SwaggerDocument => {const specPath = path.join(apiOpenApiDir, filename)@@ -151,349 +67,6 @@ const readApiSwagger = (filename: string): SwaggerDocument => {return rawSpec as SwaggerDocument}-const clone = <T>(value: T): T => {- return JSON.parse(JSON.stringify(value)) as T-}--const componentSchemaRefPrefix = '#/components/schemas/'--const schemaNameFromRef = (ref: string) => {- if (ref.startsWith(componentSchemaRefPrefix)) return ref.slice(componentSchemaRefPrefix.length)- return undefined-}--const getDocumentSchemas = (document: SwaggerDocument) => {- const components = (document.components ??= {})- return (components.schemas ??= {})-}--const collectSchemaRefs = (value: unknown, refs: Set<string>, visited = new WeakSet<object>()) => {- if (!value || typeof value !== 'object') return-- if (visited.has(value)) return-- visited.add(value)-- if (Array.isArray(value)) {- value.forEach((item) => collectSchemaRefs(item, refs, visited))- return- }-- const objectValue = value as JsonObject- const ref = objectValue.$ref- if (typeof ref === 'string') {- const refName = schemaNameFromRef(ref)- if (refName) refs.add(refName)- }-- Object.values(objectValue).forEach((item) => collectSchemaRefs(item, refs, visited))-}--const addOperationIds = (document: SwaggerDocument) => {- for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {- for (const [method, operation] of Object.entries(pathItem)) {- if (!operationMethods.has(method) || !isObject(operation)) continue-- const swaggerOperation = operation as SwaggerOperation- swaggerOperation.operationId = operationId(method, routePath)- }- }-}--const normalizeOpaqueContractResponses = (document: SwaggerDocument) => {- // This runs before contract filtering. Flask-RESTX often emits plain success responses- // without a body schema; give those routes an opaque output so they stay in oRPC.- for (const pathItem of Object.values(document.paths ?? {})) {- for (const [method, operation] of Object.entries(pathItem)) {- if (!operationMethods.has(method) || !isObject(operation)) continue-- const swaggerOperation = operation as SwaggerOperation- for (const [status, response] of Object.entries(swaggerOperation.responses ?? {})) {- // Ignore non-2xx or 204 or those w/o a response field- if (!/^2\d\d$/.test(status) || status === '204' || !isObject(response)) continue-- const content = response.content- if (!isObject(content) || Object.keys(content).length === 0) {- // No response specification, fill a dummy opaque resp- response.content = {- 'application/json': {- schema: {- additionalProperties: true,- type: 'object',- },- },- }- continue- }-- for (const [mediaType, media] of Object.entries(content)) {- if (mediaType !== 'application/json' && mediaType !== 'text/event-stream') continue- if (!isObject(media) || isObject(media.schema)) continue-- // JSON/SSE media without a schema traps heyapi. Patch only that media entry so- // sibling binary media keeps heyapi's Blob | File inference.- // Still a dummy opaque resp- media.schema = {- additionalProperties: true,- type: 'object',- }- }- }- }- }-}--const hasSuccessResponse = (operation: SwaggerOperation) => {- return Object.entries(operation.responses ?? {}).some(([status, response]) => {- if (!/^2\d\d$/.test(status)) return false- if (!isObject(response)) return false- const content = (response as JsonObject).content- // 204 No Content is a valid success response without a body- if (!isObject(content) || Object.keys(content).length === 0) return status === '204'- return true- })-}--const filterContractOperations = (document: SwaggerDocument) => {- for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {- for (const [method, operation] of Object.entries(pathItem)) {- if (!operationMethods.has(method) || !isObject(operation)) continue-- if (!hasSuccessResponse(operation as SwaggerOperation)) delete pathItem[method]- }-- const hasOperations = Object.entries(pathItem).some(- ([method, operation]) => operationMethods.has(method) && isObject(operation),- )-- if (!hasOperations) delete document.paths?.[routePath]- }-}--const includeMultipartRequestSchemas = (document: SwaggerDocument) => {- for (const pathItem of Object.values(document.paths ?? {})) {- for (const [method, operation] of Object.entries(pathItem)) {- if (!operationMethods.has(method) || !isObject(operation) || !isObject(operation.requestBody))- continue- const content = operation.requestBody.content- if (!isObject(content)) continue- const json = content['application/json']- const multipart = content['multipart/form-data']- if (- !isObject(json) ||- !isObject(json.schema) ||- !isObject(multipart) ||- !isObject(multipart.schema)- )- continue-- // hey-api selects JSON for mixed request media; retain the multipart shape- // so the generated client can serialize File values as FormData.- json.schema = { anyOf: [json.schema, multipart.schema] }- }- }-}--const includeNonJsonResponseSchemas = (document: SwaggerDocument) => {- for (const pathItem of Object.values(document.paths ?? {})) {- for (const [method, operation] of Object.entries(pathItem)) {- if (!operationMethods.has(method) || !isObject(operation)) continue-- for (const [status, response] of Object.entries(- (operation as SwaggerOperation).responses ?? {},- )) {- if (!/^2\d\d$/.test(status) || !isObject(response) || !isObject(response.content)) continue-- const jsonMedia = response.content['application/json']- if (!isObject(jsonMedia) || !isObject(jsonMedia.schema)) continue-- const alternatives: SwaggerSchema[] = []- for (const [mediaType, media] of Object.entries(response.content)) {- if (mediaType === 'application/json' || !isObject(media) || !isObject(media.schema))- continue- if (mediaType === 'text/event-stream' || media.schema.format === 'binary')- alternatives.push(media.schema)- }- if (alternatives.length === 0) continue-- // hey-api selects the JSON schema when one status advertises multiple- // response media types. Preserve SSE and binary transports in the generated- // TypeScript and Zod contracts by making that selected schema a union.- jsonMedia.schema = {- anyOf: [jsonMedia.schema, ...alternatives],- }- }- }- }-}--const normalizeCodegenSchemas = (document: SwaggerDocument) => {- const visitedSchemas = new WeakSet<object>()-- const visitSchema = (value: unknown) => {- if (!isObject(value) || visitedSchemas.has(value)) return-- visitedSchemas.add(value)- if (value.default === null) delete value.default- // Dify serializes int64 fields as JSON numbers. hey-api maps int64 to- // bigint in Zod, which disagrees with both the wire value and its own- // generated TypeScript type. Keep int64 in the published OpenAPI specs,- // but generate number-based client validators from this in-memory copy.- if (value.type === 'integer' && value.format === 'int64') delete value.format-- for (const key of [- 'additionalProperties',- 'contains',- 'else',- 'if',- 'items',- 'not',- 'propertyNames',- 'then',- 'unevaluatedItems',- 'unevaluatedProperties',- ]) {- visitSchema(value[key])- }-- for (const key of ['allOf', 'anyOf', 'oneOf', 'prefixItems']) {- const schemas = value[key]- if (Array.isArray(schemas)) schemas.forEach(visitSchema)- }-- for (const key of [- '$defs',- 'definitions',- 'dependentSchemas',- 'patternProperties',- 'properties',- ]) {- const schemas = value[key]- if (isObject(schemas)) Object.values(schemas).forEach(visitSchema)- }- }-- const visitedDocumentObjects = new WeakSet<object>()- const findSchemas = (value: unknown, parentKey?: string) => {- if (!value || typeof value !== 'object' || visitedDocumentObjects.has(value)) return-- visitedDocumentObjects.add(value)- if (parentKey === 'schema') {- visitSchema(value)- return- }- if (parentKey === 'schemas' && isObject(value)) {- Object.values(value).forEach(visitSchema)- return- }- if (parentKey === 'example' || parentKey === 'examples') return-- if (Array.isArray(value)) {- value.forEach((item) => findSchemas(item))- return- }-- Object.entries(value).forEach(([key, item]) => findSchemas(item, key))- }-- findSchemas(document)-}--const normalizeApiSwagger = (document: SwaggerDocument) => {- normalizeOpaqueContractResponses(document)- filterContractOperations(document)- addOperationIds(document)- includeMultipartRequestSchemas(document)- includeNonJsonResponseSchemas(document)- // OpenAPI defaults describe server behavior. Keep them in the exported specs,- // but do not let Zod synthesize omitted transport fields during client-side- // request or response validation. Non-null defaults remain useful for query- // parameter ergonomics and preserve the existing generated contract behavior.- normalizeCodegenSchemas(document)-- return document-}--const mergeFastOpenApiConsoleSwagger = (document: SwaggerDocument) => {- const fastOpenApiDocument = readApiSwagger(fastOpenApiConsoleSpecFilename)- const targetPaths = (document.paths ??= {})-- for (const [routePath, pathItem] of Object.entries(fastOpenApiDocument.paths ?? {})) {- const contractPath = routePath.startsWith(fastOpenApiConsolePathPrefix)- ? routePath.slice(fastOpenApiConsolePathPrefix.length) || '/'- : routePath-- if (targetPaths[contractPath])- throw new Error(`Duplicate console API path after FastOpenAPI merge: ${contractPath}`)-- targetPaths[contractPath] = pathItem- }-- const targetSchemas = getDocumentSchemas(document)- const sourceSchemas = getDocumentSchemas(fastOpenApiDocument)- for (const [schemaName, schema] of Object.entries(sourceSchemas)) {- if (targetSchemas[schemaName])- throw new Error(`Duplicate console API schema after FastOpenAPI merge: ${schemaName}`)-- targetSchemas[schemaName] = schema- }-- return document-}--const topLevelPathSegment = (routePath: string) => {- return routePath.split('/').filter(Boolean)[0] ?? 'root'-}--const selectReferencedSchemas = (- schemas: Record<string, SwaggerSchema>,- paths: Record<string, Record<string, unknown>>,-) => {- const selectedSchemas: Record<string, SwaggerSchema> = {}- const pendingRefs = new Set<string>()- collectSchemaRefs(paths, pendingRefs)-- while (pendingRefs.size > 0) {- const refName = pendingRefs.values().next().value- if (!refName) break-- pendingRefs.delete(refName)-- if (selectedSchemas[refName]) continue-- const schema = schemas[refName]- if (!schema) throw new Error(`Missing referenced schema: ${refName}`)-- selectedSchemas[refName] = schema-- const nestedRefs = new Set<string>()- collectSchemaRefs(selectedSchemas[refName], nestedRefs)- for (const nestedRef of nestedRefs) {- if (!selectedSchemas[nestedRef]) pendingRefs.add(nestedRef)- }- }-- return selectedSchemas-}--const cloneDocumentWithPaths = (- document: SwaggerDocument,- paths: Record<string, Record<string, unknown>>,-) => {- const { components: _components, paths: _paths, ...metadata } = document- const clonedPaths = clone(paths)- const components = clone(document.components ?? {})- const sourceSchemas = getDocumentSchemas(document)-- components.schemas = selectReferencedSchemas(sourceSchemas, clonedPaths)-- return {- ...clone(metadata),- components,- paths: clonedPaths,- } satisfies SwaggerDocument-}-const consoleContractEntryContent = (segments: string[]) => {const contracts = segments.map((segment) => {return {@@ -587,15 +160,7 @@ const createConsoleContractEntryJob = (document: SwaggerDocument, segments: stri}const splitConsoleDocument = (document: SwaggerDocument) => {- const pathsBySegment = new Map<string, Record<string, Record<string, unknown>>>()-- for (const [routePath, pathItem] of Object.entries(document.paths ?? {})) {- const segment = topLevelPathSegment(routePath)- const paths = pathsBySegment.get(segment) ?? {}- paths[routePath] = pathItem- pathsBySegment.set(segment, paths)- }-+ const pathsBySegment = groupConsolePaths(document)const segments = [...pathsBySegment.keys()].sort((left, right) => left.localeCompare(right))const jobs = segments.map((segment): ApiJob => ({document: cloneDocumentWithPaths(document, pathsBySegment.get(segment) ?? {}),@@ -608,7 +173,10 @@ const splitConsoleDocument = (document: SwaggerDocument) => {const createApiJobs = (spec: ApiSpec): ApiJob[] => {const document = normalizeApiSwagger(spec.name === 'console'- ? mergeFastOpenApiConsoleSwagger(readApiSwagger(spec.filename))+ ? mergeFastOpenApiConsoleSwagger(+ readApiSwagger(spec.filename),+ readApiSwagger(fastOpenApiConsoleSpecFilename),+ ): readApiSwagger(spec.filename),)@@ -717,10 +285,7 @@ const createApiConfig = (job: ApiJob): UserConfig => ({...(job.source ? { source: job.source } : {}),},plugins: job.plugins ?? [- {- comments: false,- name: '@hey-api/typescript',- },+ typescriptPlugin(),{name: 'zod','~resolvers': {diff --git a/packages/contracts/openapi-ts.enterprise-app-deploy.config.ts b/packages/contracts/openapi-ts.enterprise-app-deploy.config.tsindex 8d4bac6f3b0..636a4748bf9 100644--- a/packages/contracts/openapi-ts.enterprise-app-deploy.config.ts+++ b/packages/contracts/openapi-ts.enterprise-app-deploy.config.ts@@ -3,6 +3,7 @@ import path from 'node:path'import { fileURLToPath } from 'node:url'import { defineConfig } from '@hey-api/openapi-ts'import { loadOpenApiYaml } from './openapi-yaml.ts'+import { stripEnterpriseSchemaNamePrefix, typescriptPlugin } from './typescript-generation.ts'type JsonObject = Record<string, unknown>@@ -78,14 +79,6 @@ const stripConsoleApiPrefix = (routePath: string) => {return routePath}-const stripSchemaNamePrefix = (schemaName: string) => {- return schemaName- .replace(/^dify\.enterprise\.api\.enterprise\./, '')- .replace(/^dify\.enterprise\.api\.appdeploy\.v1\./, '')- .replace(/^dify\.enterprise\.api\.appdeploy\./, '')- .replace(/^pagination\./, '')-}-const contractTagSegment = (tag?: string) => {if (tag === 'ConsoleDeploymentService') return 'DeploymentService'if (tag === 'ConsoleAccessService') return 'AccessService'@@ -173,7 +166,9 @@ const findSchemaEntry = (schemas: Record<string, OpenApiSchema>,schemaName: string,): [string, OpenApiSchema] | undefined => {- return Object.entries(schemas).find(([name]) => stripSchemaNamePrefix(name) === schemaName)+ return Object.entries(schemas).find(+ ([name]) => stripEnterpriseSchemaNamePrefix(name) === schemaName,+ )}const enumValuesKey = (values: unknown[]) => JSON.stringify(values)@@ -202,7 +197,7 @@ const enumSchemaKey = (if (Array.isArray(existingEnumValues) && enumValuesKey(existingEnumValues) === valuesKey)return existingEnumEntry[0]- return `${stripSchemaNamePrefix(schemaName)}${toPascalCase(toWords(propertyName))}`+ return `${stripEnterpriseSchemaNamePrefix(schemaName)}${toPascalCase(toWords(propertyName))}`}const promoteInlineEnumSchema = (@@ -309,17 +304,11 @@ export default defineConfig({},parser: {transforms: {- schemaName: stripSchemaNamePrefix,+ schemaName: stripEnterpriseSchemaNamePrefix,},},plugins: [- {- name: '@hey-api/typescript',- comments: false,- enums: {- mode: 'javascript',- },- },+ typescriptPlugin(true),'zod',{name: 'orpc',diff --git a/packages/contracts/openapi-ts.enterprise.config.ts b/packages/contracts/openapi-ts.enterprise.config.tsindex aa57fedfe88..da9dc942fc7 100644--- a/packages/contracts/openapi-ts.enterprise.config.ts+++ b/packages/contracts/openapi-ts.enterprise.config.ts@@ -3,6 +3,7 @@ import path from 'node:path'import { fileURLToPath } from 'node:url'import { defineConfig } from '@hey-api/openapi-ts'import { loadOpenApiYaml } from './openapi-yaml.ts'+import { stripEnterpriseSchemaNamePrefix, typescriptPlugin } from './typescript-generation.ts'type JsonObject = Record<string, unknown>@@ -78,14 +79,6 @@ const stripConsoleApiPrefix = (routePath: string) => {return routePath}-const stripSchemaNamePrefix = (schemaName: string) => {- return schemaName- .replace(/^dify\.enterprise\.api\.enterprise\./, '')- .replace(/^dify\.enterprise\.api\.appdeploy\.v1\./, '')- .replace(/^dify\.enterprise\.api\.appdeploy\./, '')- .replace(/^pagination\./, '')-}-const contractTagSegment = (tag?: string) => {if (tag === 'EnterpriseAppDeployConsole') return 'AppDeploy'@@ -172,7 +165,9 @@ const findSchemaEntry = (schemas: Record<string, OpenApiSchema>,schemaName: string,): [string, OpenApiSchema] | undefined => {- return Object.entries(schemas).find(([name]) => stripSchemaNamePrefix(name) === schemaName)+ return Object.entries(schemas).find(+ ([name]) => stripEnterpriseSchemaNamePrefix(name) === schemaName,+ )}const enumValuesKey = (values: unknown[]) => JSON.stringify(values)@@ -201,7 +196,7 @@ const enumSchemaKey = (if (Array.isArray(existingEnumValues) && enumValuesKey(existingEnumValues) === valuesKey)return existingEnumEntry[0]- return `${stripSchemaNamePrefix(schemaName)}${toPascalCase(toWords(propertyName))}`+ return `${stripEnterpriseSchemaNamePrefix(schemaName)}${toPascalCase(toWords(propertyName))}`}const promoteInlineEnumSchema = (@@ -308,17 +303,11 @@ export default defineConfig({},parser: {transforms: {- schemaName: stripSchemaNamePrefix,+ schemaName: stripEnterpriseSchemaNamePrefix,},},plugins: [- {- name: '@hey-api/typescript',- comments: false,- enums: {- mode: 'javascript',- },- },+ typescriptPlugin(true),'zod',{name: 'orpc',diff --git a/packages/contracts/package.json b/packages/contracts/package.jsonindex 1982cde21a4..962235c12b7 100644--- a/packages/contracts/package.json+++ b/packages/contracts/package.json@@ -26,12 +26,13 @@}},"scripts": {- "gen-api-contract": "uv run --project ../../api ../../api/dev/generate_swagger_specs.py --output-dir openapi && uv run --project ../../api ../../api/dev/generate_fastopenapi_specs.py --output-dir openapi && node -e \"if (process.env.CI) fs.rmSync('generated/api', { recursive: true, force: true })\" && openapi-ts -f openapi-ts.api.config.ts && node scripts/add-orpc-error-maps.ts && vp fmt generated/api",- "gen-enterprise-contract": "openapi-ts -f openapi-ts.enterprise.config.ts && node scripts/snapshot-enterprise-openapi.ts enterprise",- "gen-enterprise-app-deploy-contract": "openapi-ts -f openapi-ts.enterprise-app-deploy.config.ts && node scripts/snapshot-enterprise-openapi.ts enterprise-app-deploy",+ "gen-api-contract": "uv run --frozen --project ../../api ../../api/dev/generate_swagger_specs.py --output-dir openapi && uv run --frozen --project ../../api ../../api/dev/generate_fastopenapi_specs.py --output-dir openapi && node -e \"if (process.env.CI) fs.rmSync('generated/api', { recursive: true, force: true })\" && openapi-ts -f openapi-ts.api.config.ts && node scripts/add-orpc-error-maps.ts && vp fmt generated/api && node scripts/generate-compatibility-sources.ts",+ "gen-enterprise-contract": "openapi-ts -f openapi-ts.enterprise.config.ts && node scripts/snapshot-enterprise-openapi.ts enterprise && node scripts/generate-compatibility-sources.ts",+ "gen-enterprise-app-deploy-contract": "openapi-ts -f openapi-ts.enterprise-app-deploy.config.ts && node scripts/snapshot-enterprise-openapi.ts enterprise-app-deploy && node scripts/generate-compatibility-sources.ts","test": "vp test","type-check": "tsrs --noEmit",- "compose:console": "node scripts/compose-console-openapi.mjs"+ "compose:console": "node scripts/compose-console-openapi.mjs",+ "gen-compatibility-sources": "node scripts/generate-compatibility-sources.ts"},"dependencies": {"@orpc/contract": "catalog:",diff --git a/packages/contracts/scripts/compose-console-openapi.mjs b/packages/contracts/scripts/compose-console-openapi.mjsindex f797b488cee..dca627991ab 100644--- a/packages/contracts/scripts/compose-console-openapi.mjs+++ b/packages/contracts/scripts/compose-console-openapi.mjs@@ -64,12 +64,16 @@ export function composeConsoleDocuments(sources) {export function loadConsoleDocument(root = resolve(import.meta.dirname, '..')) {const community = JSON.parse(- execFileSync('uv', ['run', '--project', 'api', 'api/dev/cached_console_openapi.py'], {- cwd: resolve(root, '../..'),- encoding: 'utf8',- maxBuffer: 64 * 1024 * 1024,- timeout: 100000,- }),+ execFileSync(+ 'uv',+ ['run', '--frozen', '--project', 'api', 'api/dev/cached_console_openapi.py'],+ {+ cwd: resolve(root, '../..'),+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ timeout: 100000,+ },+ ),)const snapshots = [['enterprise', 'generated/enterprise/openapi.gen.json'],diff --git a/packages/contracts/scripts/export-compatibility-types.ts b/packages/contracts/scripts/export-compatibility-types.tsnew file mode 100644index 00000000000..79946b9cb1a--- /dev/null+++ b/packages/contracts/scripts/export-compatibility-types.ts@@ -0,0 +1,176 @@+import type { UserConfig } from '@hey-api/openapi-ts'+import type { SwaggerDocument } from '../api-documents.ts'+import { execFileSync } from 'node:child_process'+import { readFileSync, statSync } from 'node:fs'+import { isAbsolute, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { createClient } from '@hey-api/openapi-ts'+import {+ cloneDocumentWithPaths,+ groupConsolePaths,+ mergeFastOpenApiConsoleSwagger,+ normalizeApiSwagger,+ toKebabCase,+} from '../api-documents.ts'+import { stripEnterpriseSchemaNamePrefix, typescriptPlugin } from '../typescript-generation.ts'++const root = resolve(import.meta.dirname, '..')+const repo = resolve(root, '../..')++/** Use the same TypeScript plugin as normal generation, without writing any artifacts. */+export async function renderCompatibilityTypes(+ document: SwaggerDocument,+ enterprise = false,+): Promise<string> {+ const config: UserConfig = {+ input: document,+ dryRun: true,+ logs: { level: 'silent', file: false },+ output: {+ path: resolve(root, '.compatibility-output'),+ // Hey API's clean step runs even in dry-run mode.+ clean: false,+ entryFile: false,+ fileName: { suffix: '.gen' },+ },+ ...(enterprise+ ? {+ parser: {+ transforms: {+ schemaName: stripEnterpriseSchemaNamePrefix,+ },+ },+ }+ : {}),+ plugins: [typescriptPlugin(enterprise)],+ }+ const [context] = await createClient(config)+ const files = context?.gen.render() ?? []+ const file = files.find((file) => file.path.endsWith('/types.gen.ts'))+ if (!file || files.length !== 1)+ throw new Error('Expected one generated compatibility types module')+ const origins = new Map<string, string>()+ for (const symbol of context!.gen.symbols.registered()) {+ const path = symbol.meta?.path+ if (!Array.isArray(path)) continue+ let node: unknown = document+ for (const part of path) {+ node =+ node && typeof node === 'object'+ ? (node as Record<string, unknown>)[String(part)]+ : undefined+ }+ if (!node || typeof node !== 'object') continue+ const source = (node as Record<string, unknown>)['x-source-location'] as+ | { file?: unknown; line?: unknown }+ | undefined+ if (+ !source ||+ typeof source.file !== 'string' ||+ !isAbsolute(source.file) ||+ typeof source.line !== 'number' ||+ !Number.isSafeInteger(source.line) ||+ source.line < 1+ )+ continue+ const url = pathToFileURL(source.file)+ url.hash = `L${source.line}`+ const href = url.href.replaceAll('*', '%2A').replaceAll('(', '%28').replaceAll(')', '%29')+ origins.set(symbol.finalName, `/** [Open backend implementation](${href}) */\n`)+ }+ // Use the generator's resolved symbols, including renamed schemas and envelopes.+ // Normal contracts generation stays unchanged; only virtual exports get links.+ return file.content.replace(+ /^export (?:type|interface|const|enum) (\w+)/gm,+ (declaration, name: string) => `${origins.get(name) ?? ''}${declaration}`,+ )+}++export function selectCommunityDocument(+ module: string,+ documents: Record<string, SwaggerDocument>,+): SwaggerDocument {+ const [, surface, segment] = module.split('/')+ const input = documents[`${surface}-openapi.json`]+ if (!input) throw new Error(`Unknown contracts surface: ${surface}`)+ const document = normalizeApiSwagger(+ surface === 'console'+ ? mergeFastOpenApiConsoleSwagger(+ structuredClone(input),+ structuredClone(documents['fastopenapi-console-openapi.json']!),+ )+ : structuredClone(input),+ )+ if (surface !== 'console') return document+ const paths: NonNullable<SwaggerDocument['paths']> = {}+ for (const [name, group] of groupConsolePaths(document)) {+ if (toKebabCase(name) === segment) Object.assign(paths, group)+ }+ if (!Object.keys(paths).length) throw new Error(`No Console operations for ${module}`)+ return cloneDocumentWithPaths(document, paths)+}++function exportPython(args: string[]): Record<string, SwaggerDocument> {+ return JSON.parse(+ execFileSync('uv', ['run', '--frozen', '--project', 'api', ...args], {+ cwd: repo,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ timeout: 90000,+ stdio: ['ignore', 'pipe', 'pipe'],+ }),+ )+}++export function loadCommunityDocuments(consoleOnly: boolean): Record<string, SwaggerDocument> {+ if (consoleOnly) {+ const exported = exportPython(['api/dev/cached_console_openapi.py'])+ return {+ 'console-openapi.json': exported.console!,+ 'fastopenapi-console-openapi.json': exported.fast!,+ }+ }+ return exportPython([+ 'python',+ '-c',+ [+ 'import contextlib, json, sys',+ 'sys.path.insert(0, "api")',+ 'with contextlib.redirect_stdout(sys.stderr):',+ ' from dev.cached_console_openapi import source_imports',+ ' source_imports()',+ ' from dev.export_console_openapi import export_all_with_sources',+ ' documents = export_all_with_sources()',+ 'json.dump(documents, sys.stdout)',+ ].join('\n'),+ ])+}++export async function exportCompatibilityTypes(module: string): Promise<string> {+ // Only existing published modules are accepted; module names cannot escape generated/.+ if (+ !/^(?:api\/(?:console\/[a-z0-9-]+|web|service|openapi)|enterprise(?:-app-deploy)?)$/.test(+ module,+ )+ )+ throw new Error(`Invalid contracts module: ${module}`)+ const original = resolve(root, 'generated', module, 'types.gen.ts')+ if (!statSync(original).isFile()) throw new Error(`Missing contracts module: ${module}`)+ if (module.startsWith('enterprise')) {+ const document: SwaggerDocument = JSON.parse(+ readFileSync(resolve(root, 'generated', module, 'openapi.gen.json'), 'utf8'),+ )+ const generated = await renderCompatibilityTypes(document, true)+ // Retained Console snapshots omit non-Console models. Preserve their existing+ // exports (including enum values) instead of silently dropping public names.+ return `${generated}\nexport * from ${JSON.stringify(original.replace(/\.ts$/, '.js'))};\n`+ }+ const documents = loadCommunityDocuments(module.startsWith('api/console/'))+ return renderCompatibilityTypes(selectCommunityDocument(module, documents))+}++if (import.meta.main) {+ const module = process.argv[2]+ if (!module) throw new Error('Expected a contracts module, such as api/console/datasets')+ process.stdout.write(JSON.stringify({ typescript: await exportCompatibilityTypes(module) }))+}diff --git a/packages/contracts/scripts/generate-compatibility-sources.ts b/packages/contracts/scripts/generate-compatibility-sources.tsnew file mode 100644index 00000000000..caf34c5974a--- /dev/null+++ b/packages/contracts/scripts/generate-compatibility-sources.ts@@ -0,0 +1,105 @@+import { existsSync, globSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { basename, dirname, relative, resolve } from 'node:path'+import { format } from 'vite-plus/fmt'++const declarationHeader = '// Generated by @dify/contracts gen-compatibility-sources.\n'++function writeIfChanged(file: string, content: string) {+ mkdirSync(dirname(file), { recursive: true })+ const existing = existsSync(file) ? readFileSync(file, 'utf8') : undefined+ // No-op generation must not restart the language server.+ if (existing !== content) writeFileSync(file, content)+}++async function writeDescriptor(file: string, value: unknown) {+ let content = `${JSON.stringify(value, null, 2)}\n`+ if (file.endsWith('.json')) {+ const formatted = await format(file, content)+ if (formatted.errors.length) throw new Error(`Failed to format ${file}`)+ content = formatted.code+ }+ writeIfChanged(file, content)+}++/** Thin mapper subpaths share one exporter configuration per backend source. */+export async function generateCompatibilitySources(+ root = resolve(import.meta.dirname, '..'),+ output = resolve(root, '../openapi-content-mapper/contracts'),+) {+ const repo = resolve(root, '../..')+ const sharedSources = {+ community: resolve(output, 'community.source.json'),+ enterprise: resolve(output, 'enterprise.source.json'),+ }+ for (const [name, file] of Object.entries(sharedSources)) {+ const enterprise = name === 'enterprise'+ await writeDescriptor(file, {+ command: ['node', 'packages/contracts/scripts/export-compatibility-types.ts'],+ cwd: relative(output, repo),+ inputs: [+ 'packages/contracts/api-documents.ts',+ 'packages/contracts/typescript-generation.ts',+ 'packages/contracts/scripts/export-compatibility-types.ts',+ 'packages/contracts/package.json',+ 'pnpm-lock.yaml',+ ...(enterprise+ ? [+ 'packages/contracts/generated/enterprise*/types.gen.ts',+ 'packages/contracts/generated/enterprise*/openapi.gen.json',+ ]+ : [+ 'packages/contracts/generated/api/**/types.gen.ts',+ 'api/**/*.py',+ 'dify-agent/src/**/*.py',+ 'dify-agent/pyproject.toml',+ 'api/pyproject.toml',+ 'api/uv.lock',+ ]),+ ],+ ...(enterprise+ ? {}+ : {+ env: ['UV_PROJECT_ENVIRONMENT'],+ exclude: ['api/tests/**'],+ optionalInputs: ['.env'],+ }),+ timeoutMs: 120000,+ })+ }+ const modules = globSync('generated/**/types.gen.ts', { cwd: root }).sort()+ const expected = new Set<string>()+ for (const entry of modules) {+ const module = entry.slice('generated/'.length, -'/types.gen.ts'.length)+ const subpath = module.replace(/^api\//, '')+ const file = resolve(output, `${subpath}.openapi-types`)+ expected.add(file)+ const declaration = resolve(output, `${subpath}.d.ts`)+ expected.add(declaration)+ // A native declaration entry avoids TS 7's missing-declaration hint for+ // package exports targeting custom extensions. Types still come from the mapper.+ writeIfChanged(declaration, `${declarationHeader}export type * from './${basename(file)}'\n`)+ await writeDescriptor(file, {+ extends: relative(+ dirname(file),+ sharedSources[module.startsWith('enterprise') ? 'enterprise' : 'community'],+ ),+ args: [module],+ })+ }+ for (const entry of globSync('**/*.openapi-types', { cwd: output })) {+ const file = resolve(output, entry)+ if (!expected.has(file)) {+ const descriptor = JSON.parse(readFileSync(file, 'utf8'))+ if (Object.values(sharedSources).includes(resolve(dirname(file), descriptor.extends ?? '')))+ rmSync(file)+ }+ }+ for (const entry of globSync('**/*.d.ts', { cwd: output })) {+ const file = resolve(output, entry)+ if (!expected.has(file) && readFileSync(file, 'utf8').startsWith(declarationHeader))+ rmSync(file)+ }+ return modules+}++if (import.meta.main) await generateCompatibilitySources()diff --git a/packages/contracts/typescript-generation.ts b/packages/contracts/typescript-generation.tsnew file mode 100644index 00000000000..8cf5f19d7b6--- /dev/null+++ b/packages/contracts/typescript-generation.ts@@ -0,0 +1,13 @@+/** Shared by contract generation and the mapper's in-memory type exporter. */+export const typescriptPlugin = (enterprise = false) => ({+ name: '@hey-api/typescript' as const,+ comments: false,+ ...(enterprise ? { enums: { mode: 'javascript' as const } } : {}),+})++export const stripEnterpriseSchemaNamePrefix = (name: string) =>+ name+ .replace(/^dify\.enterprise\.api\.enterprise\./, '')+ .replace(/^dify\.enterprise\.api\.appdeploy\.v1\./, '')+ .replace(/^dify\.enterprise\.api\.appdeploy\./, '')+ .replace(/^pagination\./, '')diff --git a/packages/openapi-content-mapper/README.md b/packages/openapi-content-mapper/README.mdindex 93d0a20c7a3..b33c5d06be9 100644--- a/packages/openapi-content-mapper/README.md+++ b/packages/openapi-content-mapper/README.md@@ -196,7 +196,9 @@ model dependencies preloaded. Changing a preloaded dependency, adding/removing aPython file, changing `.env`, or changing the environment invalidates that state.Python bytecode caches are bypassed to handle rapid same-size edits. Export errorsare surfaced rather than serving the old contract. Refreshes interrupted by more-source edits are retried. Backend tests are excluded from Console source inputs.+source edits are retried. Console and Community type descriptors track Python+sources in `api/` and the editable `dify-agent/src/` dependency, together with their+package configuration. Backend tests are excluded from Console source inputs.Native threads are checked before forking; unsafe snapshots and platforms withoutfork use a fresh-process export instead. Those refreshes still incur cold startup.@@ -236,7 +238,7 @@ live API schemas and retained Enterprise snapshots are unchanged.## API and transport-Documents export only `api` and `query`; operation IDs are not exports. `/pets/{petId}` becomes `pets.byPetId`, hyphenated segments become camelCase and HTTP methods are leaf functions. Colon actions such as `/chat:run` become `chat.run`. `key` is reserved as a route segment for query helpers. Unresolvable member collisions fail during compilation.+Documents export `api` and `query` at runtime, plus the type-only `Schemas`, `Inputs` and `Outputs` maps; operation IDs are not exports. `/pets/{petId}` becomes `pets.byPetId`, hyphenated segments become camelCase and HTTP methods are leaf functions. Colon actions such as `/chat:run` become `chat.run`. `key` is reserved as a route segment for query helpers. Unresolvable member collisions fail during compilation.An operation may set `x-client-path` to an explicit array such as `["enterprise", "access", "getEnvironmentApi"]` to preserve an existing public API. This replaces its entire client member path, including the method leaf, and also determines its query key. HTTP methods, URLs and per-operation sidecar keys still use the OpenAPI operation. Colliding or reserved member names fail during compilation.@@ -266,6 +268,174 @@ Wildcard response media follow the most specific matching declaration for the reWith one request media type, `contentType` can be omitted. With multiple media types, only `application/json` is implicit; other alternatives require an explicit matching `contentType`. Multipart accepts flat objects with scalar, Blob/File or repeated array fields, plus explicit JSON part encodings. Fetch supplies its boundary. Optional request bodies may be omitted entirely.+### Reuse model, input and output types++See [Petstore type examples] for reusable aliases and+a legacy request envelope, and [the runnable demo]+for typed HTTP calls. Run `pnpm --filter @dify/openapi-content-mapper type-check`+to check the examples, or `pnpm --filter @dify/openapi-content-mapper demo`+to execute them against a local server started by the demo.++Import types from the same document as the API. This works for YAML, JSON `.openapi`+files and `.openapi-source` command sources, without generating files:++```ts+import type { Schemas, Inputs, Outputs } from './pets.openapi.yaml'++type Pet = Schemas['Pet']+type CreatePetBody = Inputs['pets']['post']['body']+type GetPetInput = Inputs['pets']['byPetId']['get']+type PetList = Outputs['pets']['get']+type ListQuery = NonNullable<Inputs['pets']['get']>['query']+```++`Schemas` contains every `components.schemas` entry under its original name,+including unused and recursive models. Names containing `/` or `~` are accessed+with their original spelling. It describes JSON values: binary-formatted strings+remain `string`. For a multipart body, use `Inputs` to get the appropriate+`Blob`/`File`-compatible fields. Documents without component schemas export an+empty `Schemas` map.++`Inputs` and `Outputs` follow the `api` member paths, including `x-client-path`+overrides. Each input is the operation's first argument, equivalent to+`Parameters<typeof api.pets.get>[0]`; optional inputs include `undefined`. It does+not include the second argument's transport options or context. Each output is+the awaited successful result, equivalent to `Awaited<ReturnType<...>>`, including+`void` for empty responses, `Blob` for binary responses and streams for SSE.+Inline schemas and media-type discrimination are preserved. All three exports+are erased from JavaScript; use `import type` or `export type` to consume them.++### Dify contract type subpaths++Inside the Dify repository, import compatible contract types directly from this+package's subpaths. Existing type names and structures are preserved; only the+module specifier changes:++```ts+import type {+ DatasetCreatePayload,+ PostDatasetsData,+ PostDatasetsResponses,+ PostDatasetsResponse,+ PostDatasetsErrors,+ PostDatasetsError,+} from '@dify/openapi-content-mapper/console/datasets'++const body: DatasetCreatePayload = { name: 'Documentation' }+const request: PostDatasetsData = { url: '/datasets', body }+type Created = PostDatasetsResponses[201]+type Conflict = PostDatasetsErrors[409]+```++Available subpaths are `/console/*`, `/service`, `/web`, `/openapi`, `/enterprise`+and `/enterprise-app-deploy`. They provide models, `ClientOptions`, legacy `*Data`+request envelopes, status-indexed `*Responses` / `*Errors`, and the singular+response/error unions. Same-named types stay isolated in their modules. The+original `@dify/contracts` exports remain unchanged; no `customConditions` or+conditional overrides of those paths are needed.++These subpaths are **type-only**. For runtime enum objects, continue to import the+original contracts module, while the mapper subpath can supply the type:++```ts+import type { AccessMode } from '@dify/openapi-content-mapper/enterprise'+import { AccessMode as AccessModes } from '@dify/contracts/enterprise/types.gen'++const mode: AccessMode = AccessModes.ACCESS_MODE_PRIVATE+```++Enable `.openapi-types` in the consuming project's mapper settings. The mapper+automatically registers the contract sources shipped in its workspace package:++```json+{+ "contentMappers": [+ {+ "package": "@dify/openapi-content-mapper",+ "extensions": [".openapi", ".openapi-source", ".openapi-types"]+ }+ ]+}+```++No `options.sources` or `paths` entries are needed for these package subpaths.+Registration watches descriptors and backend inputs without running exporters;+exporters run when their modules are imported. Modules sharing inputs reuse one+filesystem scan per registration. Custom `.openapi-source` and `.openapi-types`+files outside the package's `contracts/` directory still require `options.sources`,+with paths relative to the consuming tsconfig. Explicit sources are combined with+the automatic sources. Run TypeScript 7.1 with `--runExternalCode`, and enable+content mappers in the editor. The [repository compatibility example]+and its tsconfig already use these subpaths:++```sh+pnpm --filter @dify/openapi-content-mapper type-check:contracts+```++The compatibility exporter reuses the same Community document normalization,+Console module splitting and Hey API TypeScript plugin as regular generation.+It exports current Python schemas into memory and runs Hey API with disk output+and cleanup disabled. Request `path`/`url`, status maps, writable variants,+recursive models, binary types and enum naming therefore follow the existing+contracts rules, rather than the mapper RPC `Inputs`/`Outputs` rules. Backend+contract changes still change the inferred types.++Type hovers include **Open backend implementation** links for registered Community+Python models and API request/response/error envelopes. With the local+[VS Code extension], F12 / Cmd+click and Go to+Implementation follow these links, including through import aliases and re-exports.+In the example, `DatasetCreatePayload` opens its Python class and `PostDatasetsData`+opens `DatasetListApi.post`. Synthetic models and snapshots without source metadata+have no backend target; the exporter does not guess by type name.++Enterprise and App Deploy use the retained OpenAPI snapshots. These snapshots omit+some non-Console models; missing exports are re-exported from the existing complete+contracts modules. Those retained types update with regular Enterprise generation,+rather than with unavailable private backend sources.++The three contracts generation commands also regenerate the mapper's thin subpath+selectors and `.d.ts` entry points. To refresh them alone after adding modules, run+`pnpm --filter @dify/contracts gen-compatibility-sources`. Each selector contains+only an `extends` path and module argument; exporter commands and watched inputs+live in two shared source configurations. Each declaration entry contains only an+`export type *` pointing to its selector; model declarations remain virtual and new+names are discovered automatically. No additional OpenAPI snapshots are written.++Package exports resolve through these standard `.d.ts` entries so TypeScript 7's+language service does not report a missing-declaration hint for the custom source+extension. Consumers need no `compilerOptions.paths` overrides or ambient module+declarations; they only enable the mapper and extension as shown above.++Dify-specific subpaths require the repository's Python and JavaScript development+dependencies, but no running API or database. They are workspace integrations and+are excluded from the standalone npm SDK's published exports and files. The+standalone package continues to support generic OpenAPI imports. Production+consumers of `@dify/contracts` are unaffected.++#### Type-only command sources++`.openapi-types` uses the same descriptor shape, watched-input validation and+cache invalidation as `.openapi-source`. Its exporter writes JSON of the form+`{"typescript":"export type Example = { id: string };"}` to stdout. The mapper+uses this TypeScript module as virtual compiler input. Exporter logs belong on+stderr, and empty or malformed results are diagnostics, not cached successes.+These files are for type resolution, not runtime imports. Dify subpaths expose+only a `types` target; runtime imports continue to use the original contracts. Ordinary OpenAPI imports still export `Schemas`,+`Inputs`, `Outputs`, `api` and `query` as described above.++Descriptors can share a configuration with `extends`. `extends` and `cwd` paths+are resolved from the descriptor that defines them; input patterns are relative+to the effective `cwd`. Other fields replace inherited values, and `args` is+appended to the effective command. Every inherited descriptor+is watched and included in cache invalidation. For example:++```json+{+ "extends": "../community.source.json",+ "args": ["api/console/datasets"]+}+```+### Document configurationPlace `pets.openapi.yaml.config.ts` next to `pets.openapi.yaml`:@@ -438,6 +608,16 @@ No running API, database or private source checkout is needed. CI installs thePython environment before the standalone Console checks. `compose:console` nowprints the composed OpenAPI JSON to stdout instead of creating a file.+Open [the real Dify type examples] to inspect dataset+models, list/create inputs and outputs, multipart file uploads, and compatibility+aliases retaining existing contracts names and request envelopes. The example+imports `Schemas`, `Inputs` and `Outputs` from the live Console source descriptor;+its sample values do not send requests. Check all repository examples with:++```sh+pnpm --filter @dify/openapi-content-mapper exec tsc --runExternalCode --noEmit -p examples/repository/tsconfig.json+```+The package uses `vp pack` and builds through `prepare` during workspace installation,like `@langgenius/dev-proxy`. Web's `prebuild` and `prebuild:vinext` hooks also buildthe SDK so production builds work after an installation with `--ignore-scripts`,@@ -486,4 +666,8 @@ This package retains the repository's modified Apache 2.0 terms, including its a[CHANGELOG]: CHANGELOG.md[Development and release]: #development-and-release[LICENSE]: LICENSE+[Petstore type examples]: examples/petstore/types.ts[VS Code extension]: ./vscode/README.md+[repository compatibility example]: examples/repository/compatibility.ts+[the real Dify type examples]: examples/repository/types.ts+[the runnable demo]: examples/petstore/demo.tsdiff --git a/packages/openapi-content-mapper/contracts/community.source.json b/packages/openapi-content-mapper/contracts/community.source.jsonnew file mode 100644index 00000000000..ec6663360dc--- /dev/null+++ b/packages/openapi-content-mapper/contracts/community.source.json@@ -0,0 +1,21 @@+{+ "command": ["node", "packages/contracts/scripts/export-compatibility-types.ts"],+ "cwd": "../../..",+ "inputs": [+ "packages/contracts/api-documents.ts",+ "packages/contracts/typescript-generation.ts",+ "packages/contracts/scripts/export-compatibility-types.ts",+ "packages/contracts/package.json",+ "pnpm-lock.yaml",+ "packages/contracts/generated/api/**/types.gen.ts",+ "api/**/*.py",+ "dify-agent/src/**/*.py",+ "dify-agent/pyproject.toml",+ "api/pyproject.toml",+ "api/uv.lock"+ ],+ "env": ["UV_PROJECT_ENVIRONMENT"],+ "exclude": ["api/tests/**"],+ "optionalInputs": [".env"],+ "timeoutMs": 120000+}diff --git a/packages/openapi-content-mapper/contracts/console/account.d.ts b/packages/openapi-content-mapper/contracts/console/account.d.tsnew file mode 100644index 00000000000..29c24da2652--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/account.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './account.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/account.openapi-types b/packages/openapi-content-mapper/contracts/console/account.openapi-typesnew file mode 100644index 00000000000..c67c17f0be6--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/account.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/account"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/activate.d.ts b/packages/openapi-content-mapper/contracts/console/activate.d.tsnew file mode 100644index 00000000000..67820188f34--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/activate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './activate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/activate.openapi-types b/packages/openapi-content-mapper/contracts/console/activate.openapi-typesnew file mode 100644index 00000000000..69bf341ea41--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/activate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/activate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/agent.d.ts b/packages/openapi-content-mapper/contracts/console/agent.d.tsnew file mode 100644index 00000000000..877ee5c0d93--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/agent.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './agent.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/agent.openapi-types b/packages/openapi-content-mapper/contracts/console/agent.openapi-typesnew file mode 100644index 00000000000..963e20609b5--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/agent.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/agent"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/all-workspaces.d.ts b/packages/openapi-content-mapper/contracts/console/all-workspaces.d.tsnew file mode 100644index 00000000000..7473d919653--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/all-workspaces.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './all-workspaces.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/all-workspaces.openapi-types b/packages/openapi-content-mapper/contracts/console/all-workspaces.openapi-typesnew file mode 100644index 00000000000..7c6ac4a0673--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/all-workspaces.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/all-workspaces"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/api-based-extension.d.ts b/packages/openapi-content-mapper/contracts/console/api-based-extension.d.tsnew file mode 100644index 00000000000..7b198c8d059--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/api-based-extension.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './api-based-extension.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/api-based-extension.openapi-types b/packages/openapi-content-mapper/contracts/console/api-based-extension.openapi-typesnew file mode 100644index 00000000000..1e37a5a9f3f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/api-based-extension.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/api-based-extension"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/api-key-auth.d.ts b/packages/openapi-content-mapper/contracts/console/api-key-auth.d.tsnew file mode 100644index 00000000000..385b0a79637--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/api-key-auth.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './api-key-auth.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/api-key-auth.openapi-types b/packages/openapi-content-mapper/contracts/console/api-key-auth.openapi-typesnew file mode 100644index 00000000000..55962d72339--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/api-key-auth.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/api-key-auth"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/app-dsl-version.d.ts b/packages/openapi-content-mapper/contracts/console/app-dsl-version.d.tsnew file mode 100644index 00000000000..17d33db6049--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/app-dsl-version.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './app-dsl-version.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/app-dsl-version.openapi-types b/packages/openapi-content-mapper/contracts/console/app-dsl-version.openapi-typesnew file mode 100644index 00000000000..765550e46cd--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/app-dsl-version.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/app-dsl-version"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/app.d.ts b/packages/openapi-content-mapper/contracts/console/app.d.tsnew file mode 100644index 00000000000..8b44fc31ff0--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/app.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './app.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/app.openapi-types b/packages/openapi-content-mapper/contracts/console/app.openapi-typesnew file mode 100644index 00000000000..92384d74944--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/app.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/app"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/apps.d.ts b/packages/openapi-content-mapper/contracts/console/apps.d.tsnew file mode 100644index 00000000000..e9a46c8ae54--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/apps.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './apps.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/apps.openapi-types b/packages/openapi-content-mapper/contracts/console/apps.openapi-typesnew file mode 100644index 00000000000..96e04f04d7b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/apps.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/apps"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/auth.d.ts b/packages/openapi-content-mapper/contracts/console/auth.d.tsnew file mode 100644index 00000000000..a54ccf6acd5--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/auth.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './auth.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/auth.openapi-types b/packages/openapi-content-mapper/contracts/console/auth.openapi-typesnew file mode 100644index 00000000000..d40241b2f25--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/auth.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/auth"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/billing.d.ts b/packages/openapi-content-mapper/contracts/console/billing.d.tsnew file mode 100644index 00000000000..5a97be8cc3a--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/billing.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './billing.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/billing.openapi-types b/packages/openapi-content-mapper/contracts/console/billing.openapi-typesnew file mode 100644index 00000000000..7fd4a5af81c--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/billing.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/billing"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/code-based-extension.d.ts b/packages/openapi-content-mapper/contracts/console/code-based-extension.d.tsnew file mode 100644index 00000000000..64e87052775--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/code-based-extension.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './code-based-extension.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/code-based-extension.openapi-types b/packages/openapi-content-mapper/contracts/console/code-based-extension.openapi-typesnew file mode 100644index 00000000000..af6058b9dd1--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/code-based-extension.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/code-based-extension"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/compliance.d.ts b/packages/openapi-content-mapper/contracts/console/compliance.d.tsnew file mode 100644index 00000000000..56af04b8e08--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/compliance.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './compliance.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/compliance.openapi-types b/packages/openapi-content-mapper/contracts/console/compliance.openapi-typesnew file mode 100644index 00000000000..2c66e7053c8--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/compliance.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/compliance"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/data-source.d.ts b/packages/openapi-content-mapper/contracts/console/data-source.d.tsnew file mode 100644index 00000000000..20f32558ae2--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/data-source.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './data-source.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/data-source.openapi-types b/packages/openapi-content-mapper/contracts/console/data-source.openapi-typesnew file mode 100644index 00000000000..86cbfe0c39e--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/data-source.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/data-source"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/datasets.d.ts b/packages/openapi-content-mapper/contracts/console/datasets.d.tsnew file mode 100644index 00000000000..599f580f617--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/datasets.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './datasets.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/datasets.openapi-types b/packages/openapi-content-mapper/contracts/console/datasets.openapi-typesnew file mode 100644index 00000000000..9605d388533--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/datasets.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/datasets"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/email-code-login.d.ts b/packages/openapi-content-mapper/contracts/console/email-code-login.d.tsnew file mode 100644index 00000000000..bedb31c21bb--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/email-code-login.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './email-code-login.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/email-code-login.openapi-types b/packages/openapi-content-mapper/contracts/console/email-code-login.openapi-typesnew file mode 100644index 00000000000..d49f05e6c74--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/email-code-login.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/email-code-login"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/email-register.d.ts b/packages/openapi-content-mapper/contracts/console/email-register.d.tsnew file mode 100644index 00000000000..a93eca47629--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/email-register.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './email-register.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/email-register.openapi-types b/packages/openapi-content-mapper/contracts/console/email-register.openapi-typesnew file mode 100644index 00000000000..e0a1ad95f0f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/email-register.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/email-register"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/explore.d.ts b/packages/openapi-content-mapper/contracts/console/explore.d.tsnew file mode 100644index 00000000000..f2a2eed44c3--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/explore.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './explore.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/explore.openapi-types b/packages/openapi-content-mapper/contracts/console/explore.openapi-typesnew file mode 100644index 00000000000..922f7933e21--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/explore.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/explore"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/features.d.ts b/packages/openapi-content-mapper/contracts/console/features.d.tsnew file mode 100644index 00000000000..75e29345886--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/features.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './features.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/features.openapi-types b/packages/openapi-content-mapper/contracts/console/features.openapi-typesnew file mode 100644index 00000000000..8e283bc4ef7--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/features.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/features"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/files.d.ts b/packages/openapi-content-mapper/contracts/console/files.d.tsnew file mode 100644index 00000000000..dbeac2611d8--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/files.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './files.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/files.openapi-types b/packages/openapi-content-mapper/contracts/console/files.openapi-typesnew file mode 100644index 00000000000..a48abea742b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/files.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/files"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/forgot-password.d.ts b/packages/openapi-content-mapper/contracts/console/forgot-password.d.tsnew file mode 100644index 00000000000..cd943d7ed5e--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/forgot-password.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './forgot-password.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/forgot-password.openapi-types b/packages/openapi-content-mapper/contracts/console/forgot-password.openapi-typesnew file mode 100644index 00000000000..de8d0d7f09f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/forgot-password.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/forgot-password"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/form.d.ts b/packages/openapi-content-mapper/contracts/console/form.d.tsnew file mode 100644index 00000000000..c2c997fddd9--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/form.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './form.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/form.openapi-types b/packages/openapi-content-mapper/contracts/console/form.openapi-typesnew file mode 100644index 00000000000..8ef546eba51--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/form.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/form"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/init.d.ts b/packages/openapi-content-mapper/contracts/console/init.d.tsnew file mode 100644index 00000000000..f88a655f157--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/init.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './init.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/init.openapi-types b/packages/openapi-content-mapper/contracts/console/init.openapi-typesnew file mode 100644index 00000000000..f6ca0e303b7--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/init.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/init"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/installed-apps.d.ts b/packages/openapi-content-mapper/contracts/console/installed-apps.d.tsnew file mode 100644index 00000000000..579e853ba51--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/installed-apps.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './installed-apps.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/installed-apps.openapi-types b/packages/openapi-content-mapper/contracts/console/installed-apps.openapi-typesnew file mode 100644index 00000000000..9a5c81177d0--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/installed-apps.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/installed-apps"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/instruction-generate.d.ts b/packages/openapi-content-mapper/contracts/console/instruction-generate.d.tsnew file mode 100644index 00000000000..a981a761f34--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/instruction-generate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './instruction-generate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/instruction-generate.openapi-types b/packages/openapi-content-mapper/contracts/console/instruction-generate.openapi-typesnew file mode 100644index 00000000000..5aef4a1ebfd--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/instruction-generate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/instruction-generate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/knowledge-fs.d.ts b/packages/openapi-content-mapper/contracts/console/knowledge-fs.d.tsnew file mode 100644index 00000000000..aae705ecce3--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/knowledge-fs.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './knowledge-fs.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/knowledge-fs.openapi-types b/packages/openapi-content-mapper/contracts/console/knowledge-fs.openapi-typesnew file mode 100644index 00000000000..b8aef058cb4--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/knowledge-fs.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/knowledge-fs"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/login.d.ts b/packages/openapi-content-mapper/contracts/console/login.d.tsnew file mode 100644index 00000000000..618e56b47af--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/login.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './login.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/login.openapi-types b/packages/openapi-content-mapper/contracts/console/login.openapi-typesnew file mode 100644index 00000000000..ff437d67a84--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/login.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/login"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/logout.d.ts b/packages/openapi-content-mapper/contracts/console/logout.d.tsnew file mode 100644index 00000000000..e6227d67a42--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/logout.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './logout.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/logout.openapi-types b/packages/openapi-content-mapper/contracts/console/logout.openapi-typesnew file mode 100644index 00000000000..33f798db2c9--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/logout.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/logout"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/notification.d.ts b/packages/openapi-content-mapper/contracts/console/notification.d.tsnew file mode 100644index 00000000000..735097dff7b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/notification.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './notification.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/notification.openapi-types b/packages/openapi-content-mapper/contracts/console/notification.openapi-typesnew file mode 100644index 00000000000..f687c4d83f1--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/notification.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/notification"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/notion.d.ts b/packages/openapi-content-mapper/contracts/console/notion.d.tsnew file mode 100644index 00000000000..52048ed8ecd--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/notion.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './notion.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/notion.openapi-types b/packages/openapi-content-mapper/contracts/console/notion.openapi-typesnew file mode 100644index 00000000000..20b9021727d--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/notion.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/notion"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/oauth.d.ts b/packages/openapi-content-mapper/contracts/console/oauth.d.tsnew file mode 100644index 00000000000..2fc4cadb3fa--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/oauth.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './oauth.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/oauth.openapi-types b/packages/openapi-content-mapper/contracts/console/oauth.openapi-typesnew file mode 100644index 00000000000..87107874c1f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/oauth.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/oauth"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/onboarding.d.ts b/packages/openapi-content-mapper/contracts/console/onboarding.d.tsnew file mode 100644index 00000000000..1c100c7701f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/onboarding.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './onboarding.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/onboarding.openapi-types b/packages/openapi-content-mapper/contracts/console/onboarding.openapi-typesnew file mode 100644index 00000000000..cd0ec06427b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/onboarding.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/onboarding"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/ping.d.ts b/packages/openapi-content-mapper/contracts/console/ping.d.tsnew file mode 100644index 00000000000..9b0deca55a7--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/ping.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './ping.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/ping.openapi-types b/packages/openapi-content-mapper/contracts/console/ping.openapi-typesnew file mode 100644index 00000000000..96a54767cdf--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/ping.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/ping"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/rag.d.ts b/packages/openapi-content-mapper/contracts/console/rag.d.tsnew file mode 100644index 00000000000..210aae0ce67--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rag.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './rag.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/rag.openapi-types b/packages/openapi-content-mapper/contracts/console/rag.openapi-typesnew file mode 100644index 00000000000..8acbf10e914--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rag.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/rag"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/refresh-token.d.ts b/packages/openapi-content-mapper/contracts/console/refresh-token.d.tsnew file mode 100644index 00000000000..195c998c2c8--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/refresh-token.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './refresh-token.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/refresh-token.openapi-types b/packages/openapi-content-mapper/contracts/console/refresh-token.openapi-typesnew file mode 100644index 00000000000..20bebda063e--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/refresh-token.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/refresh-token"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/remote-files.d.ts b/packages/openapi-content-mapper/contracts/console/remote-files.d.tsnew file mode 100644index 00000000000..e22e4f341b3--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/remote-files.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './remote-files.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/remote-files.openapi-types b/packages/openapi-content-mapper/contracts/console/remote-files.openapi-typesnew file mode 100644index 00000000000..181352ed441--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/remote-files.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/remote-files"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/reset-password.d.ts b/packages/openapi-content-mapper/contracts/console/reset-password.d.tsnew file mode 100644index 00000000000..dade47b478c--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/reset-password.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './reset-password.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/reset-password.openapi-types b/packages/openapi-content-mapper/contracts/console/reset-password.openapi-typesnew file mode 100644index 00000000000..33d2e76a692--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/reset-password.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/reset-password"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/resource-access-tokens.d.ts b/packages/openapi-content-mapper/contracts/console/resource-access-tokens.d.tsnew file mode 100644index 00000000000..5a5025aa459--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/resource-access-tokens.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './resource-access-tokens.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/resource-access-tokens.openapi-types b/packages/openapi-content-mapper/contracts/console/resource-access-tokens.openapi-typesnew file mode 100644index 00000000000..a2002fa8c6d--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/resource-access-tokens.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/resource-access-tokens"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/rule-code-generate.d.ts b/packages/openapi-content-mapper/contracts/console/rule-code-generate.d.tsnew file mode 100644index 00000000000..074a63d1c87--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-code-generate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './rule-code-generate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/rule-code-generate.openapi-types b/packages/openapi-content-mapper/contracts/console/rule-code-generate.openapi-typesnew file mode 100644index 00000000000..2d4d3026732--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-code-generate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/rule-code-generate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/rule-generate.d.ts b/packages/openapi-content-mapper/contracts/console/rule-generate.d.tsnew file mode 100644index 00000000000..4592b6ac62e--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-generate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './rule-generate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/rule-generate.openapi-types b/packages/openapi-content-mapper/contracts/console/rule-generate.openapi-typesnew file mode 100644index 00000000000..24408375cf6--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-generate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/rule-generate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.d.ts b/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.d.tsnew file mode 100644index 00000000000..d15506bae27--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './rule-structured-output-generate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.openapi-types b/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.openapi-typesnew file mode 100644index 00000000000..c81f1112c4b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/rule-structured-output-generate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/rule-structured-output-generate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/setup.d.ts b/packages/openapi-content-mapper/contracts/console/setup.d.tsnew file mode 100644index 00000000000..a802857a83f--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/setup.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './setup.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/setup.openapi-types b/packages/openapi-content-mapper/contracts/console/setup.openapi-typesnew file mode 100644index 00000000000..7ff2fd4e922--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/setup.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/setup"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/snippets.d.ts b/packages/openapi-content-mapper/contracts/console/snippets.d.tsnew file mode 100644index 00000000000..3339fc77eb6--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/snippets.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './snippets.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/snippets.openapi-types b/packages/openapi-content-mapper/contracts/console/snippets.openapi-typesnew file mode 100644index 00000000000..c080882a709--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/snippets.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/snippets"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/spec.d.ts b/packages/openapi-content-mapper/contracts/console/spec.d.tsnew file mode 100644index 00000000000..e5526da8d12--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/spec.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './spec.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/spec.openapi-types b/packages/openapi-content-mapper/contracts/console/spec.openapi-typesnew file mode 100644index 00000000000..30c818aaf88--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/spec.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/spec"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/system-features.d.ts b/packages/openapi-content-mapper/contracts/console/system-features.d.tsnew file mode 100644index 00000000000..7b08ad54850--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/system-features.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './system-features.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/system-features.openapi-types b/packages/openapi-content-mapper/contracts/console/system-features.openapi-typesnew file mode 100644index 00000000000..a44cd335800--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/system-features.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/system-features"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/tag-bindings.d.ts b/packages/openapi-content-mapper/contracts/console/tag-bindings.d.tsnew file mode 100644index 00000000000..ea4c4738256--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/tag-bindings.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './tag-bindings.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/tag-bindings.openapi-types b/packages/openapi-content-mapper/contracts/console/tag-bindings.openapi-typesnew file mode 100644index 00000000000..0fb24d6cf84--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/tag-bindings.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/tag-bindings"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/tags.d.ts b/packages/openapi-content-mapper/contracts/console/tags.d.tsnew file mode 100644index 00000000000..25769361c06--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/tags.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './tags.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/tags.openapi-types b/packages/openapi-content-mapper/contracts/console/tags.openapi-typesnew file mode 100644index 00000000000..cabe9355607--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/tags.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/tags"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/trial-apps.d.ts b/packages/openapi-content-mapper/contracts/console/trial-apps.d.tsnew file mode 100644index 00000000000..374416f4971--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/trial-apps.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './trial-apps.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/trial-apps.openapi-types b/packages/openapi-content-mapper/contracts/console/trial-apps.openapi-typesnew file mode 100644index 00000000000..168763c0d92--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/trial-apps.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/trial-apps"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/trial-models.d.ts b/packages/openapi-content-mapper/contracts/console/trial-models.d.tsnew file mode 100644index 00000000000..1f576dd25b9--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/trial-models.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './trial-models.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/trial-models.openapi-types b/packages/openapi-content-mapper/contracts/console/trial-models.openapi-typesnew file mode 100644index 00000000000..4e1de1b3ba7--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/trial-models.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/trial-models"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/version.d.ts b/packages/openapi-content-mapper/contracts/console/version.d.tsnew file mode 100644index 00000000000..2e0e2a921f9--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/version.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './version.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/version.openapi-types b/packages/openapi-content-mapper/contracts/console/version.openapi-typesnew file mode 100644index 00000000000..684d23fdcdf--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/version.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/version"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/website.d.ts b/packages/openapi-content-mapper/contracts/console/website.d.tsnew file mode 100644index 00000000000..f32f0133902--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/website.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './website.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/website.openapi-types b/packages/openapi-content-mapper/contracts/console/website.openapi-typesnew file mode 100644index 00000000000..c8f57f7b00b--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/website.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/website"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/workflow-generate.d.ts b/packages/openapi-content-mapper/contracts/console/workflow-generate.d.tsnew file mode 100644index 00000000000..081c555f05d--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow-generate.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './workflow-generate.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/workflow-generate.openapi-types b/packages/openapi-content-mapper/contracts/console/workflow-generate.openapi-typesnew file mode 100644index 00000000000..e348c88953e--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow-generate.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/workflow-generate"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/workflow-run-archives.d.ts b/packages/openapi-content-mapper/contracts/console/workflow-run-archives.d.tsnew file mode 100644index 00000000000..bc32b03a5ee--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow-run-archives.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './workflow-run-archives.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/workflow-run-archives.openapi-types b/packages/openapi-content-mapper/contracts/console/workflow-run-archives.openapi-typesnew file mode 100644index 00000000000..1168f373ff6--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow-run-archives.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/workflow-run-archives"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/workflow.d.ts b/packages/openapi-content-mapper/contracts/console/workflow.d.tsnew file mode 100644index 00000000000..3c664ed2676--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './workflow.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/workflow.openapi-types b/packages/openapi-content-mapper/contracts/console/workflow.openapi-typesnew file mode 100644index 00000000000..d241a16af27--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workflow.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/workflow"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/console/workspaces.d.ts b/packages/openapi-content-mapper/contracts/console/workspaces.d.tsnew file mode 100644index 00000000000..c73f2c68353--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workspaces.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './workspaces.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/console/workspaces.openapi-types b/packages/openapi-content-mapper/contracts/console/workspaces.openapi-typesnew file mode 100644index 00000000000..0da628b33f2--- /dev/null+++ b/packages/openapi-content-mapper/contracts/console/workspaces.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "../community.source.json",+ "args": [+ "api/console/workspaces"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/enterprise-app-deploy.d.ts b/packages/openapi-content-mapper/contracts/enterprise-app-deploy.d.tsnew file mode 100644index 00000000000..b0321b47912--- /dev/null+++ b/packages/openapi-content-mapper/contracts/enterprise-app-deploy.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './enterprise-app-deploy.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/enterprise-app-deploy.openapi-types b/packages/openapi-content-mapper/contracts/enterprise-app-deploy.openapi-typesnew file mode 100644index 00000000000..6a0e4c34c71--- /dev/null+++ b/packages/openapi-content-mapper/contracts/enterprise-app-deploy.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "enterprise.source.json",+ "args": [+ "enterprise-app-deploy"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/enterprise.d.ts b/packages/openapi-content-mapper/contracts/enterprise.d.tsnew file mode 100644index 00000000000..5800263d659--- /dev/null+++ b/packages/openapi-content-mapper/contracts/enterprise.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './enterprise.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/enterprise.openapi-types b/packages/openapi-content-mapper/contracts/enterprise.openapi-typesnew file mode 100644index 00000000000..8a8d5c54358--- /dev/null+++ b/packages/openapi-content-mapper/contracts/enterprise.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "enterprise.source.json",+ "args": [+ "enterprise"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/enterprise.source.json b/packages/openapi-content-mapper/contracts/enterprise.source.jsonnew file mode 100644index 00000000000..cc9bd0bfdc5--- /dev/null+++ b/packages/openapi-content-mapper/contracts/enterprise.source.json@@ -0,0 +1,14 @@+{+ "command": ["node", "packages/contracts/scripts/export-compatibility-types.ts"],+ "cwd": "../../..",+ "inputs": [+ "packages/contracts/api-documents.ts",+ "packages/contracts/typescript-generation.ts",+ "packages/contracts/scripts/export-compatibility-types.ts",+ "packages/contracts/package.json",+ "pnpm-lock.yaml",+ "packages/contracts/generated/enterprise*/types.gen.ts",+ "packages/contracts/generated/enterprise*/openapi.gen.json"+ ],+ "timeoutMs": 120000+}diff --git a/packages/openapi-content-mapper/contracts/openapi.d.ts b/packages/openapi-content-mapper/contracts/openapi.d.tsnew file mode 100644index 00000000000..9d1c923e307--- /dev/null+++ b/packages/openapi-content-mapper/contracts/openapi.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './openapi.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/openapi.openapi-types b/packages/openapi-content-mapper/contracts/openapi.openapi-typesnew file mode 100644index 00000000000..048ee7cf9f7--- /dev/null+++ b/packages/openapi-content-mapper/contracts/openapi.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "community.source.json",+ "args": [+ "api/openapi"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/service.d.ts b/packages/openapi-content-mapper/contracts/service.d.tsnew file mode 100644index 00000000000..2726e94ffef--- /dev/null+++ b/packages/openapi-content-mapper/contracts/service.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './service.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/service.openapi-types b/packages/openapi-content-mapper/contracts/service.openapi-typesnew file mode 100644index 00000000000..d412f8c4a4c--- /dev/null+++ b/packages/openapi-content-mapper/contracts/service.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "community.source.json",+ "args": [+ "api/service"+ ]+}diff --git a/packages/openapi-content-mapper/contracts/web.d.ts b/packages/openapi-content-mapper/contracts/web.d.tsnew file mode 100644index 00000000000..81340aa4a38--- /dev/null+++ b/packages/openapi-content-mapper/contracts/web.d.ts@@ -0,0 +1,2 @@+// Generated by @dify/contracts gen-compatibility-sources.+export type * from './web.openapi-types'diff --git a/packages/openapi-content-mapper/contracts/web.openapi-types b/packages/openapi-content-mapper/contracts/web.openapi-typesnew file mode 100644index 00000000000..6f99077c6f3--- /dev/null+++ b/packages/openapi-content-mapper/contracts/web.openapi-types@@ -0,0 +1,6 @@+{+ "extends": "community.source.json",+ "args": [+ "api/web"+ ]+}diff --git a/packages/openapi-content-mapper/examples/petstore/demo.ts b/packages/openapi-content-mapper/examples/petstore/demo.tsindex acc1ccbd1b8..79ac7de5763 100644--- a/packages/openapi-content-mapper/examples/petstore/demo.ts+++ b/packages/openapi-content-mapper/examples/petstore/demo.ts@@ -1,3 +1,4 @@+import type { CreatePetBody, GetPetInput, ListQuery, Pet, PetList } from './types.js'import assert from 'node:assert/strict'import { once } from 'node:events'import { createServer } from 'node:http'@@ -6,7 +7,7 @@ import { api as jsonApi } from './pets.openapi'import { api } from './pets.openapi.yaml'async function main() {- const pets = [{ id: 1, name: 'Mochi', status: 'available' }]+ const pets: Pet[] = [{ id: 1, name: 'Mochi', status: 'available' }]const server = createServer(async (req, res) => {const url = new URL(req.url!, 'http://localhost')res.setHeader('Content-Type', 'application/json')@@ -44,16 +45,20 @@ async function main() {const address = server.address()assert(address && typeof address !== 'string')const client = createClient({ baseUrl: `http://127.0.0.1:${address.port}` })+ const input: GetPetInput = { params: { petId: 1 } }+ const body: CreatePetBody = { name: '雪团' }+ const query: ListQuery = { status: 'available' }assert.equal((await jsonApi.pets.byPetId.get({ params: { petId: 1 } }, { client })).name,'Mochi',)// oxlint-disable-next-line no-console -- The executable demo reports HTTP results.- console.log('GET:', await api.pets.byPetId.get({ params: { petId: 1 } }, { client }))+ console.log('GET:', await api.pets.byPetId.get(input, { client }))// oxlint-disable-next-line no-console -- The executable demo reports HTTP results.- console.log('POST:', await api.pets.post({ body: { name: '雪团' } }, { client }))+ console.log('POST:', await api.pets.post({ body }, { client }))+ const available: PetList = await api.pets.get({ query }, { client })// oxlint-disable-next-line no-console -- The executable demo reports HTTP results.- console.log('QUERY:', await api.pets.get({ query: { status: 'available' } }, { client }))+ console.log('QUERY:', available)assert.equal(await api.pets.byPetId.delete({ params: { petId: 2 } }, { client }), undefined)try {await api.pets.byPetId.get({ params: { petId: 404 } }, { client })diff --git a/packages/openapi-content-mapper/examples/petstore/types.ts b/packages/openapi-content-mapper/examples/petstore/types.tsnew file mode 100644index 00000000000..133675e74d0--- /dev/null+++ b/packages/openapi-content-mapper/examples/petstore/types.ts@@ -0,0 +1,23 @@+import type { Inputs, Outputs, Schemas } from './pets.openapi.yaml'++// Shared models can be used in component props or local state.+export type Pet = Schemas['Pet']++// Inline request bodies and decoded responses follow the API member paths.+export type CreatePetBody = Inputs['pets']['post']['body']+export type GetPetInput = Inputs['pets']['byPetId']['get']+export type PetList = Outputs['pets']['get']++// List input is optional, so remove undefined before accessing its query group.+export type ListQuery = NonNullable<Inputs['pets']['get']>['query']++// A compatibility module can keep an existing export name and request envelope.+// Consumers keep importing it from the same module during migration.+export type GetPetsByPetIdData = {+ body?: never+ path: GetPetInput['params']+ query?: never+ url: '/pets/{petId}'+}++export type GetPetsByPetIdResponse = Outputs['pets']['byPetId']['get']diff --git a/packages/openapi-content-mapper/examples/repository/compatibility.ts b/packages/openapi-content-mapper/examples/repository/compatibility.tsnew file mode 100644index 00000000000..3c1e523bb2b--- /dev/null+++ b/packages/openapi-content-mapper/examples/repository/compatibility.ts@@ -0,0 +1,52 @@+// Import existing type names from the mapper subpath, with no handwritten aliases.+// Only the import path changes; no customConditions are required.+// With the local OpenAPI Backend Navigation extension, F12 on DatasetCreatePayload+// opens its Python class; F12 on PostDatasetsData opens DatasetListApi.post.+// The same targets are available as "Open backend implementation" hover links.+import type {+ ClientOptions,+ DatasetCreatePayload,+ DatasetListItemResponse,+ GetDatasetsData,+ GetDatasetsResponse,+ GetDatasetsResponses,+ PostDatasetsData,+ PostDatasetsError,+ PostDatasetsErrors,+ PostDatasetsResponse,+ PostDatasetsResponses,+} from '@dify/openapi-content-mapper/console/datasets'+import type { AccessMode } from '@dify/openapi-content-mapper/enterprise'+import { AccessMode as AccessModes } from '@dify/contracts/enterprise/types.gen'++export const dataset: DatasetCreatePayload = {+ name: 'Product documentation',+ indexing_technique: 'high_quality',+ permission: 'only_me',+}++// Legacy request envelopes keep url and path, rather than adopting RPC params.+export const listRequest: GetDatasetsData = {+ url: '/datasets',+ query: { page: 1, limit: 20 },+}+export const createRequest: PostDatasetsData = { url: '/datasets', body: dataset }++export function datasetRows(response: GetDatasetsResponse): DatasetListItemResponse[] {+ return response.data+}++// Status-indexed responses and errors, their unions, and ClientOptions are exported too.+export function createdResponse(response: PostDatasetsResponses[201]): PostDatasetsResponse {+ return response+}+export function listResponse(response: GetDatasetsResponses[200]): GetDatasetsResponse {+ return response+}+export function conflictResponse(error: PostDatasetsErrors[409]): PostDatasetsError {+ return error+}+export const clientOptions: ClientOptions = { baseUrl: 'https://dify.example/console/api' }++// Runtime enum values still come from the original contracts module.+export const privateAccess: AccessMode = AccessModes.ACCESS_MODE_PRIVATEdiff --git a/packages/openapi-content-mapper/examples/repository/console.openapi-source b/packages/openapi-content-mapper/examples/repository/console.openapi-sourceindex 5760541e824..04f3627ad25 100644--- a/packages/openapi-content-mapper/examples/repository/console.openapi-source+++ b/packages/openapi-content-mapper/examples/repository/console.openapi-source@@ -3,6 +3,8 @@"cwd": "../../../..","inputs": ["api/**/*.py",+ "dify-agent/src/**/*.py",+ "dify-agent/pyproject.toml","api/pyproject.toml","api/uv.lock","packages/contracts/scripts/compose-console-openapi.mjs",diff --git a/packages/openapi-content-mapper/examples/repository/tsconfig.json b/packages/openapi-content-mapper/examples/repository/tsconfig.jsonindex 9358241846b..aa9e49cbacc 100644--- a/packages/openapi-content-mapper/examples/repository/tsconfig.json+++ b/packages/openapi-content-mapper/examples/repository/tsconfig.json@@ -12,7 +12,7 @@"contentMappers": [{"package": "../..",- "extensions": [".yaml", ".yml", ".openapi", ".openapi-source"],+ "extensions": [".yaml", ".yml", ".openapi", ".openapi-source", ".openapi-types"],"options": {"sources": ["./console.openapi-source"]}diff --git a/packages/openapi-content-mapper/examples/repository/types.ts b/packages/openapi-content-mapper/examples/repository/types.tsnew file mode 100644index 00000000000..2076c103169--- /dev/null+++ b/packages/openapi-content-mapper/examples/repository/types.ts@@ -0,0 +1,52 @@+import type { Inputs, Outputs, Schemas } from './console.openapi-source'++// These types come from Dify's Python controllers through the Console exporter.+// Hover the aliases below to inspect the real fields; no running API is required.+export type DatasetCreatePayload = Schemas['console_DatasetCreatePayload']+export type TagResponse = Schemas['console_TagResponse']++// GET /datasets: the input is optional; its decoded response contains data + total.+export type ListDatasetsInput = Inputs['datasets']['get']+export type DatasetListQuery = NonNullable<ListDatasetsInput>['query']+export type DatasetListResponse = Outputs['datasets']['get']+export type DatasetListItem = DatasetListResponse['data'][number]++// POST /datasets: keep the full request and the form body available separately.+export type CreateDatasetInput = Inputs['datasets']['post']+export type CreateDatasetBody = CreateDatasetInput['body']+export type CreateDatasetResponse = Outputs['datasets']['post']++// POST /files/upload: multipart binary fields accept Blob/File, not JSON strings.+export type UploadFileBody = Inputs['files']['upload']['post']['body']+export type UploadFileResponse = Outputs['files']['upload']['post']++export const datasetDraft = {+ name: 'Product documentation',+ description: 'Knowledge base for product questions',+ indexing_technique: 'high_quality',+ permission: 'only_me',+} satisfies DatasetCreatePayload++export const createDatasetInput: CreateDatasetInput = { body: datasetDraft }+export const datasetListQuery: DatasetListQuery = { page: 1, limit: 20 }+export const datasetListInput: ListDatasetsInput = { query: datasetListQuery }++// Keep existing @dify/contracts names and envelopes in a compatibility module.+// This example does not replace the current generated contracts or send requests.+export type GetDatasetsData = {+ body?: never+ path?: never+ query?: DatasetListQuery+ url: '/datasets'+}++export type GetDatasetsResponse = DatasetListResponse++export type PostDatasetsData = {+ body: CreateDatasetBody+ path?: never+ query?: never+ url: '/datasets'+}++export type PostDatasetsResponse = CreateDatasetResponsediff --git a/packages/openapi-content-mapper/integration/contracts-types.test.mjs b/packages/openapi-content-mapper/integration/contracts-types.test.mjsnew file mode 100644index 00000000000..bbbf4612a55--- /dev/null+++ b/packages/openapi-content-mapper/integration/contracts-types.test.mjs@@ -0,0 +1,166 @@+/* oxlint-disable vitest/no-import-node-test -- Audit the opt-in exports with the native compiler and actual contracts. */+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { existsSync, globSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { test } from 'node:test'+import {+ exportCompatibilityTypes,+ loadCommunityDocuments,+ renderCompatibilityTypes,+ selectCommunityDocument,+} from '../../contracts/scripts/export-compatibility-types.ts'+/* oxlint-enable vitest/no-import-node-test */++const root = resolve(import.meta.dirname, '..')+const contracts = resolve(root, '../contracts')+const compiler = join(root, 'node_modules/typescript/bin/tsc')++test('all published contracts names and types remain compatible, including snapshot-only enterprise exports', async (t) => {+ const dir = mkdtempSync(join(root, 'integration/.contracts-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ const modules = globSync('generated/**/types.gen.ts', { cwd: contracts }).sort()+ const documents = { ...loadCommunityDocuments(false), ...loadCommunityDocuments(true) }+ let types = 0+ let values = 0+ for (const [index, file] of modules.entries()) {+ const module = file.slice('generated/'.length, -'/types.gen.ts'.length)+ const previous = readFileSync(join(contracts, file), 'utf8')+ const document = module.startsWith('api/')+ ? selectCommunityDocument(module, documents)+ : undefined+ const current = document+ ? await renderCompatibilityTypes(document)+ : await exportCompatibilityTypes(module)+ writeFileSync(join(dir, `module${index}.ts`), current)+ const checks = [+ `import type * as Old from ${JSON.stringify(join(contracts, file).replace(/\.ts$/, '.js'))};`,+ `import type * as Current from './module${index}.js';`,+ 'type Assert<T extends true> = T;',+ 'type Assignable<A, B> = [A] extends [B] ? true : false;',+ 'type IsAny<T> = 0 extends (1 & T) ? true : false;',+ ]+ for (const [, name] of previous.matchAll(/^export type (\w+)\s*=/gm)) {+ types+++ checks.push(+ `type OldToNew${name} = Assert<Assignable<Old.${name}, Current.${name}>>;`,+ `type NewToOld${name} = Assert<Assignable<Current.${name}, Old.${name}>>;`,+ `type NoAny${name} = Assert<Assignable<IsAny<Current.${name}>, IsAny<Old.${name}>>>;`,+ )+ }+ for (const [, name] of previous.matchAll(/^export const (\w+)\s*=/gm)) {+ values+++ checks.push(+ `type OldValue${name} = Assert<Assignable<typeof Old.${name}, typeof Current.${name}>>;`,+ `type NewValue${name} = Assert<Assignable<typeof Current.${name}, typeof Old.${name}>>;`,+ )+ }+ writeFileSync(join(dir, `check${index}.ts`), checks.join('\n'))+ }+ writeFileSync(+ join(dir, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ strict: true,+ noEmit: true,+ skipLibCheck: true,+ target: 'ES2022',+ module: 'NodeNext',+ lib: ['ES2022', 'DOM'],+ },+ include: ['*.ts'],+ }),+ )+ const result = spawnSync(process.execPath, [compiler, '-p', dir, '--pretty', 'false'], {+ encoding: 'utf8',+ timeout: 120000,+ maxBuffer: 8 * 1024 * 1024,+ })+ assert.ifError(result.error)+ assert.equal(result.status, 0, result.stdout + result.stderr)+ assert(!existsSync(join(contracts, '.compatibility-output')))+ t.diagnostic(+ `Checked ${modules.length} modules, ${types} named types and ${values} runtime enum objects in both directions`,+ )+})++test('mapper subpaths expose the existing types without conditions or changing legacy runtime imports', (t) => {+ const dir = mkdtempSync(join(root, 'integration/.subpaths-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ for (const mapper of [false, true]) {+ const path = mapper+ ? '@dify/openapi-content-mapper/console/datasets'+ : '@dify/contracts/api/console/datasets/types.gen'+ writeFileSync(+ join(dir, 'index.ts'),+ `+import type {DatasetCreatePayload, PostDatasetsData, PostDatasetsErrors, PostDatasetsResponses, PostDatasetsError, PostDatasetsResponse} from '${path}';+import type {AccessMode} from '${mapper ? '@dify/openapi-content-mapper/enterprise' : '@dify/contracts/enterprise/types.gen'}';+import {AccessMode as AccessModes} from '@dify/contracts/enterprise/types.gen';+const body: DatasetCreatePayload = {name: 'Docs'};+const request: PostDatasetsData = {url: '/datasets', body};+const response: PostDatasetsResponse = null! as PostDatasetsResponses[201];+const error: PostDatasetsError = null! as PostDatasetsErrors[409];+const mode: AccessMode = AccessModes.ACCESS_MODE_PRIVATE;+// @ts-expect-error legacy requests still require the URL+const bad: PostDatasetsData = {body};+// @ts-expect-error status maps must not become any+const wrong: PostDatasetsResponses[201] = 'wrong';+`,+ )+ writeFileSync(+ join(dir, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ strict: true,+ noEmit: true,+ skipLibCheck: true,+ target: 'ES2022',+ module: 'NodeNext',+ },+ contentMappers: mapper+ ? [+ {+ package: root,+ extensions: ['.openapi-types'],+ },+ ]+ : [],+ include: ['index.ts'],+ }),+ )+ const result = spawnSync(+ process.execPath,+ [compiler, '--runExternalCode', '--traceResolution', '-p', dir],+ {+ encoding: 'utf8',+ timeout: 180000,+ maxBuffer: 16 * 1024 * 1024,+ },+ )+ assert.ifError(result.error)+ assert.equal(result.status, 0, (result.stdout + result.stderr).slice(-12000))+ assert.match(+ result.stdout,+ mapper+ ? /contracts\/console\/datasets\.openapi-types/+ : /generated\/api\/console\/datasets\/types\.gen\.ts/,+ )+ }+ const runtime = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `+import assert from 'node:assert/strict';+import {AccessMode} from '@dify/contracts/enterprise/types.gen';+assert.equal(AccessMode.ACCESS_MODE_PRIVATE, 'ACCESS_MODE_PRIVATE');+assert(import.meta.resolve('@dify/contracts/enterprise/types.gen').endsWith('/generated/enterprise/types.gen.ts'));+await assert.rejects(import('@dify/openapi-content-mapper/console/datasets'), {code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'});+`,+ ],+ { cwd: root, encoding: 'utf8' },+ )+ assert.equal(runtime.status, 0, runtime.stdout + runtime.stderr)+})diff --git a/packages/openapi-content-mapper/integration/package.mjs b/packages/openapi-content-mapper/integration/package.mjsindex 2df4e008a27..4526ef587f0 100644--- a/packages/openapi-content-mapper/integration/package.mjs+++ b/packages/openapi-content-mapper/integration/package.mjs@@ -75,6 +75,11 @@ test('packed SDK installs and works outside the workspace with npm and official)const installed = join(directory, 'node_modules', manifest.name)const packed = JSON.parse(await readFile(join(installed, 'package.json'), 'utf8'))+ assert(!packed.exports['./console/*'], 'Dify-only subpaths must stay out of the standalone SDK')+ assert(+ !packed.exports['./enterprise'],+ 'Dify-only subpaths must stay out of the standalone SDK',+ )assert.equal(packed.name, manifest.name)assert.equal(packed.version, manifest.version)assert(!packed.private)diff --git a/packages/openapi-content-mapper/integration/type-navigation.test.mjs b/packages/openapi-content-mapper/integration/type-navigation.test.mjsnew file mode 100644index 00000000000..42a47663040--- /dev/null+++ b/packages/openapi-content-mapper/integration/type-navigation.test.mjs@@ -0,0 +1,79 @@+/* oxlint-disable vitest/no-import-node-test -- Exercise native TS hover resolution against real Python exports. */+import assert from 'node:assert/strict'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { test } from 'node:test'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { rpcProcess } from '../test/rpc.mjs'+import navigation from '../vscode/locations.cjs'+/* oxlint-enable vitest/no-import-node-test */++const root = resolve(import.meta.dirname, '..')+const compiler = join(root, 'node_modules/typescript/bin/tsc')++test(+ 'subpath type hovers navigate to Python models and handlers through aliases and re-exports',+ { timeout: 180000 },+ async (t) => {+ const dir = mkdtempSync(join(root, 'integration/.navigation-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ writeFileSync(+ join(dir, 'types.ts'),+ "export type { DatasetCreatePayload as Payload, PostDatasetsData as Request, PostDatasetsResponse as Response } from '@dify/openapi-content-mapper/console/datasets';",+ )+ const source = [+ "import type { Payload, Request, Response } from './types.js';",+ 'export const payload: Payload = { name: "Docs" };',+ 'export const request: Request = { url: "/datasets", body: payload };',+ 'export function response(value: Response) { return value; }',+ ].join('\n')+ writeFileSync(join(dir, 'index.ts'), source)+ writeFileSync(+ join(dir, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: { strict: true, noEmit: true, target: 'ES2022', module: 'NodeNext' },+ contentMappers: [{ package: root, extensions: ['.openapi-types'] }],+ include: ['*.ts'],+ }),+ )+ const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root, 120000)+ t.after(() => rpc.close())+ const uri = pathToFileURL(join(dir, 'index.ts')).href+ await rpc.request('initialize', {+ processId: process.pid,+ rootUri: pathToFileURL(dir).href,+ initializationOptions: { runExternalCode: true },+ capabilities: { textDocument: { hover: { contentFormat: ['markdown'] } } },+ })+ rpc.notify('initialized', {})+ rpc.notify('textDocument/didOpen', {+ textDocument: { uri, languageId: 'typescript', version: 1, text: source },+ })+ for (const [line, name, definition] of [+ [1, 'Payload', 'class DatasetCreatePayload(BaseModel):'],+ [+ 2,+ 'Request',+ 'def post(self, req_data: DatasetCreatePayload, request_context: RequestContext):',+ ],+ [+ 3,+ 'Response',+ 'def post(self, req_data: DatasetCreatePayload, request_context: RequestContext):',+ ],+ ]) {+ const hover = await rpc.request('textDocument/hover', {+ textDocument: { uri },+ position: { line, character: source.split('\n')[line].indexOf(name) },+ })+ const locations = navigation.backendLocations([hover.contents].flat())+ assert.equal(locations.length, 1, JSON.stringify(hover))+ const target = fileURLToPath(locations[0].uri)+ assert.equal(target, resolve(root, '../../api/controllers/console/datasets/datasets.py'))+ assert.equal(+ readFileSync(target, 'utf8').split('\n')[locations[0].line - 1].trim(),+ definition,+ )+ }+ },+)diff --git a/packages/openapi-content-mapper/package.json b/packages/openapi-content-mapper/package.jsonindex c6678eab59c..173aa5dc3c9 100644--- a/packages/openapi-content-mapper/package.json+++ b/packages/openapi-content-mapper/package.json@@ -69,9 +69,66 @@"./errors": {"types": "./dist/errors.d.ts","default": "./dist/errors.js"+ },+ "./console/*": {+ "types": "./contracts/console/*.d.ts"+ },+ "./service": {+ "types": "./contracts/service.d.ts"+ },+ "./web": {+ "types": "./contracts/web.d.ts"+ },+ "./openapi": {+ "types": "./contracts/openapi.d.ts"+ },+ "./enterprise": {+ "types": "./contracts/enterprise.d.ts"+ },+ "./enterprise-app-deploy": {+ "types": "./contracts/enterprise-app-deploy.d.ts"}},"publishConfig": {+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "./vite": {+ "types": "./dist/tooling/vite.d.ts",+ "default": "./dist/tooling/vite.js"+ },+ "./loader": {+ "types": "./dist/tooling/loader.d.ts",+ "default": "./dist/tooling/loader.js"+ },+ "./namespace": {+ "types": "./dist/tooling/openapi-namespace.d.ts",+ "default": "./dist/tooling/openapi-namespace.js"+ },+ "./register": {+ "types": "./dist/tooling/register.d.ts",+ "default": "./dist/tooling/register.js"+ },+ "./mapper": {+ "types": "./dist/tooling/mapper.d.ts",+ "default": "./dist/tooling/mapper.js"+ },+ "./runtime": {+ "types": "./dist/client.d.ts",+ "default": "./dist/client.js"+ },+ "./query-runtime": {+ "types": "./dist/query-runtime.d.ts",+ "default": "./dist/query-runtime.js"+ },+ "./package.json": "./package.json",+ "./errors": {+ "types": "./dist/errors.d.ts",+ "default": "./dist/errors.js"+ }+ },"access": "public","registry": "https://registry.npmjs.org/","tag": "beta"@@ -80,10 +137,12 @@"build": "vp pack","prepare": "pnpm run build","type-check": "tsc -p tsconfig.json --noEmit && tsc --runExternalCode --noEmit -p examples/petstore/tsconfig.json",+ "type-check:contracts": "tsc --runExternalCode --noEmit -p examples/repository/tsconfig.json","test": "node --test --test-concurrency=1 test/*.test.mjs","demo": "node --import ./dist/tooling/register.js examples/petstore/demo.ts","test:next": "node --test integration/next.mjs","test:repository": "node --test integration/*.test.mjs",+ "test:contracts": "node --test integration/contracts-types.test.mjs","compare:orpc": "node integration/compare-orpc.mjs","check:orpc": "node integration/compare-orpc.mjs --check","prepack": "pnpm run build",@@ -100,6 +159,7 @@"yaml": "catalog:"},"devDependencies": {+ "@dify/contracts": "workspace:*","@tanstack/query-core": "catalog:","@types/node": "catalog:","typescript": "catalog:ts71",diff --git a/packages/openapi-content-mapper/src/index.ts b/packages/openapi-content-mapper/src/index.tsindex 3a1373f8d55..4d2fd212b2e 100644--- a/packages/openapi-content-mapper/src/index.ts+++ b/packages/openapi-content-mapper/src/index.ts@@ -5,7 +5,9 @@ export type {InferSchema,RequestOptions,ResponseFor,+ RpcInputs,RpcOperation,+ RpcOutputs,RpcQueryRouter,RpcRouter,SchemaDocument,diff --git a/packages/openapi-content-mapper/src/tooling/mapper.ts b/packages/openapi-content-mapper/src/tooling/mapper.tsindex 283ea64b5c6..fd321c2f525 100644--- a/packages/openapi-content-mapper/src/tooling/mapper.ts+++ b/packages/openapi-content-mapper/src/tooling/mapper.ts@@ -1,4 +1,5 @@import { Buffer } from 'node:buffer'+import { fileURLToPath } from 'node:url'import { record } from '../document.js'import { readFrames } from './framing.js'import { mapperTransform } from './mapper-cache.js'@@ -8,6 +9,7 @@ import { isSource, resolveDocument, sourceProject } from './source.js'const projects = new Map<string, ReturnType<typeof sourceProject>>()let initialized = falseconst transform = mapperTransform()+const bundledDirectory = fileURLToPath(new URL('../../contracts', import.meta.url))async function dispatch(method: string, params: Record<string, unknown>): Promise<string> {switch (method) {@@ -19,7 +21,7 @@ async function dispatch(method: string, params: Record<string, unknown>): Promiscase 'openProject': {if (!initialized || typeof params.projectHandle !== 'string')throw new Error('Initialize the mapper and supply a projectHandle first')- const project = sourceProject(params.configFileName, params.options)+ const project = sourceProject(params.configFileName, params.options, bundledDirectory)projects.set(params.projectHandle, project)return JSON.stringify({configIdentity: project.configIdentity,diff --git a/packages/openapi-content-mapper/src/tooling/schema-types.ts b/packages/openapi-content-mapper/src/tooling/schema-types.tsindex ab93d0de827..6ad55a8cdd4 100644--- a/packages/openapi-content-mapper/src/tooling/schema-types.ts+++ b/packages/openapi-content-mapper/src/tooling/schema-types.ts@@ -84,6 +84,15 @@ export function schemaTypes(root: unknown): string {for (const child of Object.values(value)) collect(child)}collect(root)+ // Public models include components that no operation references. Keep their+ // original names, escaping only the JSON Pointer used to resolve each alias.+ const schemas = Object.keys(record(record(record(root).components).schemas)).map((name) => ({+ name,+ type: reference(+ `#/components/schemas/${name.replaceAll('~', '~0').replaceAll('/', '~1')}`,+ true,+ ),+ }))for (const [path, index] of references) {const schema = pointer(root, path)const ordinary = render(schema, false)@@ -102,5 +111,8 @@ export function schemaTypes(root: unknown): string {declarations.push('};')}declarations.push('}>;')+ declarations.push('export type Schemas = {')+ for (const schema of schemas) declarations.push(`${JSON.stringify(schema.name)}: ${schema.type};`)+ declarations.push('};')return `${declarations.join('\n')}\n`}diff --git a/packages/openapi-content-mapper/src/tooling/source.ts b/packages/openapi-content-mapper/src/tooling/source.tsindex 21abfbfef73..156945c2d1f 100644--- a/packages/openapi-content-mapper/src/tooling/source.ts+++ b/packages/openapi-content-mapper/src/tooling/source.ts@@ -1,13 +1,14 @@import { execFileSync } from 'node:child_process'import { createHash } from 'node:crypto'-import { globSync, readFileSync, statSync } from 'node:fs'+import { existsSync, globSync, readFileSync, statSync } from 'node:fs'import { dirname, resolve } from 'node:path'import { fileURLToPath } from 'node:url'import { record } from '../document.js'const sources = new Map<string, { identity: string; content: string }>()const physicalPath = (file: string) => (file.startsWith('file:') ? fileURLToPath(file) : file)-export const isSource = (file: string) => file.endsWith('.openapi-source')+export const isTypeSource = (file: string) => file.endsWith('.openapi-types')+export const isSource = (file: string) => file.endsWith('.openapi-source') || isTypeSource(file)function strings(value: unknown, name: string): string[] {if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item))@@ -15,23 +16,50 @@ function strings(value: unknown, name: string): string[] {return value as string[]}-/** Source descriptors are authored inputs; the exported OpenAPI document stays in memory. */-export function inspectSource(content: string, fileName: string) {- const file = physicalPath(fileName)- const config = record(JSON.parse(content))- const command = strings(config.command, 'command')- if (!command.length) throw new Error('command must contain an executable')- if (config.cwd !== undefined && typeof config.cwd !== 'string')+type SourceConfig = {+ config: Record<string, unknown>+ cwd: string+ descriptors: Map<string, string>+}++/** Resolve extends and cwd relative to the descriptor that defines them. */+function sourceConfig(content: string, file: string, parents = new Set<string>()): SourceConfig {+ if (parents.has(file)) throw new Error(`Circular source descriptor inheritance: ${file}`)+ parents.add(file)+ const own = record(JSON.parse(content))+ if (own.cwd !== undefined && typeof own.cwd !== 'string')throw new Error('cwd must be a string relative to the source descriptor')- const cwd = resolve(dirname(file), config.cwd ?? '.')+ let inherited: SourceConfig = { config: {}, cwd: dirname(file), descriptors: new Map() }+ if (own.extends !== undefined) {+ if (typeof own.extends !== 'string' || !own.extends)+ throw new Error('extends must be a non-empty relative descriptor path')+ const parent = resolve(dirname(file), own.extends)+ inherited = sourceConfig(readFileSync(parent, 'utf8'), parent, parents)+ }+ inherited.descriptors.set(file, content)+ return {+ config: { ...inherited.config, ...own },+ cwd: own.cwd === undefined ? inherited.cwd : resolve(dirname(file), own.cwd),+ descriptors: inherited.descriptors,+ }+}++/** The directory to watch for files newly matching a glob. */+function globDirectory(pattern: string, cwd: string): string | undefined {+ const wildcard = pattern.search(/[*?{[]/)+ if (wildcard < 0) return undefined+ const prefix = pattern.slice(0, wildcard)+ return resolve(cwd, /[/\\]$/.test(prefix) ? prefix : dirname(prefix))+}++type InputSnapshot = { dependencies: string[]; identity: string }++function inspectInputs(config: Record<string, unknown>, cwd: string): InputSnapshot {const inputs = strings(config.inputs, 'inputs')const exclude = strings(config.exclude ?? [], 'exclude')if (!inputs.length) throw new Error('inputs must declare the files used by the exporter')const env = strings(config.env ?? [], 'env')- const timeout = config.timeoutMs ?? 60000- if (typeof timeout !== 'number' || !Number.isSafeInteger(timeout) || timeout <= 0)- throw new Error('timeoutMs must be a positive integer')- const dependencies = new Set([file])+ const dependencies = new Set<string>()const optional = new Set(strings(config.optionalInputs ?? [], 'optionalInputs').map((input) => resolve(cwd, input)),)@@ -46,12 +74,8 @@ export function inspectSource(content: string, fileName: string) {})const matchedFiles = matches.filter((match) => statSync(resolve(cwd, match)).isFile())if (!matchedFiles.length) throw new Error(`No source input files match ${input} in ${cwd}`)- const wildcard = [...input].findIndex((character) => '*?{['.includes(character))- if (wildcard >= 0) {- const prefix = input.slice(0, wildcard)- const directory = prefix.endsWith('/') || prefix.endsWith('\\') ? prefix : dirname(prefix)- dependencies.add(resolve(cwd, directory))- }+ const directory = globDirectory(input, cwd)+ if (directory) dependencies.add(directory)for (const match of matchedFiles) {const dependency = resolve(cwd, match)dependencies.add(dependency)@@ -60,7 +84,7 @@ export function inspectSource(content: string, fileName: string) {}}const files = [...dependencies].sort()- const hash = createHash('sha256').update(content).update(cwd)+ const hash = createHash('sha256')for (const name of env) hash.update(JSON.stringify([name, process.env[name] ?? null]))for (const dependency of files) {const stat = statSync(dependency, { throwIfNoEntry: false })@@ -83,7 +107,46 @@ export function inspectSource(content: string, fileName: string) {),)}- return { command, cwd, timeout, dependencies: files, identity: hash.digest('hex') }+ return { dependencies: files, identity: hash.digest('hex') }+}++/** Source descriptors are authored inputs; the exported OpenAPI document stays in memory. */+export function inspectSource(+ content: string,+ fileName: string,+ inputSnapshots?: Map<string, InputSnapshot>,+) {+ const file = physicalPath(fileName)+ const { config, cwd, descriptors } = sourceConfig(content, file)+ const command = strings(config.command, 'command')+ if (!command.length) throw new Error('command must contain an executable')+ const args = strings(config.args ?? [], 'args')+ const timeout = config.timeoutMs ?? 60000+ if (typeof timeout !== 'number' || !Number.isSafeInteger(timeout) || timeout <= 0)+ throw new Error('timeoutMs must be a positive integer')+ // This cache lives for one project registration only. Modules sharing input+ // globs reuse the scan, while every project refresh reads fresh filesystem state.+ const key = JSON.stringify([+ cwd,+ config.inputs,+ config.exclude,+ config.optionalInputs,+ config.env,+ ])+ let inputs = inputSnapshots?.get(key)+ if (!inputs) {+ inputs = inspectInputs(config, cwd)+ inputSnapshots?.set(key, inputs)+ }+ const hash = createHash('sha256').update(content).update(cwd).update(inputs.identity)+ for (const [descriptor, text] of descriptors) hash.update(descriptor).update(text)+ return {+ command: [...command, ...args],+ cwd,+ timeout,+ dependencies: [...new Set([...descriptors.keys(), ...inputs.dependencies])].sort(),+ identity: hash.digest('hex'),+ }}export function resolveDocument(content: string, fileName: string) {@@ -109,25 +172,64 @@ export function resolveDocument(content: string, fileName: string) {}// Never cache empty/invalid stdout; exporter logs belong on stderr.const document = record(JSON.parse(output))- if (typeof document.openapi !== 'string' || !document.paths)+ if (isTypeSource(fileName)) {+ if (typeof document.typescript !== 'string' || !document.typescript.trim())+ throw new Error(+ `Type exporter for ${fileName} must write a non-empty typescript string in JSON`,+ )+ } else if (typeof document.openapi !== 'string' || !document.paths)throw new Error(`OpenAPI exporter for ${fileName} must write an OpenAPI document to stdout`)sources.set(fileName, { identity: source.identity, content: output })return { content: output, dependencies: source.dependencies }}/** TS must know external inputs before transforming files, including on incremental builds. */-export function sourceProject(configFileName: unknown, options: unknown) {+export function sourceProject(+ configFileName: unknown,+ options: unknown,+ bundledDirectory?: string,+) {const config = options === undefined || options === null ? {} : record(options)const entries = strings(config.sources ?? [], 'options.sources')if (entries.length && typeof configFileName !== 'string')throw new Error('Command sources require a tsconfig file')const directory =typeof configFileName === 'string' && configFileName ? dirname(configFileName) : process.cwd()- const registered = new Set(entries.map((entry) => resolve(directory, entry)))+ const registered = new Set<string>()const watchedFiles = new Set<string>()+ // Workspace-only contract sources belong to this package, never the consumer.+ // The published SDK has no contracts directory and needs no repository inputs.+ if (bundledDirectory && existsSync(bundledDirectory)) {+ watchedFiles.add(bundledDirectory)+ for (const file of globSync('**/*.openapi-types', { cwd: bundledDirectory }).sort()) {+ registered.add(resolve(bundledDirectory, file))+ let parent = dirname(resolve(bundledDirectory, file))+ while (parent !== bundledDirectory && parent !== dirname(parent)) {+ watchedFiles.add(parent)+ parent = dirname(parent)+ }+ }+ }+ for (const entry of entries) {+ const base = globDirectory(entry, directory)+ if (base) {+ const matches = globSync(entry, { cwd: directory }).sort()+ if (!matches.length) throw new Error(`No source descriptors match ${entry}`)+ for (const match of matches) registered.add(resolve(directory, match))+ watchedFiles.add(base)+ for (const match of matches) {+ let parent = dirname(resolve(directory, match))+ while (parent !== base && parent !== dirname(parent)) {+ watchedFiles.add(parent)+ parent = dirname(parent)+ }+ }+ } else registered.add(resolve(directory, entry))+ }const hash = createHash('sha256')+ const inputSnapshots = new Map<string, InputSnapshot>()for (const file of registered) {- const source = inspectSource(readFileSync(file, 'utf8'), file)+ const source = inspectSource(readFileSync(file, 'utf8'), file, inputSnapshots)hash.update(source.identity)for (const dependency of source.dependencies) watchedFiles.add(dependency)}diff --git a/packages/openapi-content-mapper/src/tooling/transform.ts b/packages/openapi-content-mapper/src/tooling/transform.tsindex 011b4126387..1ab79abfe7c 100644--- a/packages/openapi-content-mapper/src/tooling/transform.ts+++ b/packages/openapi-content-mapper/src/tooling/transform.ts@@ -11,7 +11,7 @@ import { operationConfig } from './operation-config.js'import { createRouter, routerModule, routerModuleId } from './router.js'import { operationConfigFile, runtimeConfigFile } from './runtime-config.js'import { schemaTypes } from './schema-types.js'-import { isSource, resolveDocument } from './source.js'+import { isSource, isTypeSource, resolveDocument } from './source.js'import { typeDocument } from './type-document.js'// Positions use UTF-16, as do YAML's ranges and JavaScript string offsets.@@ -75,6 +75,14 @@ function parseSpec(content: string, fileName: string) {export function transformSpec(content: string, fileName: string): Transform {try {+ // Explicit type-only command sources preserve a generator's public exports.+ // Consumers use import type; runtime values remain in the original contracts.+ if (isTypeSource(fileName)) {+ const { typescript } = record(JSON.parse(content))+ if (typeof typescript !== 'string' || !typescript.trim())+ throw new Error('Expected a non-empty typescript string from the type exporter')+ return { text: typescript, extension: '.ts', mappings: [] }+ }const { document, value, router } = parseSpec(content, fileName)// Only the literal type is needed. An initializer makes TS check the entire// object expression as well as constructing its type, even for unused routes.@@ -205,6 +213,8 @@ export function transformSpec(content: string, fileName: string): Transform {'export declare const api: import("@dify/openapi-content-mapper").RpcRouter<Document, Routes, Context, Errors>;\n'text +='export declare const query: import("@dify/openapi-content-mapper").RpcQueryRouter<Document, Routes, Context, Errors>;\n'+ text += 'export type Inputs = import("@dify/openapi-content-mapper").RpcInputs<typeof api>;\n'+ text += 'export type Outputs = import("@dify/openapi-content-mapper").RpcOutputs<typeof api>;\n'// Exporter output has no source positions in the authored command descriptor.return { text, extension: '.ts', mappings: isSource(fileName) ? [] : mappings }} catch (error) {diff --git a/packages/openapi-content-mapper/src/tooling/vite.ts b/packages/openapi-content-mapper/src/tooling/vite.tsindex eca234f995c..59b7d10d0fa 100644--- a/packages/openapi-content-mapper/src/tooling/vite.ts+++ b/packages/openapi-content-mapper/src/tooling/vite.ts@@ -21,11 +21,27 @@ export function openapi(let server: ViteDevServer | undefinedlet groupErrors = falseconst dependencies = new Map<string, string[]>()+ const watchedDirectories = new Set<string>()+ function watchDirectory(directory: string) {+ if (+ !server ||+ [...watchedDirectories].some(+ (watched) => directory === watched || directory.startsWith(`${watched}${sep}`),+ )+ )+ return+ watchedDirectories.add(directory)+ server.watcher.add(directory)+ }return {name: 'openapi-content-mapper',enforce: 'pre',configureServer(value) {server = value+ // Vite already watches its root recursively. Re-adding directories starts+ // another initial scan, which can swallow new files with ignoreInitial.+ watchedDirectories.clear()+ watchedDirectories.add(resolve(value.config.root))},configResolved(config) {root = config.root@@ -92,10 +108,11 @@ export function openapi(const stat = statSync(dependency, { throwIfNoEntry: false })// Vite treats addWatchFile as an implicit import. Missing optional// inputs and directories belong to the watcher, not its module graph.- if (server && (!stat || stat.isDirectory())) server.watcher.add(dependency)+ if (server && (!stat || stat.isDirectory()))+ watchDirectory(stat?.isDirectory() ? dependency : dirname(dependency))else this.addWatchFile(dependency)}- server?.watcher.add([`${fileName}.queries.ts`, `${fileName}.errors.ts`])+ watchDirectory(dirname(fileName))return {code: render(encoded === undefined ? undefined : JSON.parse(decodeURIComponent(encoded)),diff --git a/packages/openapi-content-mapper/src/types.ts b/packages/openapi-content-mapper/src/types.tsindex 5299137dbd3..b5d80a0a880 100644--- a/packages/openapi-content-mapper/src/types.ts+++ b/packages/openapi-content-mapper/src/types.ts@@ -257,6 +257,18 @@ type RpcInput<O> = O extends unknown: unknown): nevertype RpcResponse<T> = T extends undefined ? void : T+/** The first call argument, including undefined when the operation accepts no input. */+export type RpcInputs<Router> = {+ [K in keyof Router]: Router[K] extends (...args: infer Args) => unknown+ ? Args[0]+ : RpcInputs<Router[K]>+}+/** Decoded successful results, matching awaited API calls (including void). */+export type RpcOutputs<Router> = {+ [K in keyof Router]: Router[K] extends (...args: never[]) => infer Result+ ? Awaited<Result>+ : RpcOutputs<Router[K]>+}/** Resolve operation signatures only when a consumer accesses their route. */export type RpcRouter<S, Routes, Context extends object = object, Errors = object> = {[K in keyof Routes]: Routes[K] extends readonly [diff --git a/packages/openapi-content-mapper/test/aliases.test.mjs b/packages/openapi-content-mapper/test/aliases.test.mjsindex c85500d7184..d2021b9b8af 100644--- a/packages/openapi-content-mapper/test/aliases.test.mjs+++ b/packages/openapi-content-mapper/test/aliases.test.mjs@@ -82,7 +82,12 @@ test('explicit client paths preserve HTTP methods, defaults, error maps, query kjoin(directory, 'consumer.ts'),`import { api, query } from './spec.openapi';+import type { Inputs, Outputs } from './spec.openapi';import { safe } from '@orpc/client';+const input: Inputs['enterprise']['access']['getEnvironmentApi'] = { params: { id: 'a' } };+const output: Outputs['enterprise']['access']['getEnvironmentApi'] = { id: 'a' };+// @ts-expect-error type maps follow the explicit client path too+type OriginalPath = Outputs['environments']['byId']['get'];const [error, data, defined] = await safe(api.enterprise.access.getEnvironmentApi({ params: { id: 'a' } }));if (defined) { const code: 'DENIED' = error.code; }if (data) { const id: string = data.id; }diff --git a/packages/openapi-content-mapper/test/compatibility-sources.test.mjs b/packages/openapi-content-mapper/test/compatibility-sources.test.mjsnew file mode 100644index 00000000000..9d4a05b57b0--- /dev/null+++ b/packages/openapi-content-mapper/test/compatibility-sources.test.mjs@@ -0,0 +1,65 @@+/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise generated descriptors through the real command cache. */+import assert from 'node:assert/strict'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { dirname, join, resolve } from 'node:path'+import { test } from 'node:test'+import { generateCompatibilitySources } from '../../contracts/scripts/generate-compatibility-sources.ts'+import { inspectSource, resolveDocument } from '../dist/tooling/source.js'+/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */++test('generated Community sources refresh cached types after sibling Python dependency changes', async (t) => {+ const repo = mkdtempSync(resolve(import.meta.dirname, '.compatibility-sources-'))+ t.after(() => rmSync(repo, { recursive: true, force: true }))+ function write(path, content) {+ const file = join(repo, path)+ mkdirSync(dirname(file), { recursive: true })+ writeFileSync(file, content)+ return file+ }+ for (const file of [+ 'packages/contracts/api-documents.ts',+ 'packages/contracts/typescript-generation.ts',+ 'packages/contracts/package.json',+ 'packages/contracts/generated/api/web/types.gen.ts',+ 'pnpm-lock.yaml',+ 'api/schema.py',+ 'api/pyproject.toml',+ 'api/uv.lock',+ 'dify-agent/pyproject.toml',+ ])+ write(file, file.endsWith('.json') ? '{}' : '')+ const modelPath = 'dify-agent/src/dify_agent/protocol/knowledge_fs.py'+ const model = write(modelPath, 'class KnowledgeFsCitation: pass\n')+ write(+ 'packages/contracts/scripts/export-compatibility-types.ts',+ `+import { appendFileSync, readFileSync } from 'node:fs';+appendFileSync('exports.log', '1');+const source = readFileSync(${JSON.stringify(modelPath)}, 'utf8');+console.log(JSON.stringify({typescript: 'export type Source = ' + JSON.stringify(source) + ';'}));+`,+ )+ const contracts = join(repo, 'packages/contracts')+ const output = join(repo, 'packages/openapi-content-mapper/contracts')+ await generateCompatibilitySources(contracts, output)+ const file = join(output, 'web.openapi-types')+ const content = readFileSync(file, 'utf8')+ const before = inspectSource(content, file)+ assert(before.dependencies.includes(model))+ const first = resolveDocument(content, file)+ assert.deepEqual(resolveDocument(content, file), first)+ assert.equal(readFileSync(join(repo, 'exports.log'), 'utf8'), '1')+ write(modelPath, 'class KnowledgeFsCitation: extra: str\n')+ const edited = inspectSource(content, file)+ assert.notEqual(edited.identity, before.identity)+ assert.match(JSON.parse(resolveDocument(content, file).content).typescript, /extra: str/)+ assert.equal(readFileSync(join(repo, 'exports.log'), 'utf8'), '11')+ const added = write('dify-agent/src/dify_agent/protocol/new_model.py', 'class NewModel: pass\n')+ const addedIdentity = inspectSource(content, file).identity+ assert.notEqual(addedIdentity, edited.identity)+ rmSync(added)+ assert.notEqual(inspectSource(content, file).identity, addedIdentity)+ const metadata = write('dify-agent/pyproject.toml', '[project]\nversion = "2"\n')+ assert(inspectSource(content, file).dependencies.includes(metadata))+ assert.notEqual(inspectSource(content, file).identity, edited.identity)+})diff --git a/packages/openapi-content-mapper/test/contract-subpaths.test.mjs b/packages/openapi-content-mapper/test/contract-subpaths.test.mjsnew file mode 100644index 00000000000..ab847698898--- /dev/null+++ b/packages/openapi-content-mapper/test/contract-subpaths.test.mjs@@ -0,0 +1,196 @@+/* oxlint-disable vitest/no-import-node-test -- Verify actual package exports with the native compiler and language server. */+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { test } from 'node:test'+import { pathToFileURL } from 'node:url'+import { rpcProcess } from './rpc.mjs'+/* oxlint-enable vitest/no-import-node-test */++const root = resolve(import.meta.dirname, '..')+const compiler = join(root, 'node_modules/typescript/bin/tsc')++for (const moduleResolution of ['NodeNext', 'Bundler']) {+ test(`contract subpaths have typed LSP diagnostics without paths or sources options (${moduleResolution})`, async (t) => {+ const dir = mkdtempSync(join(root, 'test/.subpaths-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ const source = [+ "import type { EnvironmentDeployment, RuntimeState } from '@dify/openapi-content-mapper/enterprise-app-deploy';",+ 'export function environmentId(deployment: EnvironmentDeployment): string {',+ ' return deployment.environment.id;',+ '}',+ 'export type RuntimeStates = typeof RuntimeState;',+ "export const state: RuntimeState = 'RUNTIME_STATE_RUNNING';",+ ].join('\n')+ writeFileSync(join(dir, 'index.ts'), source)+ writeFileSync(+ join(dir, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ strict: true,+ noEmit: true,+ target: 'ES2022',+ module: moduleResolution === 'Bundler' ? 'ESNext' : 'NodeNext',+ moduleResolution,+ },+ contentMappers: [+ {+ package: root,+ extensions: ['.openapi-types'],+ },+ ],+ include: ['index.ts'],+ }),+ )+ const compiled = spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], {+ encoding: 'utf8',+ timeout: 30000,+ })+ assert.ifError(compiled.error)+ assert.equal(compiled.status, 0, compiled.stdout + compiled.stderr)++ const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)+ const uri = pathToFileURL(join(dir, 'index.ts')).href+ try {+ await rpc.request('initialize', {+ processId: process.pid,+ rootUri: pathToFileURL(dir).href,+ initializationOptions: { runExternalCode: true },+ workspaceFolders: [{ uri: pathToFileURL(dir).href, name: 'subpath-consumer' }],+ capabilities: {+ general: { positionEncodings: ['utf-16'] },+ textDocument: {+ diagnostic: { dynamicRegistration: false },+ hover: { contentFormat: ['plaintext'] },+ },+ },+ })+ rpc.notify('initialized', {})+ rpc.notify('textDocument/didOpen', {+ textDocument: { uri, languageId: 'typescript', version: 1, text: source },+ })+ const diagnostics = await rpc.request('textDocument/diagnostic', {+ textDocument: { uri },+ })+ // CLI type checking alone misses TS7016 when the server reports it as a hint.+ assert.deepEqual(diagnostics.items, [], JSON.stringify(diagnostics))+ const hover = await rpc.request('textDocument/hover', {+ textDocument: { uri },+ position: { line: 0, character: source.indexOf('EnvironmentDeployment') },+ })+ assert.match(JSON.stringify(hover), /environment: DeploymentEnvironment/)++ rpc.notify('textDocument/didChange', {+ textDocument: { uri, version: 2 },+ contentChanges: [+ {+ text: `${source}\nexport const invalid: EnvironmentDeployment = { environment: 123 };`,+ },+ ],+ })+ const invalid = await rpc.request('textDocument/diagnostic', {+ textDocument: { uri },+ })+ assert(invalid.items.some((item) => item.code === 2322 && item.severity === 1))+ assert(!invalid.items.some((item) => item.code === 7016))+ } finally {+ rpc.close()+ }+ })+}++test('automatically registered package sources refresh LSP and incremental types after input changes', async (t) => {+ const dir = mkdtempSync(join(root, 'test/.bundled-sources-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ const mapper = join(dir, 'mapper')+ const contracts = join(mapper, 'contracts')+ mkdirSync(contracts, { recursive: true })+ cpSync(join(root, 'dist'), join(mapper, 'dist'), { recursive: true })+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))+ writeFileSync(+ join(mapper, 'package.json'),+ JSON.stringify({ name: 'fixture-mapper', type: 'module', typescript: manifest.typescript }),+ )+ const schema = join(mapper, 'schema.txt')+ writeFileSync(schema, 'string')+ writeFileSync(+ join(mapper, 'export.mjs'),+ `import {readFileSync} from 'node:fs';+process.stdout.write(JSON.stringify({typescript: 'export type Model = {name: ' + readFileSync('schema.txt', 'utf8') + '};'}));`,+ )+ writeFileSync(+ join(contracts, 'shared.json'),+ JSON.stringify({+ cwd: '..',+ command: ['node', 'export.mjs'],+ inputs: ['schema.txt', 'export.mjs'],+ }),+ )+ writeFileSync(+ join(contracts, 'model.openapi-types'),+ JSON.stringify({ extends: './shared.json' }),+ )+ writeFileSync(join(contracts, 'model.d.ts'), "export type * from './model.openapi-types';")+ const source = [+ "import type {Model} from './mapper/contracts/model.d.ts';",+ 'export function name(model: Model): string { return model.name; }',+ ].join('\n')+ writeFileSync(join(dir, 'index.ts'), source)+ writeFileSync(+ join(dir, 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: { strict: true, noEmit: true, incremental: true, module: 'NodeNext' },+ contentMappers: [{ package: mapper, extensions: ['.openapi-types'] }],+ include: ['index.ts'],+ }),+ )+ const compile = () =>+ spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], {+ encoding: 'utf8',+ timeout: 30000,+ })+ const first = compile()+ assert.ifError(first.error)+ assert.equal(first.status, 0, first.stdout + first.stderr)++ const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)+ try {+ await rpc.request('initialize', {+ processId: process.pid,+ rootUri: pathToFileURL(dir).href,+ initializationOptions: { runExternalCode: true },+ capabilities: {+ general: { positionEncodings: ['utf-16'] },+ textDocument: {+ diagnostic: { dynamicRegistration: false },+ hover: { contentFormat: ['plaintext'] },+ },+ },+ })+ rpc.notify('initialized', {})+ const uri = pathToFileURL(join(dir, 'index.ts')).href+ rpc.notify('textDocument/didOpen', {+ textDocument: { uri, languageId: 'typescript', version: 1, text: source },+ })+ const hover = () =>+ rpc.request('textDocument/hover', {+ textDocument: { uri },+ position: { line: 0, character: source.indexOf('Model') },+ })+ assert.match(JSON.stringify(await hover()), /name: string/)+ writeFileSync(schema, 'number')+ rpc.notify('workspace/didChangeWatchedFiles', {+ changes: [{ uri: pathToFileURL(schema).href, type: 2 }],+ })+ assert.match(JSON.stringify(await hover()), /name: number/)+ const diagnostics = await rpc.request('textDocument/diagnostic', { textDocument: { uri } })+ assert(diagnostics.items.some((item) => item.code === 2322))+ const changed = compile()+ assert.ifError(changed.error)+ assert.notEqual(changed.status, 0)+ assert.match(changed.stdout + changed.stderr, /number.*string/)+ } finally {+ rpc.close()+ }+})diff --git a/packages/openapi-content-mapper/test/source.test.mjs b/packages/openapi-content-mapper/test/source.test.mjsindex e730dad3954..710536328ee 100644--- a/packages/openapi-content-mapper/test/source.test.mjs+++ b/packages/openapi-content-mapper/test/source.test.mjs@@ -4,6 +4,7 @@ import { spawnSync } from 'node:child_process'import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { join, resolve } from 'node:path'import { test } from 'node:test'+import { setTimeout as delay } from 'node:timers/promises'import { pathToFileURL } from 'node:url'import { build, createServer } from 'vite'import loader from '../dist/tooling/loader.js'@@ -31,7 +32,7 @@ console.error('Exporter diagnostic');console.log(JSON.stringify({openapi:'3.1.0',info:{title:'Pets',version:'1'},paths:{'/pets':{get:{'x-source-location':{file:'./backend.py',line:7},responses:{200:{description:'OK',content:{'application/json':{schema:{type:readFileSync('schema.txt','utf8')}}}}}}},'/unused':{get:{responses:{204:{description:'OK'}}}}-}}));+},components:{schemas:{Pet:{type:readFileSync('schema.txt','utf8')}}}}));`,)const content = JSON.stringify({@@ -119,7 +120,12 @@ test('TS incremental checks invalidate when backend input changes without touchiconst { directory, schema, config } = fixture(t)writeFileSync(join(directory, 'index.ts'),- "import { api } from './pets.openapi-source'; const result: string = await api.pets.get();",+ `import { api } from './pets.openapi-source';+import type { Schemas, Inputs, Outputs } from './pets.openapi-source';+const input: Inputs['pets']['get'] = undefined;+const result: string = await api.pets.get(input);+const schema: string = null! as Schemas['Pet'];+const output: string = null! as Outputs['pets']['get'];`,)const compile = () =>spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', directory], {@@ -200,55 +206,82 @@ if (await load(undefined, {client: (await import('@dify/openapi-content-mapper')assert(!after.includes('"pets"'))})-// Skipped while flaky on CI: Vite sometimes never reloads after the new input is added on Linux-// runners (Depot and GitHub-hosted), failing unrelated PRs.-test.skip('Vite refreshes command sources when a new backend input is added', async (t) => {- const { directory, file, content } = fixture(t)- writeFileSync(file, JSON.stringify({ ...JSON.parse(content), optionalInputs: ['.env'] }))- const exporter = join(directory, 'export.mjs')- writeFileSync(- exporter,- readFileSync(exporter, 'utf8')- .replace('readFileSync, appendFileSync', 'readFileSync, appendFileSync, existsSync')- .replace("'/pets':", "[existsSync('extra.txt') ? '/animals' : '/pets']:"),- )- writeFileSync(join(directory, 'entry.ts'), "export { api } from './pets.openapi-source'")- const server = await createServer({- configFile: false,- root: directory,- logLevel: 'silent',- plugins: [openapi()],- server: { port: 0 },- })- t.after(() => server.close())- // A new file created during Chokidar's initial scan is not an `add` event- // when ignoreInitial is enabled (notably on Linux).- const watcherReady = new Promise((resolve) => server.watcher.once('ready', resolve))- await server.listen()- await watcherReady- await server.transformRequest('/entry.ts')- await server.transformRequest('/pets.openapi-source')- const url = '/pets.openapi-source?openapi-router=%5B%5D'- assert.match((await server.transformRequest(url)).code, /pets/)- const extra = join(directory, 'extra.txt')- const refreshed = new Promise((resolve, reject) => {- const timeout = setTimeout(- () => reject(new Error('No Vite reload after adding a backend input')),- 10000,+for (const external of [false, true]) {+ test(`Vite refreshes command sources for input additions and removals (${external ? 'outside' : 'inside'} root)`, async (t) => {+ const { directory, file, content } = fixture(t)+ writeFileSync(file, JSON.stringify({ ...JSON.parse(content), optionalInputs: ['backend.env'] }))+ const exporter = join(directory, 'export.mjs')+ writeFileSync(+ exporter,+ readFileSync(exporter, 'utf8')+ .replace('readFileSync, appendFileSync', 'readFileSync, appendFileSync, existsSync')+ .replace(+ "'/pets':",+ "[existsSync('backend.env') ? '/configured' : existsSync('extra.txt') ? '/animals' : '/pets']:",+ ),+ )+ const frontend = external ? join(directory, 'frontend') : directory+ mkdirSync(frontend, { recursive: true })+ writeFileSync(+ join(frontend, 'entry.ts'),+ `export { api } from '${external ? '..' : '.'}/pets.openapi-source'`,)- const send = server.ws.send.bind(server.ws)- server.ws.send = (...args) => {- if (args[0]?.type === 'full-reload' && args[0].triggeredBy === extra) {+ const server = await createServer({+ configFile: false,+ root: frontend,+ logLevel: 'silent',+ plugins: [openapi()],+ server: { port: 0, fs: { allow: [directory] } },+ })+ t.after(() => server.close())+ // New files created during the initial scan are ignored by Chokidar.+ const watcherReady = new Promise((resolve) => server.watcher.once('ready', resolve))+ await server.listen()+ await watcherReady+ await server.transformRequest('/entry.ts')+ const specUrl = external ? `/@fs${file}` : '/pets.openapi-source'+ await server.transformRequest(specUrl)+ const url = `${specUrl}?openapi-router=%5B%5D`+ assert.match((await server.transformRequest(url)).code, /pets/)+ if (external) {+ // External dependencies are discovered on first import, after root readiness.+ // Wait until the recursively watched child has actually been scanned.+ const deadline = Date.now() + 10000+ while (!server.watcher.getWatched()[join(directory, 'unwatched')]?.includes('calls')) {+ assert(Date.now() < deadline, 'External dependency watcher did not become ready')+ await delay(10)+ }+ }+ async function changeInput(input, mutate, expected) {+ const send = server.ws.send.bind(server.ws)+ let timeout+ const refreshed = new Promise((resolve, reject) => {+ timeout = setTimeout(+ () => reject(new Error(`No Vite reload after changing ${input}`)),+ 10000,+ )+ server.ws.send = (...args) => {+ if (args[0]?.type === 'full-reload' && args[0].triggeredBy === input) resolve()+ return send(...args)+ }+ })+ try {+ mutate()+ await refreshed+ assert.match((await server.transformRequest(url)).code, expected)+ } finally {clearTimeout(timeout)- resolve()+ server.ws.send = send}- return send(...args)}+ const extra = join(directory, 'extra.txt')+ await changeInput(extra, () => writeFileSync(extra, 'new backend route'), /animals/)+ await changeInput(extra, () => rmSync(extra), /pets/)+ const env = join(directory, 'backend.env')+ await changeInput(env, () => writeFileSync(env, 'SETTING=value'), /configured/)+ await changeInput(env, () => rmSync(env), /pets/)})- writeFileSync(extra, 'new backend route')- await refreshed- assert.match((await server.transformRequest(url)).code, /animals/)-})+}test('the language server refreshes command-source hover types after backend changes', async (t) => {const { directory, schema } = fixture(t)diff --git a/packages/openapi-content-mapper/test/type-source.test.mjs b/packages/openapi-content-mapper/test/type-source.test.mjsnew file mode 100644index 00000000000..aabe734625d--- /dev/null+++ b/packages/openapi-content-mapper/test/type-source.test.mjs@@ -0,0 +1,175 @@+/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise type-only command sources through the real compiler. */+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { test } from 'node:test'+import { inspectSource, resolveDocument, sourceProject } from '../dist/tooling/source.js'+import { transformSpec } from '../dist/tooling/transform.js'+/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */++const root = resolve(import.meta.dirname, '..')+const compiler = join(root, 'node_modules/typescript/bin/tsc')++test('package sources merge with explicit sources and track shared inputs and module additions', (t) => {+ const dir = mkdtempSync(join(import.meta.dirname, '.package-sources-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ const bundled = join(dir, 'contracts')+ mkdirSync(join(bundled, 'console'), { recursive: true })+ const input = join(dir, 'schema.txt')+ writeFileSync(input, 'string')+ const config = {+ command: ['node', '-e', 'throw new Error("Registration must not run exporters")'],+ cwd: '..',+ inputs: ['schema.txt'],+ }+ const shared = join(bundled, 'shared.json')+ writeFileSync(shared, JSON.stringify(config))+ const descriptor = JSON.stringify({ extends: '../shared.json', args: ['first'] })+ const first = join(bundled, 'console/first.openapi-types')+ writeFileSync(first, descriptor)+ const custom = join(dir, 'custom.openapi-types')+ writeFileSync(custom, JSON.stringify({ ...config, cwd: '.' }))+ const configPath = join(dir, 'tsconfig.json')+ const options = { sources: ['./custom.openapi-types'] }+ const inspect = () => sourceProject(configPath, options, bundled)+ const initial = inspect()+ assert.deepEqual([...initial.registered].sort(), [first, custom].sort())+ for (const file of [bundled, join(bundled, 'console'), first, shared, input, custom])+ assert(initial.watchedFiles.includes(file), file)+ writeFileSync(input, 'number')+ const changed = inspect()+ assert.notEqual(changed.configIdentity, initial.configIdentity)+ writeFileSync(shared, JSON.stringify({ ...config, timeoutMs: 10000 }))+ assert.notEqual(inspect().configIdentity, changed.configIdentity)+ const added = join(bundled, 'console/second.openapi-types')+ writeFileSync(added, descriptor)+ assert(inspect().registered.has(added))+ rmSync(first)+ assert(!inspect().registered.has(first))+ const standalone = sourceProject(configPath, options, join(dir, 'missing-contracts'))+ assert.deepEqual([...standalone.registered], [custom])+})++test('thin type sources inherit cwd and watched inputs and invalidate when shared configuration changes', (t) => {+ const dir = mkdtempSync(join(import.meta.dirname, '.inherited-source-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ mkdirSync(join(dir, 'modules'))+ writeFileSync(join(dir, 'input.txt'), 'string')+ writeFileSync(+ join(dir, 'export.mjs'),+ `+process.stdout.write(JSON.stringify({typescript: 'export type Module = ' + JSON.stringify(process.argv[2]) + ';'}));+`,+ )+ const base = join(dir, 'base.json')+ const config = { command: ['node', 'export.mjs'], inputs: ['input.txt', 'export.mjs'] }+ writeFileSync(base, JSON.stringify(config))+ const file = join(dir, 'modules/types.openapi-types')+ const content = JSON.stringify({ extends: '../base.json', args: ['datasets'] })+ writeFileSync(file, content)+ const inspected = inspectSource(content, file)+ assert.equal(inspected.cwd, dir)+ assert.deepEqual(inspected.command, ['node', 'export.mjs', 'datasets'])+ assert(inspected.dependencies.includes(base))+ assert(inspected.dependencies.includes(join(dir, 'input.txt')))+ assert.match(resolveDocument(content, file).content, /datasets/)+ const before = sourceProject(join(dir, 'tsconfig.json'), {+ sources: ['./modules/*.openapi-types'],+ })+ writeFileSync(base, JSON.stringify({ ...config, timeoutMs: 10000 }))+ const after = sourceProject(join(dir, 'tsconfig.json'), {+ sources: ['./modules/*.openapi-types'],+ })+ assert.notEqual(after.configIdentity, before.configIdentity)+ assert.notEqual(inspectSource(content, file).identity, inspected.identity)+ writeFileSync(base, JSON.stringify({ extends: './modules/types.openapi-types' }))+ assert.throws(() => inspectSource(content, file), /Circular source descriptor/)+ assert.throws(() => inspectSource('{"extends":42}', file), /extends must be/)+ assert.throws(() => inspectSource('{"extends":"../missing.json"}', file), /ENOENT/)+})++test('type sources track inputs, preserve named exports, and invalidate incremental checks', (t) => {+ const dir = mkdtempSync(join(import.meta.dirname, '.type-source-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ mkdirSync(join(dir, 'sources'))+ writeFileSync(join(dir, 'schema.txt'), 'string')+ writeFileSync(+ join(dir, 'export.mjs'),+ `+import {readFileSync} from 'node:fs';+process.stdout.write(JSON.stringify({typescript:+ 'export type Model = {name: ' + readFileSync('schema.txt', 'utf8') + '};' ++ 'export type GetData = {path: {id: string}; url: "/pets/{id}"};' ++ 'export type GetResponses = {200: Model; 204: void};' ++ 'export type GetResponse = GetResponses[keyof GetResponses];' ++ 'export type GetErrors = {404: {code: "missing"}; default: {message: string}};' ++ 'export type GetError = GetErrors[keyof GetErrors];'+}));`,+ )+ const descriptor = JSON.stringify({+ cwd: '..',+ command: ['node', 'export.mjs'],+ inputs: ['schema.txt', 'export.mjs'],+ })+ const source = join(dir, 'sources/types.openapi-types')+ writeFileSync(source, descriptor)+ const config = {+ compilerOptions: {+ strict: true,+ noEmit: true,+ incremental: true,+ skipLibCheck: true,+ target: 'ES2022',+ module: 'NodeNext',+ },+ contentMappers: [+ {+ package: root,+ extensions: ['.openapi-types'],+ options: { sources: ['./sources/*.openapi-types'] },+ },+ ],+ include: ['check.ts'],+ }+ const configPath = join(dir, 'tsconfig.json')+ writeFileSync(configPath, JSON.stringify(config))+ writeFileSync(+ join(dir, 'check.ts'),+ `+import type {Model, GetData, GetResponses, GetResponse, GetErrors, GetError} from './sources/types.openapi-types';+const name: string = (null! as Model).name;+const input: GetData = {path: {id: 'a'}, url: '/pets/{id}'};+const response: GetResponse = null! as GetResponses[200];+const error: GetError = null! as GetErrors[404];+// @ts-expect-error legacy envelopes do not accept params+const wrong: GetData = {params: {id: 'a'}, url: '/pets/{id}'};+// @ts-expect-error status-indexed response maps are retained+type MissingStatus = GetResponses[201];+`,+ )+ const compile = () =>+ spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], { encoding: 'utf8' })+ const first = compile()+ assert.equal(first.status, 0, first.stdout + first.stderr)+ const before = sourceProject(configPath, config.contentMappers[0].options)+ assert(before.registered.has(source))+ writeFileSync(join(dir, 'schema.txt'), 'number')+ assert.notEqual(+ sourceProject(configPath, config.contentMappers[0].options).configIdentity,+ before.configIdentity,+ )+ const changed = compile()+ assert.notEqual(changed.status, 0)+ assert.match(changed.stdout + changed.stderr, /number.*string/)+ writeFileSync(join(dir, 'sources/new.openapi-types'), descriptor)+ assert.equal(sourceProject(configPath, config.contentMappers[0].options).registered.size, 2)+ config.contentMappers[0].options.sources = []+ writeFileSync(configPath, JSON.stringify(config))+ const unregistered = compile()+ assert.notEqual(unregistered.status, 0)+ assert.match(unregistered.stdout + unregistered.stderr, /options.sources/)+ writeFileSync(join(dir, 'export.mjs'), 'process.stdout.write(JSON.stringify({typescript: ""}))')+ assert.throws(() => resolveDocument(readFileSync(source, 'utf8'), source), /non-empty typescript/)+ assert(transformSpec('{"typescript":42}', source).diagnostics)+})diff --git a/packages/openapi-content-mapper/test/types.test.mjs b/packages/openapi-content-mapper/test/types.test.mjsindex 6bc57eb2cb5..4375113664e 100644--- a/packages/openapi-content-mapper/test/types.test.mjs+++ b/packages/openapi-content-mapper/test/types.test.mjs@@ -54,7 +54,7 @@ query.pets.byPetId.get.queryOptions({ input: { params: { petId: 'wrong' } }, con)})-function project(files, run) {+function project(files, run, compilerOptions = {}) {const dir = mkdtempSync(join(root, 'test/.tmp-'))try {writeFileSync(@@ -69,6 +69,7 @@ function project(files, run) {moduleResolution: 'NodeNext',types: ['node'],lib: ['ES2022', 'DOM'],+ ...compilerOptions,},contentMappers: [{ package: root, extensions: ['.yaml', '.yml', '.openapi'] }],include: ['*.ts'],@@ -99,8 +100,24 @@ for (const [extension, content] of [[`pets.${extension}`]: content,'index.ts': `import { api, query } from './pets.${extension}';+import type { Schemas, Inputs, Outputs } from './pets.${extension}';import * as document from './pets.${extension}';-// @ts-expect-error documents expose only api and query+type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;+const inputMatches: Equal<Inputs['pets']['post'], Parameters<typeof api.pets.post>[0]> = true;+const outputMatches: Equal<Outputs['pets']['byPetId']['get'], Awaited<ReturnType<typeof api.pets.byPetId.get>>> = true;+const schemaMatches: Equal<Schemas['Pet'], Outputs['pets']['byPetId']['get']> = true;+const create: Inputs['pets']['post']['body'] = {name: 'Mochi'};+const optionalInput: Inputs['pets']['get'] = undefined;+const deletedOutput: Outputs['pets']['byPetId']['delete'] = undefined;+// @ts-expect-error required inputs cannot be omitted+const missingInput: Inputs['pets']['post'] = undefined;+// @ts-expect-error inline bodies retain required fields+const missingName: Inputs['pets']['post']['body'] = {};+// @ts-expect-error unknown schema names are rejected+type UnknownSchema = Schemas['Missing'];+// @ts-expect-error type exports are not runtime values+document.Schemas;+// @ts-expect-error operation IDs are not exportsdocument.getPet;import { createTanstackQueryUtils } from '@orpc/tanstack-query';const wrappedQuery = createTanstackQueryUtils(api);@@ -163,6 +180,174 @@ api.pets.get({ body: {} });})}+test('public schemas include unused recursive models, escaped names and JSON wire types', () => {+ const binary = { type: 'string', format: 'binary' }+ const spec = {+ openapi: '3.1.0',+ paths: {+ '/upload': {+ post: {+ requestBody: {+ required: true,+ content: {+ 'application/json': { schema: { $ref: '#/components/schemas/File' } },+ 'multipart/form-data': { schema: { $ref: '#/components/schemas/File' } },+ },+ },+ responses: { 204: { description: 'Done' } },+ },+ },+ },+ components: {+ schemas: {+ File: { type: 'object', required: ['data'], properties: { data: binary } },+ 'A/B~C': { type: 'integer' },+ // Public export names cannot collide with schema names.+ Schemas: { type: 'boolean' },+ Unused: {+ type: 'object',+ required: ['value', 'children'],+ properties: {+ value: { $ref: '#/components/schemas/A~1B~0C' },+ children: { type: 'array', items: { $ref: '#/components/schemas/Unused' } },+ },+ },+ },+ },+ }+ project(+ {+ 'spec.openapi': JSON.stringify(spec),+ 'empty.openapi': JSON.stringify({ openapi: '3.1.0', paths: {} }),+ 'index.ts': `+import type { Schemas, Inputs, Outputs } from './spec.openapi';+import type { Schemas as EmptySchemas, Inputs as EmptyInputs, Outputs as EmptyOutputs } from './empty.openapi';+type IsNever<T> = [T] extends [never] ? true : false;+const emptySchemas: IsNever<keyof EmptySchemas> = true;+const emptyInputs: IsNever<keyof EmptyInputs> = true;+const emptyOutputs: IsNever<keyof EmptyOutputs> = true;+const escaped: Schemas['A/B~C'] = 1;+const collision: Schemas['Schemas'] = true;+const jsonFile: Schemas['File'] = {data: 'base64'};+const json: Inputs['upload']['post'] = {body: jsonFile};+const form: Inputs['upload']['post'] = {body: {data: new Blob()}, contentType: 'multipart/form-data'};+// @ts-expect-error schema models use JSON strings, not multipart Blob values+const wrongModel: Schemas['File'] = {data: new Blob()};+// @ts-expect-error the request body must match its media type+const wrongForm: Inputs['upload']['post'] = {body: jsonFile, contentType: 'multipart/form-data'};+// @ts-expect-error JSON is the default media type+const wrongJson: Inputs['upload']['post'] = {body: {data: new Blob()}};+const nothing: Outputs['upload']['post'] = undefined;+type Descend<T, D extends unknown[] = []> = D['length'] extends 60 ? T : T extends {children: (infer C)[]} ? Descend<C, [...D, unknown]> : never;+const deep: number = (null! as Descend<Schemas['Unused']>).value;+// @ts-expect-error unused recursive schemas remain precise beyond inference depth limits+const wrongDeep: string = (null! as Descend<Schemas['Unused']>).value;+`,+ },+ (_dir, compile) => {+ const result = compile()+ assert.equal(result.status, 0, result.output)+ },+ )+})++test('compatibility modules retain existing contracts imports, names and request structure', () => {+ const spec = {+ openapi: '3.1.0',+ paths: {+ '/tags': {+ get: {+ parameters: [+ {+ in: 'query',+ name: 'type',+ required: true,+ schema: { $ref: '#/components/schemas/TagType' },+ },+ { in: 'query', name: 'keyword', schema: { type: 'string' } },+ ],+ responses: {+ 200: {+ content: {+ 'application/json': {+ schema: {+ type: 'array',+ items: { $ref: '#/components/schemas/console_TagResponse' },+ },+ },+ },+ },+ },+ },+ },+ '/tags/{tag_id}': {+ delete: {+ parameters: [{ in: 'path', name: 'tag_id', required: true, schema: { type: 'string' } }],+ responses: { 204: { description: 'Done' } },+ },+ },+ },+ components: {+ schemas: {+ TagType: { type: 'string', enum: ['app', 'knowledge', 'skill', 'snippet'] },+ console_TagResponse: {+ type: 'object',+ required: ['id', 'name'],+ properties: {+ id: { type: 'string' },+ name: { type: 'string' },+ binding_count: { type: ['string', 'null'] },+ type: { type: ['string', 'null'] },+ },+ },+ },+ },+ }+ project(+ {+ 'console.openapi': JSON.stringify(spec),+ 'tags.types.ts': `+import type { Schemas, Inputs, Outputs } from './console.openapi';+export type TagResponse = Schemas['console_TagResponse'];+export type GetTagsResponse = Outputs['tags']['get'];+export type GetTagsData = {+ body?: never;+ path?: never;+ query: Inputs['tags']['get']['query'];+ url: '/tags';+};+export type DeleteTagsByTagIdData = {+ body?: never;+ path: Inputs['tags']['byTagId']['delete']['params'];+ query?: never;+ url: '/tags/{tag_id}';+};+`,+ 'index.ts': `+import type * as Previous from ${JSON.stringify(join(root, '../contracts/generated/api/console/tags/types.gen.ts'))};+import type { TagResponse, GetTagsData, GetTagsResponse, DeleteTagsByTagIdData } from '@dify/contracts/api/console/tags/types.gen';+const tag: TagResponse = null! as Previous.TagResponse;+const oldTag: Previous.TagResponse = null! as TagResponse;+const input: GetTagsData = null! as Previous.GetTagsData;+const oldInput: Previous.GetTagsData = null! as GetTagsData;+const output: GetTagsResponse = null! as Previous.GetTagsResponse;+const oldOutput: Previous.GetTagsResponse = null! as GetTagsResponse;+const deletion: DeleteTagsByTagIdData = null! as Previous.DeleteTagsByTagIdData;+const oldDeletion: Previous.DeleteTagsByTagIdData = null! as DeleteTagsByTagIdData;+// @ts-expect-error legacy request types still require url+const missingUrl: GetTagsData = {query: {type: 'app'}};+// @ts-expect-error legacy request types retain path rather than params+const renamedPath: DeleteTagsByTagIdData = {params: {tag_id: 'id'}, url: '/tags/{tag_id}'};+`,+ },+ (_dir, compile) => {+ const result = compile()+ assert.equal(result.status, 0, result.output)+ },+ { paths: { '@dify/contracts/api/console/tags/types.gen': ['./tags.types.ts'] } },+ )+})+test('schema changes invalidate types on the next native compilation', () => {project({diff --git a/packages/openapi-content-mapper/vscode/README.md b/packages/openapi-content-mapper/vscode/README.mdindex 7d64b66833e..d3e0f784ad0 100644--- a/packages/openapi-content-mapper/vscode/README.md+++ b/packages/openapi-content-mapper/vscode/README.md@@ -7,6 +7,13 @@ extension. TypeScript 7.1 content mappers must already be enabled in the workspaThe extension asks the active TypeScript hover provider for the resolved symbol'sbackend link. It does not run exporters, parse TypeScript, or create index files.Both `api` and `query` method properties are supported, including import aliases.+Repository type subpaths also carry backend links: registered Community models+open their Python classes, and request/response/error envelope types open the+corresponding API handler. Import aliases and type re-exports retain these links.+Try `DatasetCreatePayload` or `PostDatasetsData` in+[`examples/repository/compatibility.ts`].+Synthetic models and Enterprise snapshots without local source metadata have no+backend target.Existing schema definitions remain available; VS Code may show multiple targetswhen a file-backed contract also has a schema definition. Use Go to Implementationto select the backend alone. Missing local backend files are skipped.@@ -20,3 +27,5 @@ code --install-extension openapi-backend-navigation-0.1.0.vsix --forceReload the VS Code window after installation. On `consoleClient.datasets.get`,hover to click **Open backend implementation**, or press F12 on `get`.++[`examples/repository/compatibility.ts`]: ../examples/repository/compatibility.tsdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a832ee95829..559cc34d967 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1353,6 +1353,9 @@ importers:specifier: 'catalog:'version: 2.9.1devDependencies:+ '@dify/contracts':+ specifier: workspace:*+ version: link:../contracts'@tanstack/query-core':specifier: 'catalog:'version: 5.104.4diff --git a/web/tsconfig.json b/web/tsconfig.jsonindex 47f1e2bbc51..e9f5311cebc 100644--- a/web/tsconfig.json+++ b/web/tsconfig.json@@ -24,7 +24,7 @@"contentMappers": [{"package": "@dify/openapi-content-mapper",- "extensions": [".openapi", ".openapi-source"]+ "extensions": [".openapi", ".openapi-source", ".openapi-types"]}]}