@abapify/ts-xsd

中文文档
0.4.34发布于 2026/11/03MITTypeScriptES Module构建来源已验证近 30 天下载 1.4万

W3C XSD 1.1 parser, builder, and TypeScript type inference

原始使用文档
文档目录19 节
  1. Why
  2. Installation
  3. Quick Start
  4. Parse and Build XSD
  5. Type Inference from Schema Literals
  6. Parse and Build XML with a Schema
  7. Generate TypeScript Interfaces from XSD
  8. API Reference
  9. XSD Module
  10. Infer Module
  11. XML Module
  12. Codegen Module
  13. CLI
  14. Config-Based Generation
  15. Schema Structure
  16. Cross-Schema Type Resolution
  17. Design Principles
  18. References
  19. License

ts-xsd

npm version license

W3C XSD 1.1 parser, builder, and TypeScript type inference — a 1:1 TypeScript representation of XML Schema Definition.

Why

Working with XSD schemas in TypeScript usually means hand-maintaining types that drift from the source of truth. ts-xsd closes that gap:

  • Parse any W3C XSD 1.1 schema into a typed Schema object — no invented properties, no shortcuts.
  • Infer TypeScript types at compile time from schema literals via InferSchema<T>.
  • Generate TypeScript interfaces at build time when schemas are too complex for compile-time inference.
  • Round-trip XSD → Schema → XSD with semantic preservation.
  • Parse/build XML documents against a schema definition.

Installation

npm install @abapify/ts-xsd
# or
pnpm add @abapify/ts-xsd
# or
bun add @abapify/ts-xsd

Runtime dependency: @xmldom/xmldom (DOM parsing). ts-morph and zod are required for codegen features.

Quick Start

Parse and Build 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 });

Type Inference from Schema Literals

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 }

Parse and Build XML with a Schema

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>

Generate TypeScript Interfaces from 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 Reference

XSD Module

import {
  parseXsd,
  buildXsd,
  resolveImports,
  loadSchema,
  type Schema,
} from '@abapify/ts-xsd';

parseXsd(xsd: string): Schema

Parse an XSD XML string into a typed Schema object.

buildXsd(schema: Schema, options?: BuildOptions): string

Build an XSD XML string from a Schema object.

const xsd = buildXsd(schema, {
  prefix: 'xs', // Namespace prefix (default: 'xs')
  pretty: true, // Pretty print (default: true)
  indent: '  ', // Indentation string
});

resolveImports(schema, availableSchemas): Schema

Resolve and link imported schemas by matching import.schemaLocation to $filename. Returns a new schema with $imports populated.

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

Load and parse an XSD file from disk. Synchronous. Set autoLink: true to automatically resolve imports, or autoResolve: true to merge everything into one schema.

const schema = loadSchema('/path/to/schema.xsd', { autoLink: true });

Infer Module

import type { InferSchema, InferElement, SchemaLike } from '@abapify/ts-xsd';

InferSchema<T>

Infer a TypeScript type from a schema literal (as const). Returns a union of all root element types.

InferElement<T, Name>

Infer the type for a specific root element by name.

type Person = InferElement<typeof schema, 'person'>;

Built-in Type Mapping

XSD TypeTypeScript
xs:string, xs:token, xs:NCNamestring
xs:int, xs:integer, xs:decimalnumber
xs:booleanboolean
xs:date, xs:dateTime, xs:timestring
xs:anyURI, xs:QNamestring
xs:anyTypeunknown

XML Module

import { parseXml, buildXml } from '@abapify/ts-xsd';

parseXml<T>(schema, xml: string): T

Parse an XML string into a typed object using a schema definition.

buildXml<T>(schema, data: T, options?: XmlBuildOptions): string

Build an XML string from a typed object using a schema definition. Defaults to xmlDecl: true (includes <?xml ...?> declaration); pass { xmlDecl: false } for bare output.

Codegen Module

import { generateSchemaLiteral, generateInterfaces } from '@abapify/ts-xsd';

generateSchemaLiteral(xsd: string, options?): string

Generate a TypeScript as const schema literal from XSD content — for use with 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 }

Generate TypeScript interfaces from a parsed schema. Useful when schemas are too complex for compile-time InferSchema<T> (TypeScript TS2589 recursion limits).

const { code } = generateInterfaces(schema, {
  flatten: true, // Inline all nested types (default: false)
  addJsDoc: true, // JSDoc comments
  rootTypeName: 'MySchema',
});
OptionTypeDefaultDescription
flattenbooleanfalseInline all nested types into one
addJsDocbooleanfalseAdd JSDoc comments
rootTypeNamestringautoCustom name for the root type

CLI

The package ships a CLI for code generation:

# 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

Config-Based Generation

For multi-schema projects, use the composable generator system:

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 Structure

The Schema type is a 1:1 TypeScript representation of W3C XSD. Non-W3C extension properties are prefixed with $:

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)
}

Cross-Schema Type Resolution

Link schemas via $imports to resolve types across schema boundaries:

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>;

Design Principles

  1. Pure W3C XSD 1.1 — types match the official XMLSchema.xsd exactly; no invented properties.
  2. Type-safe — full TypeScript support with compile-time inference.
  3. Minimal dependencies — @xmldom/xmldom for DOM parsing, ts-morph and zod for codegen.
  4. Tree-shakeable — import only what you need.
  5. Round-trip verified — tested against the official W3C XMLSchema.xsd.

References

License

MIT

版本与发布记录

@abapify/ts-xsd 共发布 31 个版本,首次发布于 2026/04/21;过去 12 个月发布了 31 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.34latest2026/11/033 天前
0.4.332026/11/023 天前
0.4.322026/11/023 天前
0.4.302026/10/316 天前
0.4.292026/10/306 天前
0.4.272026/10/307 天前

关于 @abapify/ts-xsd 的常见问题

@abapify/ts-xsd 是什么?

W3C XSD 1.1 parser, builder, and TypeScript type inference

如何安装 @abapify/ts-xsd?

在项目目录运行 npm install @abapify/ts-xsd,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 ts-xsd,可以用 npx ts-xsd 直接运行。

@abapify/ts-xsd 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@abapify/ts-xsd 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@abapify/ts-xsd 可以商用吗?

@abapify/ts-xsd 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@abapify/ts-xsd 的下载量有多少?

根据 npm 官方下载统计,@abapify/ts-xsd 在 2026/10/05 – 2026/11/03 这 30 天内被下载 13,560 次,日均约 452 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@abapify/ts-xsd 还在维护吗?

最新版本 0.4.34 发布于 2026/11/03(3 天前);至今共发布 31 个版本,其中过去 12 个月发布了 31 个;首次发布于 2026/04/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。