t-xsd
W3C XSD 1. 1 解析器, 构建器, 和 TypeScript 类型推论 —— 1:1 TypeScript 代表 XML Schema 定义.
为什么
在TypeScript中与XSD schemas合作,通常指从真理源来漂移的手持型. ts-xsd 缩小这一差距:
- 解析 任意 W3C XSD 1.1 计程器为打入
Schema对象——没有发明属性,没有快捷键. - 推断 编译时的脚本类型
InferSchema<T>。 。 。 . - 生成 TypeScript 接口在构建时,当计划过于复杂,无法编译时间推论.
- 往返旅行
XSD → Schema → XSD和语义保护. - 解析/ 构建 XML 文档与计划定义相对应.
安装
npm install @abapify/ts-xsd
# or
pnpm add @abapify/ts-xsd
# or
bun add @abapify/ts-xsd
运行时间依赖 :
@xmldom/xmldom(DOM解析).ts-morph财务报告和审定财务报表zod用于代码特性.
快速启动
分析并构建 XSD
import { parseXsd, buildXsd } from '@abapify/ts-xsd';
// Parse XSD to typed Schema object
const schema = parseXsd(`
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="person" type="PersonType"/>
<xs:complexType name="PersonType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:int" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
`);
// Build back to XSD
const xsd = buildXsd(schema, { pretty: true });
Schema 文学的推论
import type { InferSchema } from '@abapify/ts-xsd';
const personSchema = {
element: [{ name: 'person', type: 'PersonType' }],
complexType: [
{
name: 'PersonType',
sequence: {
element: [
{ name: 'name', type: 'xs:string' },
{ name: 'age', type: 'xs:int', minOccurs: 0 },
],
},
},
],
} as const;
// Infer TypeScript type at compile time — no runtime cost
type Person = InferSchema<typeof personSchema>;
// => { name: string; age?: number }
分析并用 Schema 构建 XML
import { parseXml, buildXml } from '@abapify/ts-xsd';
const xml = `<person><name>John</name><age>30</age></person>`;
const data = parseXml(personSchema, xml);
// => { person: { name: 'John', age: 30 } }
const rebuilt = buildXml(personSchema, data, { xmlDecl: false });
// => <person><name>John</name><age>30</age></person>
从 XSD 生成类型脚本接口
import { parseXsd, generateInterfaces } from '@abapify/ts-xsd';
const schema = parseXsd(xsdContent);
const { code } = generateInterfaces(schema, {
flatten: true, // Inline all nested types into one
addJsDoc: true, // Add JSDoc comments
rootTypeName: 'MySchema',
});
// code is a ready-to-write .ts file:
// export type MySchema = { person: { name: string; age?: number } };
API 参考
XSD 模块
import {
parseXsd,
buildXsd,
resolveImports,
loadSchema,
type Schema,
} from '@abapify/ts-xsd';
parseXsd(xsd: string): Schema
将 XSD XML 字符串分析为已键入 Schema 对象.
buildXsd(schema: Schema, options?: BuildOptions): string
从 a 构建 XSD XML 字符串 Schema 对象.
const xsd = buildXsd(schema, {
prefix: 'xs', // Namespace prefix (default: 'xs')
pretty: true, // Pretty print (default: true)
indent: ' ', // Indentation string
});
resolveImports(schema, availableSchemas): Schema
通过匹配解决和链接导入的策略 import.schemaLocation 改为 $filename返回新的计划 $imports 人口众多.
const base = { ...parseXsd(baseXsd), $filename: 'base.xsd' };
const orders = { ...parseXsd(ordersXsd), $filename: 'orders.xsd' };
const linked = resolveImports(orders, [base]);
// linked.$imports = [base]
loadSchema(schemaPath: string, options?: LoaderOptions): Schema
从磁盘上装入并解析一个 XSD 文件 。 同步。 设定 autoLink: true 自动解决进口,或 autoResolve: true 将一切合并为一个计划.
const schema = loadSchema('/path/to/schema.xsd', { autoLink: true });
推断模块
import type { InferSchema, InferElement, SchemaLike } from '@abapify/ts-xsd';
InferSchema<T>
从图文体中推断出一个类型( S) :as const) (中文(简体) ). 返回所有根元素类型的结合.
InferElement<T, Name>
按名称推断特定根元素的类型.
type Person = InferElement<typeof schema, 'person'>;
内建类型映射
| XSD 类型 | 类型脚本 |
|---|---|
xs:string, (中文(简体) ), xs:token, (中文(简体) ), xs:NCName | string |
xs:int, (中文(简体) ), xs:integer, (中文(简体) ), xs:decimal | number |
xs:boolean | boolean |
xs:date, (中文(简体) ), xs:dateTime, (中文(简体) ), xs:time | string |
xs:anyURI, (中文(简体) ), xs:QName | string |
xs:anyType | unknown |
XML 模块
import { parseXml, buildXml } from '@abapify/ts-xsd';
parseXml<T>(schema, xml: string): T
使用 schema 定义将 XML 字符串分析成一个被输入的对象 .
buildXml<T>(schema, data: T, options?: XmlBuildOptions): string
使用 schema 定义从打字对象中构建 XML 字符串 。 默认为 xmlDecl: true (包括: <?xml ...?> 声明); 通过 { xmlDecl: false } 用于裸出.
代码模块
import { generateSchemaLiteral, generateInterfaces } from '@abapify/ts-xsd';
generateSchemaLiteral(xsd: string, options?): string
生成类型脚本 as const 由 XSD 内容生成的图案文字——用于 InferSchema<T>。 。 。 .
const code = generateSchemaLiteral(xsdContent, {
name: 'PersonSchema',
features: { $xmlns: true, $filename: true },
exclude: ['annotation'],
});
// export const PersonSchema = { ... } as const;
generateInterfaces(schema: Schema, options?): { code: string }
从解析的 schema 生成 TypeScript 接口 。 当计划过于复杂而无法编译时有用 InferSchema<T> (TypeScript TS2589 复发限制).
const { code } = generateInterfaces(schema, {
flatten: true, // Inline all nested types (default: false)
addJsDoc: true, // JSDoc comments
rootTypeName: 'MySchema',
});
| 选项 | 类型 | 默认 | 说明 |
|---|---|---|---|
flatten | boolean | false | 将所有嵌入类型内置为一 |
addJsDoc | boolean | false | 添加联合来文文件评论 |
rootTypeName | string | 自动 | 根类型自定义名称 |
国 际
包装一个CLI用于代码生成:
# Config-based (recommended) — uses ts-xsd.config.ts in cwd
npx ts-xsd codegen
# Single-file mode
npx ts-xsd codegen person.xsd
npx ts-xsd codegen person.xsd ./generated/person-schema.ts
npx ts-xsd codegen person.xsd --name=PersonSchema
基于配置的生成
对于多方案项目,使用可堆肥发电机系统:
import {
defineConfig,
rawSchema,
interfaces,
} from '@abapify/ts-xsd/generators';
export default defineConfig({
sources: {
base: {
xsdDir: 'schemas',
outputDir: 'src/generated',
schemas: ['base'],
},
orders: {
xsdDir: 'schemas',
outputDir: 'src/generated',
schemas: ['orders'],
autoLink: true,
},
},
generators: [rawSchema(), interfaces({ flatten: true })],
});
Schema 结构
这个 Schema 类型是 W3C XSD 的 1:1 类型脚本代表。 非W3C扩展属性前缀为 $数字 :
interface Schema {
targetNamespace?: string;
elementFormDefault?: 'qualified' | 'unqualified';
// Composition
import?: Import[];
include?: Include[];
// Declarations
element?: TopLevelElement[];
complexType?: TopLevelComplexType[];
simpleType?: TopLevelSimpleType[];
group?: NamedGroup[];
attributeGroup?: NamedAttributeGroup[];
// Extensions (non-W3C, prefixed with $)
$xmlns?: { [prefix: string]: string }; // Namespace prefix mappings
$imports?: Schema[]; // Linked imported schemas
$filename?: string; // Source filename (for round-trip)
}
跨计划类型分辨率
链接计划通过 $imports 解决跨越计划边界的类别:
const base = { ...parseXsd(baseXsd), $filename: 'base.xsd' };
const orders = { ...parseXsd(ordersXsd), $filename: 'orders.xsd' };
const linked = resolveImports(orders, [base]);
// InferSchema can now resolve types from `base`
type OrderData = InferSchema<typeof linked>;
设计原则
- 纯 W3C XSD 1.1 - 类型与官员匹配 XML 计划 准确; 没有发明属性 .
- 类型安全 ——全TypeScript支持以编译-时间推论.
- 最小依赖性 —— 说
@xmldom/xmldom为DOM解析,ts-morph财务报告和审定财务报表zod代码源. - 树能震动 - 进口你需要的东西.
- 经核实的往返旅行 ——针对官方W3C XMLSchema.xsd进行测试.