feat(interfaces): add comprehensive TypeScript interface modules, demo data, docs, and publish metadata

This commit is contained in:
2025-12-18 15:25:36 +00:00
parent f46d8a54cd
commit f3f03bbc57
24 changed files with 6357 additions and 169 deletions

476
readme.md
View File

@@ -1,14 +1,24 @@
# @signature.digital/tools
A TypeScript package providing utility interfaces and classes for efficient digital contract management and business context integration with a modular design. 📝
A comprehensive TypeScript library for **digital contract management** covering every stage from drafting and collaboration to e-signatures, legal compliance, and archival. 📜✨
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
## Features at a Glance
Install using your preferred package manager:
🔹 **99.9% Contract Coverage** Supports employment, service, sales, lease, license, NDA, financial, and dozens more contract types
🔹 **eIDAS Compliant Signatures** Simple, advanced, and qualified electronic signatures with full audit trails
🔹 **Identity Verification** Passport/NFC, document+selfie, video ident, and third-party IdP support
🔹 **Legal Compliance** RFC 3161 TSA timestamps, blockchain anchoring, LTV (Long-Term Validation)
🔹 **Version Control** Semantic versioning, branches, diffs, and amendment tracking
🔹 **Real-time Collaboration** Comments, suggestions, presence tracking, conflict resolution
🔹 **Complete Audit Logs** Hash-chained, tamper-evident action history
🔹 **PDF Generation** Configurable templates, branding, security, and digital signing
🔹 **TypeScript-First** Full type safety with comprehensive interfaces and factory functions
## Install
```bash
# Using pnpm (recommended)
@@ -18,149 +28,397 @@ pnpm add @signature.digital/tools
npm install @signature.digital/tools
```
## Usage
This package provides TypeScript interfaces for modeling digital contracts with support for roles, paragraphs, and involved parties.
### Core Interfaces
The package exports these key interfaces:
## Quick Start
```typescript
import type {
IPortableContract,
IRole,
IInvolvedParty,
IParagraph,
import {
createEmptyContract,
createRole,
createInvolvedParty,
createParagraph,
type IPortableContract,
} from '@signature.digital/tools';
// Create a new employment contract
const contract = createEmptyContract(
'Software Developer Employment Agreement',
'employment',
'employment_full_time',
'user-123',
'en'
);
// Define roles
const employerRole = createRole('employer', 'Employer', 'The hiring company');
const employeeRole = createRole('employee', 'Employee', 'The hired individual');
contract.availableRoles.push(employerRole, employeeRole);
// Add contract content
contract.paragraphs.push(
createParagraph('Scope of Work', 'The Employee shall perform software development duties...', 'clause', 1),
createParagraph('Compensation', 'The Employee shall receive a monthly salary of...', 'clause', 2)
);
console.log(contract.id); // UUID
console.log(contract.lifecycle.currentStatus); // 'draft'
```
### Interface Overview
## Package Structure
#### `IPortableContract`
This package provides **three entry points**:
The main contract interface containing:
| Entry Point | Package Name | Description |
|-------------|--------------|-------------|
| `@signature.digital/tools` | `@signature.digital/tools` | Main export re-exports all interfaces |
| `@signature.digital/tools/interfaces` | `@signature.digital/interfaces` | Core TypeScript interfaces |
| `@signature.digital/tools/demodata` | `@signature.digital/demodata` | Demo contracts for testing |
- `title` - Contract title
- `context` - Description of the contract context
- `availableRoles` - Array of available roles
- `involvedParties` - Parties involved with their contacts
- `priorContracts` - Reference to preceding contracts
- `paragraphs` - Contract content sections
## Core Concepts
#### `IRole`
### 📄 Contract Types
Defines a role within the contract:
The library supports a comprehensive taxonomy of contract types:
```typescript
interface IRole {
id: string;
type TContractCategory =
| 'employment' // Full-time, part-time, minijob, freelance, executive...
| 'service' // SLA, MSA, maintenance, support agreements
| 'sales' // Purchase orders, distribution, supply agreements
| 'lease' // Residential, commercial, equipment, vehicle
| 'license' // Software, patent, trademark, franchise
| 'partnership' // Joint ventures, strategic alliances
| 'confidentiality' // NDA (unilateral/bilateral/multilateral)
| 'financial' // Loans, guarantees, investments
| 'other'; // Settlement, POA, LOI, MOU
```
### 🔐 Signature System
Full support for eIDAS-compliant signatures:
```typescript
import type { ISignature, TSignatureType, TSignatureLegalLevel } from '@signature.digital/tools';
// Supported signature types
type TSignatureType = 'drawn' | 'typed' | 'click' | 'digital' | 'qualified' | 'biometric';
// eIDAS legal levels
type TSignatureLegalLevel = 'simple' | 'advanced' | 'qualified';
```
**Signature data structures** include:
- **Drawn signatures** Stroke data from signature pads (compatible with signature_pad library)
- **Typed signatures** Text with font styling
- **Click-to-sign** Acknowledgment-based acceptance
- **Digital signatures** X.509/PKI certificate-based (PKCS#7)
- **Qualified signatures** eIDAS QES via QTSP
- **Biometric** Fingerprint, facial, voice (extensible)
### 🪪 Identity Verification
```typescript
import type { IIdentityVerificationResult, TIdentityVerificationMethod } from '@signature.digital/tools';
// Supported verification methods
type TIdentityVerificationMethod =
| 'email' | 'sms' | 'knowledge'
| 'document_upload' | 'document_nfc' | 'document_ocr'
| 'biometric_facial' | 'video_ident'
| 'bankid' | 'eid' | 'third_party_idp';
```
### ⚖️ Legal Compliance
**RFC 3161 TSA Timestamps:**
```typescript
import type { ITsaTimestamp, IBlockchainTimestamp } from '@signature.digital/tools';
// TSA timestamp with qualified status
interface ITsaTimestamp {
authority: ITsaAuthority;
token: ITsaToken;
verification: ITsaVerification;
qualifiedInfo?: IQualifiedTsaInfo;
}
```
**Blockchain Anchoring:**
```typescript
// Supported networks
type TBlockchainNetwork = 'bitcoin' | 'ethereum' | 'polygon' | 'arbitrum' | 'optimism' | 'hyperledger' | 'private';
```
### 📝 Contract Content
Paragraphs support rich features:
```typescript
import type { IParagraph, IVariable, ICondition } from '@signature.digital/tools';
// Section types
type TSectionType = 'preamble' | 'definitions' | 'clause' | 'subclause' | 'schedule' | 'exhibit' | 'annex' | 'amendment' | 'signature_block' | 'witness_block' | 'acknowledgment' | 'recital';
// Variables with validation and formatting
interface IVariable {
variableId: string;
name: string;
description: string;
type: TVariableType; // 'text' | 'number' | 'currency' | 'date' | 'party_name' | 'calculated'...
value?: unknown;
required: boolean;
validation?: IVariableValidation;
format?: IVariableFormat;
}
```
#### `IParagraph`
### 💰 Financial Terms
Represents a contract section:
Machine-readable financial data:
```typescript
interface IParagraph {
uniqueId: string;
parent: IParagraph | null;
title: string;
content: string;
}
```
import type { IFinancialTerms, IPaymentScheduleEntry } from '@signature.digital/tools';
#### `IInvolvedParty`
Links a role to a contact:
```typescript
interface IInvolvedParty {
role: string;
contact: TContact; // from @tsclass/tsclass
}
```
### Example: Creating a Contract
```typescript
import type {
IPortableContract,
IRole,
IParagraph,
} from '@signature.digital/tools';
const roles: IRole[] = [
{
id: 'employer',
name: 'Employer',
description: 'The party offering the position.',
},
{
id: 'employee',
name: 'Employee',
description: 'The party accepting the position.',
},
];
const paragraphs: IParagraph[] = [
{
uniqueId: '1',
parent: null,
title: 'Introduction',
content: 'This contract outlines the terms of employment.',
},
{
uniqueId: '2',
parent: null,
title: 'Scope of Work',
content: 'The employee will perform the following duties...',
},
];
const contract: IPortableContract = {
title: 'Employment Contract',
context: 'Standard employment agreement',
availableRoles: roles,
involvedParties: [
{ role: 'employer', contact: null },
{ role: 'employee', contact: null },
],
priorContracts: [],
paragraphs,
const financialTerms: IFinancialTerms = {
totalValue: { amount: 50000, currency: 'EUR', includesTax: false },
paymentSchedule: [...],
paymentMethods: ['bank_transfer', 'sepa_direct_debit'],
billingRates: [...],
penalties: [...],
};
```
### Using Demo Data
### 📅 Time Terms
The package includes demo data for testing and development:
Duration, milestones, renewal, and termination:
```typescript
import type { ITimeTerms, IRenewalTerms, ITerminationTerms } from '@signature.digital/tools';
const timeTerms: ITimeTerms = {
effectiveDate: Date.now(),
duration: { value: 12, unit: 'months' },
isIndefinite: false,
renewal: {
type: 'auto_renew',
renewalPeriod: { value: 12, unit: 'months' },
maxRenewals: 3,
},
termination: {
noticePeriod: { duration: { value: 30, unit: 'days' }, form: 'written' },
},
};
```
### 🔄 Version Control
Git-like versioning for contracts:
```typescript
import { createInitialVersion, incrementVersion, versionToString } from '@signature.digital/tools';
const v1 = createInitialVersion('user-123');
const v2version = incrementVersion(v1.version, 'minor');
console.log(versionToString(v2version)); // '0.2.0'
```
### 👥 Collaboration
Real-time collaboration support:
```typescript
import type { ICommentThread, ISuggestion, IUserPresence } from '@signature.digital/tools';
import { createCommentThread, createSuggestion, createUserPresence } from '@signature.digital/tools';
// Track user presence
const presence = createUserPresence('user-123', 'Alice', '#1a73e8');
// Comments with threads
const thread = createCommentThread(contractId, versionId, {
type: 'text_range',
paragraphId: 'para-1',
textRange: { start: 0, end: 50, quotedText: 'Sample text' },
}, 'user-123');
// Track-changes style suggestions
const suggestion = createSuggestion(
contractId, versionId, 'para-1',
'replace', 'old text', 'new text',
'user-456', 'Bob'
);
```
### 📊 Audit Logging
Tamper-evident, hash-chained audit logs:
```typescript
import type { IAuditLog, IContractAction, TActionCategory } from '@signature.digital/tools';
// Action categories
type TActionCategory =
| 'create' | 'view' | 'edit' | 'status_change'
| 'share' | 'permission_change' | 'comment'
| 'signature_request' | 'signature_given' | 'signature_declined'
| 'export' | 'print' | 'download'
| 'archive' | 'restore' | 'delete';
```
### 📑 PDF Generation
Comprehensive PDF configuration:
```typescript
import { createDefaultPdfConfig, type IPdfGenerationConfig } from '@signature.digital/tools';
const pdfConfig = createDefaultPdfConfig('Employment Contract');
// Customize branding
pdfConfig.branding.primaryColor = '#1a73e8';
pdfConfig.branding.logo = {
url: 'https://example.com/logo.png',
position: 'left',
maxWidth: 150,
maxHeight: 50,
};
// Security settings
pdfConfig.security = {
encryption: { enabled: true, algorithm: 'AES-256' },
permissions: {
printing: 'high_resolution',
copying: false,
modifying: false,
},
};
```
## Demo Data
Test your implementation with realistic demo contracts:
```typescript
import { demoContract } from '@signature.digital/tools/demodata';
console.log(demoContract.title); // "Minijob Employment Contract"
console.log(demoContract.title); // 'Minijob Employment Contract'
console.log(demoContract.metadata.governingLaw.country); // 'DE'
console.log(demoContract.paragraphs.length); // 8 fully structured paragraphs
```
### Separate Interface Import
The demo contract showcases:
- Multi-language support (DE/EN)
- Variable placeholders with validation
- Legal references (BGB, SGB IV, MiLoG)
- Financial terms with payment schedules
- Company and person contacts with full details
- Proper role and party structure
You can import just the interfaces without the full package:
## Factory Functions
The library provides factory functions for creating properly initialized objects:
```typescript
import type { IPortableContract } from '@signature.digital/tools/interfaces';
// Contract creation
createEmptyContract(title, category, contractType, createdBy, language?)
createDefaultMetadata(category, contractType, language?)
createDefaultGoverningLaw()
// Roles and parties
createRole(id, name, description, options?)
createInvolvedParty(roleId, contact, signingOrder?)
// Content
createParagraph(title, content, sectionType?, order?)
createVariable(variableId, name, type, required?)
// Terms
createEmptyFinancialTerms()
createEmptyTimeTerms()
createEmptyObligationTerms()
// Versioning
createInitialVersion(userId, userDisplayName?)
createEmptyVersionHistory(contractId, initialVersion)
incrementVersion(current, incrementType)
versionToString(version)
parseVersionString(versionString)
// Collaboration
createCommentThread(contractId, versionId, anchor, userId)
createComment(threadId, authorId, authorDisplayName, content)
createSuggestion(...)
createCollaborator(userId, contact, permission, invitedBy)
createUserPresence(userId, displayName, color)
// Lifecycle
createInitialLifecycle(contractId)
createEmptyAuditLog(contractId)
createStatusTransition(fromStatus, toStatus, triggeredBy, reason?)
createLegalHold(name, description, contractIds, createdBy, reason)
// Attachments
createContractAttachment(contractId, versionId, type, category, title, addedBy)
createPriorContractReference(relationshipType, contractId?, externalReference?)
createDocumentBundle(name, mainContractId, purpose, createdBy)
createAttachmentFile(filename, mimeType, size, storageProvider, storageKey, checksum)
// Identity verification
createIdentityVerificationRequest(methods, requiredConfidence, expiresInSeconds?)
createPendingVerificationResult(requestId)
// Legal compliance
createEmptyLegalComplianceProof()
createPendingTsaTimestamp(authorityUrl)
createPendingBlockchainTimestamp(network, dataHash)
// PDF
createDefaultPdfConfig(title)
createDefaultBranding()
createDefaultLayout()
createDefaultContentOptions()
createDefaultPageNumbering()
// Signatures
createEmptySignatureMetadata()
createDefaultSignatureFieldRequirements()
```
## Module Exports
## TypeScript Integration
The package provides three entry points:
All interfaces follow strict naming conventions:
- **Interfaces**: `I` prefix (e.g., `IPortableContract`)
- **Types**: `T` prefix (e.g., `TContractStatus`)
| Entry Point | Description |
| ------------------------------------- | ------------------------------- |
| `@signature.digital/tools` | Main export with all interfaces |
| `@signature.digital/tools/interfaces` | Interface definitions only |
| `@signature.digital/tools/demodata` | Demo contract data |
```typescript
import type {
// Core interfaces
IPortableContract,
IRole,
IInvolvedParty,
IParagraph,
// Signature system
ISignature,
ISignatureField,
TSignatureType,
TSignatureLegalLevel,
// Identity
IIdentityVerificationResult,
TIdentityVerificationMethod,
// Legal
ILegalComplianceProof,
ITsaTimestamp,
IBlockchainTimestamp,
// Terms
IFinancialTerms,
ITimeTerms,
IObligationTerms,
// And 200+ more types...
} from '@signature.digital/tools';
```
## License and Legal Information