<p align="center">
  <a href="https://asterdoc.com?utm_source=github&utm_medium=core" target="_blank" rel="noopener noreferrer">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://assets.asterdoc.com/asterdoc-logo-400x400-dark.png" type="image/png">
      <img src="https://assets.asterdoc.com/asterdoc-logo-400x400-dark.png" height="64" alt="Asterdoc logo">
    </picture>
  </a>
  <br />
</p>

<h1 align="center">@asterdoc/core</h1>

<div align="center">

[![Asterdoc documentation](https://img.shields.io/badge/Documentation-Asterdoc-red.svg)](https://docs.asterdoc.com?utm_source=github&utm_medium=core)
[![Follow on Twitter](https://img.shields.io/twitter/follow/asterdoc?style=social)](https://x.com/intent/follow?screen_name=asterdoc)

</div>

[Asterdoc](https://asterdoc.com?utm_source=github&utm_medium=core) is **documents as code**. It lets developers and AI agents define, validate, and render business documents using typed, composable schemas. This eliminates template drift, broken mappings, and brittle glue code — while giving AI systems a reliable document layer they can safely read, reason over, and generate against in production workflows.

## Package overview

Fundamental package for modeling business documents as typed, versioned artifacts. Provides builders for Forms, Documents, Checklists, and Bundles with schema-driven validation and composition.

- 🏗️ **Type-safe builders** - Fluent API for defining document structures
- 📋 **Four artifact types** - Form, Document, Checklist, and Bundle builders
- ✅ **Schema-driven validation** - Built-in structure and constraint validation
- 🎯 **Composable design** - Reuse fields and artifacts across definitions
- 📦 **Standalone library** - Use independently or with @asterdoc/sdk

JSON Schema exports are maintained by `@asterdoc/schemas`. To regenerate the
latest and versioned bundles, run:

```bash
pnpm --filter @asterdoc/schemas export:bundled-schema
```

## Installation

```bash
npm install @asterdoc/core
```

## Usage

Define forms with parties, fields, and validation rules:

```typescript
import { a } from "@asterdoc/core";

const leaseAgreement = a
  .form()
  .name("residential-lease-agreement")
  .version("1.0.0")
  .title("Residential Lease Agreement")
  .defaultLayer("markdown")
  .layers({
    markdown: a
      .layer()
      .file()
      .mimeType("text/markdown")
      .path("fixtures/lease-agreement.md"),
  })
  .parties({
    landlord: a
      .party()
      .label("Landlord")
      .signature({ required: true }),
    tenant: a
      .party()
      .label("Tenant")
      .min(1)
      .max(4)
      .signature({ required: true }),
  })
  .fields({
    leaseId: { type: "uuid", label: "Lease ID" },
    propertyAddress: {
      type: "address",
      label: "Property Address",
      required: true,
    },
    monthlyRent: { type: "money", label: "Monthly Rent", required: true },
    leaseStartDate: { type: "date", label: "Lease Start Date", required: true },
  })
  .build();
```

Define repeated values with recursive List fields:

```typescript
const contacts = a.field
  .list()
  .label("Contacts")
  .item(a.field.email().label("Email").required().build())
  .minItems(1)
  .build();
```

Add file attachments and advanced field types:

```typescript
const advancedLease = a
  .form()
  .name("commercial-lease")
  .version("1.0.0")
  .title("Commercial Lease Agreement")
  .allowAdditionalAnnexes(true)
  .annexes({
    photoId: a.annex().title("Photo ID").required(true),
    proofOfIncome: a.annex().title("Proof of Income").required(true),
  })
  .parties({
    landlord: a
      .party()
      .label("Landlord")
      .signature({ required: true }),
    tenant: a
      .party()
      .label("Tenant")
      .max(4)
      .signature({ required: true }),
  })
  .fields({
    leaseId: { type: "uuid", label: "Lease ID", required: true },
    leaseTermMonths: {
      type: "number",
      label: "Lease Term (months)",
      required: true,
    },
    monthlyRent: { type: "money", label: "Monthly Rent", required: true },
    petPolicy: {
      type: "enum",
      enum: [{ value: "no-pets" }, { value: "small-pets" }, { value: "all-pets" }],
      label: "Pet Policy",
      required: true,
    },
  })
  .build();
```

Define static documents with metadata:

```typescript
const leadPaintDisclosure = a
  .document()
  .name("lead-paint-disclosure")
  .version("1.0.0")
  .title("Lead Paint Disclosure")
  .code("EPA-747-K-12-001")
  .issuer("U.S. Environmental Protection Agency")
  .edition({ key: "2025-12", label: "Rev. December 2025", date: "2025-12" })
  .metadata({ agency: "EPA/HUD", cfr: "40 CFR 745" })
  .layers({
    pdf: a
      .layer()
      .file()
      .path("fixtures/lead-paint-disclosure.pdf")
      .mimeType("application/pdf"),
  })
  .defaultLayer("pdf")
  .build();
```

Define workflow checklists with status tracking:

```typescript
const leaseChecklist = a
  .checklist()
  .name("lease-application-checklist")
  .version("1.0.0")
  .title("Lease Application Checklist")
  .items([
    {
      id: "application_received",
      title: "Application Received",
      status: { kind: "boolean" },
    },
    {
      id: "credit_check",
      title: "Credit Check Complete",
      status: { kind: "boolean" },
    },
    {
      id: "background_check",
      title: "Background Check Complete",
      status: { kind: "boolean" },
    },
    { id: "lease_signed", title: "Lease Signed", status: { kind: "boolean" } },
  ])
  .build();
```

Compose artifacts into bundles:

```typescript
const propertyAddress = {
  type: "address",
  label: "Property Address",
  required: true,
};
const monthlyRent = { type: "money", label: "Monthly Rent", required: true };

const residentialLease = a
  .form()
  .name("residential-lease")
  .version("1.0.0")
  .fields({ leaseId: { type: "uuid" }, propertyAddress, monthlyRent })
  .build();

const commercialLease = a
  .form()
  .name("commercial-lease")
  .version("1.0.0")
  .fields({ leaseId: { type: "uuid" }, propertyAddress, monthlyRent })
  .build();

const leaseBundle = a
  .bundle()
  .name("residential-lease-bundle")
  .version("1.0.0")
  .contents([
    { type: "inline", key: "residential", artifact: residentialLease.toJSON({ includeSchema: false }) },
    { type: "inline", key: "commercial", artifact: commercialLease.toJSON({ includeSchema: false }) },
    { type: "inline", key: "disclosure", artifact: leadPaintDisclosure.toJSON({ includeSchema: false }) },
    { type: "inline", key: "checklist", artifact: leaseChecklist.toJSON({ includeSchema: false }) },
  ])
  .build();
```

Extract TypeScript types from artifacts:

```typescript
import { type InferFormPayload } from "@asterdoc/core";

type LeaseData = InferFormPayload<typeof leaseAgreement>;

const data: LeaseData = {
  fields: {
    leaseId: "550e8400-e29b-41d4-a716-446655440000",
    propertyAddress: {
      line1: "123 Main St",
      locality: "Portland",
      region: "OR",
      postalCode: "97201",
      country: "USA",
    },
    monthlyRent: { amount: 1500, currency: "USD" },
    leaseStartDate: "2024-02-01",
  },
};
```

Validate and fill forms with data:

```typescript
// Check if the form schema itself is valid
if (!leaseAgreement.isValid()) {
  console.log("Form schema is invalid");
}

// Fill the form with data (validates during fill)
try {
  const filled = leaseAgreement.fill(data);
  console.log("Form filled successfully");
} catch (error) {
  console.error("Validation failed:", error);
}

// Or use safeFill to avoid exceptions
const result = leaseAgreement.safeFill(data);
if (result.success) {
  const filled = result.data;
} else {
  console.error("Validation failed:", result.error);
}
```

Every write stores the canonical value: a `country` field its ISO 3166-1 code (`CA`), a `region` field its ISO 3166-2 code (`US-TX`), a `codes: true` address both codes (`US`, `TX`), and masked text without the mask's separators. A value that cannot be resolved fails with a `code` and, for a place, the `candidates` to choose from:

```typescript
const residency = a
  .form()
  .name("residency")
  .version("1.0.0")
  .fields({
    country: { type: "country", label: "Country" },
    taxId: { type: "text", label: "Tax ID", mask: "##-#######" },
  })
  .build();

residency.fill({ fields: { country: "Canada", taxId: "12-3456789" } });
// stores { country: "CA", taxId: "123456789" }

residency.safeFill({ fields: { country: "Canda" } }).error?.errors[0];
// { field: "fields.country", code: "unknown_country", candidates: [{ code: "CA", name: "Canada" }, ...], ... }
```

A form's own `tests` run with `runTests()`. `render({ require: "complete" })` refuses a form that `seal()` would refuse. Render and seal verify a file layer's `checksum` and throw `LayerChecksumError` on a mismatch, and `contentHash()` returns the `sha256:` digest of the stored definition. An artifact written for an older schema date upgrades in memory on load and records it in `migratedFrom`; `strictSchema: true` refuses it, and a date newer than the SDK knows is an error.

Forms render PDF, DOCX, HTML, Markdown, and text layers with the built-in MIME-selected renderer. Pass a custom renderer to `.render()` or `.seal()` only when overriding that default. For API reference and advanced patterns, visit [docs.asterdoc.com](https://docs.asterdoc.com).

## Changelog

View the [Changelog](https://github.com/asterdoc/asterdoc/blob/main/CHANGELOG.md) for updates.

## Related packages

- [`@asterdoc/sdk`](../sdk) - Complete framework with renderers
- [`@asterdoc/types`](../types) - TypeScript utilities and types
- [`@asterdoc/schemas`](../schemas) - JSON Schema definitions
- [`@asterdoc/render`](../render) - MIME-selected PDF, DOCX, and text rendering
- [`@asterdoc/resolvers`](../resolvers) - File and environment resolvers

## Contributing

We're open to all community contributions! If you'd like to contribute in any way, please read our [contribution guidelines](https://github.com/asterdoc/asterdoc/blob/main/CONTRIBUTING.md) and [code of conduct](https://github.com/asterdoc/asterdoc/blob/main/CODE_OF_CONDUCT.md).

## License

This project is licensed under the MIT license.

See [LICENSE](https://github.com/asterdoc/asterdoc/blob/main/LICENSE) for more information.
