From e0df19746edc2cb7889e5e41c4bb32bb467b7c62 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 22 Jan 2026 10:00:12 +0000 Subject: [PATCH 1/3] Initial plan From 133e98f19be016620f02916066b567efabae185f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 22 Jan 2026 10:09:32 +0000 Subject: [PATCH 2/3] feat: add comprehensive documentation structure and standards Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com> --- CONTRIBUTING.md | 430 +++++++++++++++++++++++++ README.md | 60 ++-- docs/README.md | 299 ++++++++++++++++++ docs/architecture/data-layer.md | 279 +++++++++++++++++ docs/architecture/system-layer.md | 449 +++++++++++++++++++++++++++ docs/architecture/ui-layer.md | 362 +++++++++++++++++++++ docs/standards/api-design.md | 320 +++++++++++++++++++ docs/standards/error-handling.md | 179 +++++++++++ docs/standards/naming-conventions.md | 76 +++++ 9 files changed, 2435 insertions(+), 19 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 docs/README.md create mode 100644 docs/architecture/data-layer.md create mode 100644 docs/architecture/system-layer.md create mode 100644 docs/architecture/ui-layer.md create mode 100644 docs/standards/api-design.md create mode 100644 docs/standards/error-handling.md create mode 100644 docs/standards/naming-conventions.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..b368e52df --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,430 @@ +# Contributing to ObjectStack Protocol + +Thank you for your interest in contributing to ObjectStack! This guide will help you get started with contributing to the protocol specifications. + +## πŸ“‹ Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [Getting Started](#getting-started) +- [Development Workflow](#development-workflow) +- [Contribution Types](#contribution-types) +- [Coding Standards](#coding-standards) +- [Testing Guidelines](#testing-guidelines) +- [Documentation Guidelines](#documentation-guidelines) +- [Pull Request Process](#pull-request-process) +- [Community](#community) + +## Code of Conduct + +We are committed to providing a welcoming and inclusive environment. Please be respectful and professional in all interactions. + +## Getting Started + +### Prerequisites + +- **Node.js** >= 18.0.0 +- **PNPM** >= 8.0.0 +- **Git** >= 2.0.0 + +### Initial Setup + +```bash +# 1. Fork the repository on GitHub +# 2. Clone your fork +git clone https://github.com/YOUR_USERNAME/spec.git +cd spec + +# 3. Add upstream remote +git remote add upstream https://github.com/objectstack-ai/spec.git + +# 4. Install dependencies +pnpm install + +# 5. Build the project +pnpm build + +# 6. Run tests +pnpm test +``` + +## Development Workflow + +### 1. Choose What to Work On + +Before starting, review: +- **[PRIORITIES.md](./PRIORITIES.md)** - Current sprint priorities +- **[DEVELOPMENT_ROADMAP.md](./DEVELOPMENT_ROADMAP.md)** - Long-term roadmap +- **[GitHub Issues](https://github.com/objectstack-ai/spec/issues)** - Open issues + +### 2. Create a Branch + +```bash +# Update your main branch +git checkout main +git pull upstream main + +# Create a feature branch +git checkout -b feature/your-feature-name +# or +git checkout -b fix/your-bug-fix +``` + +### 3. Make Your Changes + +Follow the [Coding Standards](#coding-standards) and ensure: +- Changes are minimal and focused +- Code follows existing patterns +- Tests are added/updated +- Documentation is updated + +### 4. Test Your Changes + +```bash +# Run all tests +pnpm test + +# Run tests for specific package +pnpm --filter @objectstack/spec test + +# Build to verify schemas +pnpm build +``` + +### 5. Submit Your Changes + +```bash +# Stage your changes +git add . + +# Commit with descriptive message +git commit -m "feat: add new field type for encrypted data" + +# Push to your fork +git push origin feature/your-feature-name + +# Create Pull Request on GitHub +``` + +## Contribution Types + +### πŸ”§ Protocol Definitions + +Adding or modifying protocol definitions in `packages/spec/src/`: + +1. **Create Zod Schema** - Always start here +2. **Add JSDoc Comments** - Document with `@description` +3. **Write Tests** - Target 80%+ coverage +4. **Generate Schemas** - Run `pnpm build` +5. **Create Documentation** - Add MDX in `content/docs/references/` + +Example: +```typescript +/** + * Represents an encrypted field for storing sensitive data + * @description Provides end-to-end encryption for sensitive information + */ +export const EncryptedFieldSchema = z.object({ + /** Field type identifier */ + type: z.literal('encrypted'), + + /** Encryption algorithm (default: AES-256-GCM) */ + algorithm: z.enum(['aes-256-gcm', 'rsa-4096']).default('aes-256-gcm'), + + /** Key management strategy */ + keyManagement: z.enum(['user', 'organization', 'system']).default('organization'), +}); +``` + +### πŸ“š Documentation + +- **Concepts** - High-level explanations in `content/docs/concepts/` +- **Guides** - How-to tutorials in `content/docs/guides/` +- **References** - API documentation in `content/docs/references/` +- **Specifications** - Protocol specs in `content/docs/specifications/` + +### πŸ› Bug Fixes + +1. Create an issue describing the bug (if not exists) +2. Reference the issue in your PR +3. Add regression tests +4. Update documentation if behavior changes + +### ✨ Examples + +Add working examples in `examples/`: +- Include `README.md` with setup instructions +- Provide `objectstack.config.ts` configuration +- Add `CHANGELOG.md` for version history + +## Coding Standards + +### Naming Conventions + +**CRITICAL**: Follow these naming conventions strictly: + +#### Configuration Keys (TypeScript Properties) +Use `camelCase`: +```typescript +{ + maxLength: 100, + referenceFilters: ['active'], + defaultValue: 'none', +} +``` + +#### Machine Names (Data Values) +Use `snake_case`: +```typescript +{ + name: 'project_task', + object: 'account', + field: 'first_name', +} +``` + +### Schema Definition Pattern + +```typescript +import { z } from 'zod'; + +/** + * Schema description + * @description Detailed explanation + */ +export const MySchema = z.object({ + /** Property description */ + propertyName: z.string().describe('Property description'), + + /** Another property */ + anotherProperty: z.number().optional().describe('Optional property'), +}); + +export type MyType = z.infer; +``` + +### File Organization + +``` +packages/spec/src/ +β”œβ”€β”€ data/ # ObjectQL - Data Protocol +β”‚ β”œβ”€β”€ field.zod.ts +β”‚ β”œβ”€β”€ object.zod.ts +β”‚ └── validation.zod.ts +β”œβ”€β”€ ui/ # ObjectUI - UI Protocol +β”‚ β”œβ”€β”€ app.zod.ts +β”‚ β”œβ”€β”€ view.zod.ts +β”‚ └── theme.zod.ts +β”œβ”€β”€ system/ # ObjectOS - System Protocol +β”‚ β”œβ”€β”€ manifest.zod.ts +β”‚ β”œβ”€β”€ plugin.zod.ts +β”‚ └── driver.zod.ts +β”œβ”€β”€ ai/ # AI Protocol +β”‚ β”œβ”€β”€ agent.zod.ts +β”‚ └── model.zod.ts +└── api/ # API Protocol + β”œβ”€β”€ envelopes.zod.ts + └── requests.zod.ts +``` + +## Testing Guidelines + +### Test Coverage + +- **Target**: 80%+ code coverage +- **Location**: Co-located `*.test.ts` files +- **Framework**: Vitest + +### Test Structure + +```typescript +import { describe, it, expect } from 'vitest'; +import { MySchema } from './my-schema.zod'; + +describe('MySchema', () => { + describe('validation', () => { + it('should accept valid data', () => { + const result = MySchema.safeParse({ + propertyName: 'valid value', + }); + expect(result.success).toBe(true); + }); + + it('should reject invalid data', () => { + const result = MySchema.safeParse({ + propertyName: 123, // wrong type + }); + expect(result.success).toBe(false); + }); + }); + + describe('type inference', () => { + it('should infer correct TypeScript types', () => { + type MyType = z.infer; + const data: MyType = { + propertyName: 'value', + }; + expect(data.propertyName).toBe('value'); + }); + }); +}); +``` + +## Documentation Guidelines + +### MDX Documentation + +Create documentation in `content/docs/references/` matching the source structure: + +```markdown +--- +title: MySchema +description: Schema description for SEO and navigation +--- + +# MySchema + +Brief description of what this schema represents. + +## Overview + +Detailed explanation of the schema's purpose and use cases. + +## Schema Definition + +\`\`\`typescript +import { MySchema } from '@objectstack/spec'; + +const config = { + propertyName: 'value', +}; + +const validated = MySchema.parse(config); +\`\`\` + +## Properties + +### propertyName + +- **Type**: `string` +- **Required**: Yes +- **Description**: Description of this property + +## Examples + +### Basic Usage + +\`\`\`typescript +const basic = { + propertyName: 'simple value', +}; +\`\`\` + +### Advanced Usage + +\`\`\`typescript +const advanced = { + propertyName: 'complex value', + anotherProperty: 42, +}; +\`\`\` + +## Related + +- [RelatedSchema](./related-schema) +- [AnotherSchema](./another-schema) +``` + +### Bilingual Support + +Provide both English and Chinese versions: +- English: `my-schema.mdx` +- Chinese: `my-schema.cn.mdx` + +## Pull Request Process + +### Before Submitting + +- [ ] All tests pass (`pnpm test`) +- [ ] Code builds successfully (`pnpm build`) +- [ ] Documentation is updated +- [ ] Naming conventions are followed +- [ ] JSDoc comments are complete +- [ ] No unrelated changes included + +### PR Checklist + +Use this template for your PR description: + +```markdown +## Description +Brief description of changes + +## Type of Change +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation update + +## Changes Made +- Item 1 +- Item 2 + +## Testing +- [ ] Unit tests added/updated +- [ ] All tests passing +- [ ] Manual testing completed + +## Documentation +- [ ] JSDoc comments added +- [ ] MDX documentation created/updated +- [ ] Examples provided + +## Checklist +- [ ] Zod schema follows naming conventions +- [ ] Comprehensive JSDoc comments with @description +- [ ] Unit tests with 80%+ coverage +- [ ] Documentation with examples +- [ ] JSON schema generated successfully +- [ ] All existing tests pass +``` + +### Review Process + +1. **Automated Checks** - CI/CD runs tests and builds +2. **Code Review** - Maintainers review your code +3. **Feedback** - Address review comments +4. **Approval** - At least one maintainer approval required +5. **Merge** - Maintainers will merge when ready + +## Community + +### Communication Channels + +- **GitHub Discussions** - General questions and discussions +- **GitHub Issues** - Bug reports and feature requests +- **Pull Requests** - Code contributions + +### Getting Help + +- Review [PLANNING_INDEX.md](./PLANNING_INDEX.md) for documentation navigation +- Check [ARCHITECTURE.md](./ARCHITECTURE.md) for system design +- Read [QUICK_START_IMPLEMENTATION.md](./QUICK_START_IMPLEMENTATION.md) for implementation examples + +### Recognition + +Contributors will be: +- Listed in release notes +- Mentioned in the CHANGELOG +- Credited in documentation (where applicable) + +## License + +By contributing, you agree that your contributions will be licensed under the Apache 2.0 License. + +--- + +**Questions?** Open a [GitHub Discussion](https://github.com/objectstack-ai/spec/discussions) + +**Need Help?** Check the [documentation](./content/docs/) or ask in discussions + +**Thank you for contributing to ObjectStack! πŸš€** diff --git a/README.md b/README.md index 385cdcacd..97cbffe68 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,34 @@ This repository contains the core specifications, schemas, and protocols that po ## πŸ“š Documentation +### Quick Start +* **[Getting Started](./content/docs/guides/getting-started.mdx):** Quick introduction to ObjectStack Protocol +* **[Installation Guide](./content/docs/guides/installation.mdx):** Setup instructions +* **[Contributing Guide](./CONTRIBUTING.md):** How to contribute to the project + ### Planning & Architecture -* **[Development Roadmap](./DEVELOPMENT_ROADMAP.md):** Complete development plan considering all future possibilities. -* **[Priority Matrix](./PRIORITIES.md):** What to work on next, sprint planning guide. -* **[Architecture Diagrams](./ARCHITECTURE.md):** Visual reference for the complete system. +* **[Development Roadmap](./DEVELOPMENT_ROADMAP.md):** Complete development plan considering all future possibilities +* **[Priority Matrix](./PRIORITIES.md):** What to work on next, sprint planning guide +* **[Architecture Diagrams](./ARCHITECTURE.md):** Visual reference for the complete system +* **[Planning Index](./PLANNING_INDEX.md):** Complete guide to navigating planning documentation ### Technical Documentation The official documentation is built with Fumadocs and Next.js. -* **[Documentation Content](./content/docs/):** MDX documentation files (concepts, specifications, references). -* **[Documentation Site](./apps/docs/):** Fumadocs-powered Next.js app. -* **[Live Site](http://localhost:3000/docs):** Run `pnpm docs:dev` to view locally. +* **[Documentation Content](./content/docs/):** MDX documentation files (concepts, specifications, references) +* **[Documentation Site](./apps/docs/):** Fumadocs-powered Next.js app +* **[Technical Guides](./docs/):** In-depth technical guides and standards +* **[Live Site](http://localhost:3000/docs):** Run `pnpm docs:dev` to view locally + +### Architecture Deep Dives +* **[Data Layer (ObjectQL)](./docs/architecture/data-layer.md):** Query language and data abstraction +* **[UI Layer (ObjectUI)](./docs/architecture/ui-layer.md):** Server-driven UI protocol +* **[System Layer (ObjectOS)](./docs/architecture/system-layer.md):** Runtime kernel and plugins + +### Standards & Best Practices +* **[Naming Conventions](./docs/standards/naming-conventions.md):** Schema naming rules (camelCase vs snake_case) +* **[API Design](./docs/standards/api-design.md):** API design principles and patterns +* **[Error Handling](./docs/standards/error-handling.md):** Consistent error handling strategies ## πŸ“¦ Monorepo Structure @@ -104,24 +121,27 @@ pnpm docs:dev # Visit http://localhost:3000/docs ``` -## 🀝 Contribution +## 🀝 Contributing -### Getting Started -1. **Read the Roadmap**: Review [DEVELOPMENT_ROADMAP.md](./DEVELOPMENT_ROADMAP.md) to understand the vision. -2. **Check Priorities**: See [PRIORITIES.md](./PRIORITIES.md) for what to work on next. -3. **Understand Architecture**: Read [ARCHITECTURE.md](./ARCHITECTURE.md) for system overview. +We welcome contributions! Please read our **[Contributing Guide](./CONTRIBUTING.md)** for detailed guidelines. -### Development Process -1. **Code First**: Always start by defining the Zod Schema in `packages/spec/src`. -2. **Write Tests**: Add comprehensive tests in `*.test.ts` files (target 80%+ coverage). -3. **Generate**: Run `pnpm build` to update JSON Schemas and Documentation. -4. **Commit**: Submit PR with updated Code + Schemas + Docs. +### Quick Start for Contributors -### Naming Conventions -- **Configuration Keys** (TypeScript properties): `camelCase` (e.g., `maxLength`, `referenceFilters`) -- **Machine Names** (Data values): `snake_case` (e.g., `name: 'project_task'`, `object: 'account'`) +1. **Read the Docs**: Review [CONTRIBUTING.md](./CONTRIBUTING.md) for complete guidelines +2. **Check Priorities**: See [PRIORITIES.md](./PRIORITIES.md) for what to work on next +3. **Understand Architecture**: Read [ARCHITECTURE.md](./ARCHITECTURE.md) for system overview +4. **Follow Standards**: Review [docs/standards/](./docs/standards/) for coding standards + +### Key Standards + +- **Naming Conventions**: See [docs/standards/naming-conventions.md](./docs/standards/naming-conventions.md) + - Configuration keys: `camelCase` (e.g., `maxLength`, `referenceFilters`) + - Machine names: `snake_case` (e.g., `name: 'project_task'`, `object: 'account'`) +- **API Design**: Follow [docs/standards/api-design.md](./docs/standards/api-design.md) +- **Error Handling**: Use patterns from [docs/standards/error-handling.md](./docs/standards/error-handling.md) ### PR Checklist + - [ ] Zod schema follows naming conventions - [ ] Comprehensive JSDoc comments with `@description` - [ ] Unit tests with 80%+ coverage @@ -129,6 +149,8 @@ pnpm docs:dev - [ ] JSON schema generated successfully - [ ] All existing tests pass +See [CONTRIBUTING.md](./CONTRIBUTING.md) for complete details. + ## πŸ“„ License Apach2 2.0 Β© ObjectStack diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..6c7ddfc1b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,299 @@ +# ObjectStack Protocol Documentation + +> Comprehensive technical documentation for the ObjectStack Protocol ecosystem + +## πŸ“š Documentation Structure + +This directory contains **technical guides** and **standards** for the ObjectStack Protocol. For the main documentation site, see [`content/docs/`](../content/docs/). + +## πŸ“‚ Directory Organization + +``` +docs/ +β”œβ”€β”€ README.md # This file - Documentation index +β”œβ”€β”€ guides/ # Technical how-to guides +β”‚ β”œβ”€β”€ ai-integration/ # AI feature integration guides +β”‚ β”œβ”€β”€ security/ # Security implementation guides +β”‚ └── performance/ # Performance optimization guides +β”œβ”€β”€ standards/ # Protocol standards and conventions +β”‚ β”œβ”€β”€ naming-conventions.md # Naming rules for schemas +β”‚ β”œβ”€β”€ api-design.md # API design principles +β”‚ └── error-handling.md # Error handling patterns +β”œβ”€β”€ architecture/ # Detailed architecture documents +β”‚ β”œβ”€β”€ data-layer.md # ObjectQL architecture +β”‚ β”œβ”€β”€ ui-layer.md # ObjectUI architecture +β”‚ └── system-layer.md # ObjectOS architecture +└── migration/ # Migration and upgrade guides + β”œβ”€β”€ v0-to-v1.md # Version migration guides + └── breaking-changes.md # Breaking change documentation +``` + +## 🎯 Quick Navigation + +### For Developers + +| I want to... | Read this | +|--------------|-----------| +| **Integrate AI features** | [AI Integration Guide](./AI_INTEGRATION_GUIDE.md) | +| **Implement authentication** | [Authentication Standard](./AUTHENTICATION_STANDARD.md) | +| **Understand naming rules** | [Naming Conventions](../CONTRIBUTING.md#naming-conventions) | +| **Learn the architecture** | [Architecture](../ARCHITECTURE.md) | + +### For Contributors + +| I want to... | Read this | +|--------------|-----------| +| **Start contributing** | [CONTRIBUTING.md](../CONTRIBUTING.md) | +| **See what to work on** | [PRIORITIES.md](../PRIORITIES.md) | +| **Understand the roadmap** | [DEVELOPMENT_ROADMAP.md](../DEVELOPMENT_ROADMAP.md) | + +### For Architects + +| I want to... | Read this | +|--------------|-----------| +| **System design** | [ARCHITECTURE.md](../ARCHITECTURE.md) | +| **Protocol specifications** | [content/docs/specifications/](../content/docs/specifications/) | +| **Reference documentation** | [content/docs/references/](../content/docs/references/) | + +## πŸ“– Main Documentation Site + +The official user-facing documentation is built with Fumadocs and located in: + +- **Content**: [`content/docs/`](../content/docs/) - MDX documentation files +- **Site**: [`apps/docs/`](../apps/docs/) - Fumadocs Next.js application +- **Local Preview**: Run `pnpm docs:dev` and visit http://localhost:3000/docs + +### Documentation Categories + +#### 1. **Concepts** (`content/docs/concepts/`) +High-level explanations and philosophy: +- Architecture overview +- Core values and manifesto +- Enterprise patterns +- Security architecture +- Terminology + +#### 2. **Guides** (`content/docs/guides/`) +Step-by-step tutorials and how-tos: +- Getting started +- Installation +- Project structure +- Field types +- Custom drivers +- View configuration +- Workflows and validation + +#### 3. **References** (`content/docs/references/`) +API documentation (auto-generated from schemas): +- AI Protocol APIs +- Data Protocol APIs +- System Protocol APIs +- UI Protocol APIs +- API Protocol envelopes and requests + +#### 4. **Specifications** (`content/docs/specifications/`) +Detailed protocol specifications: +- Data layer specifications +- UI layer specifications +- Server specifications +- REST API specification + +## πŸ› οΈ Technical Guides (This Directory) + +### Current Guides + +1. **[AI_INTEGRATION_GUIDE.md](./AI_INTEGRATION_GUIDE.md)** + - Building AI-powered applications + - RAG pipeline implementation + - Natural language query processing + - Model registry usage + +2. **[AUTHENTICATION_STANDARD.md](./AUTHENTICATION_STANDARD.md)** + - Authentication provider implementation + - OAuth, SAML, LDAP integration + - Session management + - Security best practices + +## πŸ“ Documentation Standards + +### Writing Style + +- **Clear and Concise** - Use simple language +- **Code Examples** - Provide working examples +- **Progressive Disclosure** - Start simple, then show advanced +- **Bilingual** - Provide EN and CN versions where possible + +### Markdown Formatting + +```markdown +# Main Title + +> Brief description or tagline + +## Section + +Brief introduction to the section. + +### Subsection + +Detailed content. + +#### Code Examples + +\`\`\`typescript +// Always include comments +const example = { + property: 'value', +}; +\`\`\` + +#### Tips + +> πŸ’‘ **Tip**: Helpful information for users + +#### Warnings + +> ⚠️ **Warning**: Important cautionary information + +#### Best Practices + +> βœ… **Best Practice**: Recommended approach +``` + +### Code Block Guidelines + +1. **Always specify language** for syntax highlighting +2. **Include comments** explaining key parts +3. **Show imports** when relevant +4. **Demonstrate both simple and advanced** usage +5. **Use real-world examples** when possible + +### Cross-References + +Use relative links to reference other documentation: + +```markdown +See [ARCHITECTURE.md](../ARCHITECTURE.md) for system design details. +``` + +## 🌍 Multilingual Support + +### Chinese Documentation + +For Chinese versions: +- Create files with `.cn.md` or `.cn.mdx` suffix +- Keep structure identical to English version +- Update `meta.cn.json` for navigation + +Example: +``` +guides/ +β”œβ”€β”€ getting-started.mdx # English +β”œβ”€β”€ getting-started.cn.mdx # Chinese +β”œβ”€β”€ meta.json # English navigation +└── meta.cn.json # Chinese navigation +``` + +## πŸ”„ Documentation Workflow + +### Adding New Documentation + +1. **Identify Category** - Concept, Guide, Reference, or Specification? +2. **Create File** - Use appropriate directory and naming +3. **Follow Template** - Use consistent structure +4. **Add Examples** - Include working code examples +5. **Update Navigation** - Add to `meta.json` +6. **Test Locally** - Run `pnpm docs:dev` to preview +7. **Submit PR** - Follow [CONTRIBUTING.md](../CONTRIBUTING.md) + +### Updating Existing Documentation + +1. **Make Changes** - Update content +2. **Verify Examples** - Ensure code still works +3. **Update Version** - Note changes in commit message +4. **Test Build** - Run `pnpm docs:build` +5. **Submit PR** - Include "docs:" prefix in commit + +## πŸ§ͺ Testing Documentation + +### Local Testing + +```bash +# Start development server +pnpm docs:dev + +# Build production site +pnpm docs:build + +# Serve production build +pnpm docs:start +``` + +### Verification Checklist + +- [ ] All links work (no 404s) +- [ ] Code examples are syntactically correct +- [ ] Images load properly +- [ ] Navigation is correct +- [ ] Search finds relevant content +- [ ] Build completes without errors + +## πŸ“Š Documentation Metrics + +### Current Status + +- **Concept Pages**: 10+ pages +- **Guides**: 8+ tutorials +- **References**: 250+ API docs +- **Specifications**: 25+ specs +- **Languages**: English, Chinese +- **Total Pages**: 290+ + +### Coverage Goals + +- **Protocol Coverage**: 95%+ (all schemas documented) +- **Examples**: 100%+ working examples +- **Bilingual**: 80%+ pages in both EN/CN +- **Up-to-date**: Review quarterly + +## 🀝 Contributing to Documentation + +### What We Need + +- **More Guides** - Step-by-step tutorials +- **Use Cases** - Real-world examples +- **Translations** - Chinese translations +- **Diagrams** - Architecture visualizations +- **Videos** - Screencasts and tutorials + +### How to Help + +1. **Report Issues** - Found unclear docs? Open an issue +2. **Suggest Improvements** - Have ideas? Create a discussion +3. **Submit Changes** - Fix typos, improve examples +4. **Write New Content** - Add guides, examples + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for detailed guidelines. + +## πŸ“ž Getting Help + +### Documentation Questions + +- **GitHub Discussions** - Ask questions about documentation +- **GitHub Issues** - Report documentation bugs +- **Pull Requests** - Suggest documentation improvements + +### Documentation Team + +- Review [PLANNING_INDEX.md](../PLANNING_INDEX.md) for planning docs +- Check [DEVELOPMENT_ROADMAP.md](../DEVELOPMENT_ROADMAP.md) for documentation roadmap + +## πŸ“„ License + +Documentation is licensed under [Apache 2.0](../LICENSE). + +--- + +**Last Updated**: 2026-01-22 +**Maintainer**: ObjectStack Documentation Team +**Status**: βœ… Active diff --git a/docs/architecture/data-layer.md b/docs/architecture/data-layer.md new file mode 100644 index 000000000..0d0ff4425 --- /dev/null +++ b/docs/architecture/data-layer.md @@ -0,0 +1,279 @@ +# ObjectQL - Data Layer Architecture + +> Deep dive into the ObjectQL (Object Query Language) data protocol architecture + +## Overview + +ObjectQL is the **data abstraction layer** of ObjectStack. It defines how data structures are expressed, queried, and manipulated across different storage backends. + +## Key Components + +### 1. Schema Definition (`src/data/`) + +#### Object Schema +Defines business entities (tables/collections): + +```typescript +const CustomerAccount = { + name: 'customer_account', + label: 'Customer Account', + fields: { /* field definitions */ }, + enableHistory: true, + enableSharing: true, +}; +``` + +#### Field Schema +Defines data properties with 25+ types: + +- **Basic**: text, textarea, number, boolean, date, datetime +- **Advanced**: lookup, formula, rollup, autonumber +- **Rich**: email, phone, url, currency, percent +- **Complex**: address, geolocation, file, image + +### 2. Query Protocol (`src/data/query/`) + +Abstract Syntax Tree (AST) for unified data access: + +```typescript +const query = { + select: ['name', 'email', 'revenue'], + from: 'customer_account', + where: { + and: [ + { field: 'industry', operator: 'eq', value: 'technology' }, + { field: 'revenue', operator: 'gt', value: 500000 } + ] + }, + orderBy: [{ field: 'revenue', direction: 'desc' }], + limit: 10, +}; +``` + +### 3. Validation Rules (`src/data/validation.zod.ts`) + +Business logic validation: + +- **Format Validation**: Email, phone, URL patterns +- **Range Validation**: Min/max for numbers and dates +- **Uniqueness**: Field-level and composite keys +- **Cross-Field**: Conditional validation based on other fields +- **Custom**: Script-based validation logic + +### 4. Automation (`src/data/automation/`) + +#### Workflows +State-based automation rules: + +```typescript +const workflowRule = { + name: 'high_value_alert', + object: 'customer_account', + triggerType: 'on_create_or_update', + criteria: { field: 'annual_revenue', operator: 'gt', value: 1000000 }, + actions: [ + { type: 'email_alert', template: 'notify_sales_manager' }, + { type: 'field_update', field: 'priority', value: 'high' } + ], +}; +``` + +#### Flows +Visual logic orchestration: + +- **Screen Flows**: User-interactive wizards +- **Autolaunched Flows**: Backend automation +- **Scheduled Flows**: Time-based execution + +### 5. Security (`src/data/security/`) + +#### Permissions +Fine-grained access control: + +```typescript +const permissionSet = { + name: 'sales_user', + objectPermissions: { + customer_account: { + read: true, + create: true, + edit: true, + delete: false, + } + }, + fieldPermissions: { + customer_account: { + annual_revenue: { read: true, edit: false } + } + } +}; +``` + +#### Sharing Rules +Row-level security: + +- **OWD Model**: Organization-wide defaults +- **Sharing Rules**: Criteria-based sharing +- **Manual Sharing**: User-granted access +- **Role Hierarchy**: Inheritance-based access + +## Data Flow + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Application Layer (UI, API, CLI) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ ObjectQL Query Builder β”‚ +β”‚ - Validates schema references β”‚ +β”‚ - Checks permissions β”‚ +β”‚ - Applies business rules β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Query Optimizer β”‚ +β”‚ - Optimizes AST β”‚ +β”‚ - Plans execution β”‚ +β”‚ - Caches metadata β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Driver Layer β”‚ +β”‚ - Translates AST to native queries β”‚ +β”‚ - Handles driver-specific features β”‚ +β”‚ - Manages connections β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Storage Backend (PostgreSQL, MongoDB, MySQL, etc.) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Driver Interface + +Drivers translate ObjectQL to native storage formats: + +```typescript +interface DriverInterface { + // CRUD Operations + create(object: string, data: Record): Promise; + read(object: string, id: string): Promise; + update(object: string, id: string, data: Record): Promise; + delete(object: string, id: string): Promise; + + // Query Operations + query(query: Query): Promise; + count(query: Query): Promise; + + // Schema Operations + describeObject(object: string): Promise; + listObjects(): Promise; +} +``` + +## Advanced Features + +### Formulas + +Computed fields with expression language: + +```typescript +{ + name: 'total_value', + type: 'formula', + returnType: 'number', + expression: 'quantity * unit_price * (1 - discount_percent / 100)' +} +``` + +### Rollup Summaries + +Aggregate related records: + +```typescript +{ + name: 'total_opportunities', + type: 'rollup', + relationshipField: 'account_id', + relatedObject: 'opportunity', + aggregateFunction: 'SUM', + aggregateField: 'amount' +} +``` + +### Lookup Relationships + +Reference other objects: + +```typescript +{ + name: 'account_id', + type: 'lookup', + reference: 'customer_account', + displayField: 'account_name', + cascadeDelete: false +} +``` + +## Performance Considerations + +### Indexing + +Define indexes for query optimization: + +```typescript +const indexes = [ + { fields: ['email'], unique: true }, + { fields: ['industry', 'revenue'] }, + { fields: ['created_date'] } +]; +``` + +### Query Optimization + +- Use field selection to limit data transfer +- Apply filters early in the query +- Use pagination for large result sets +- Leverage database indexes + +### Caching + +- Cache object metadata +- Cache permission sets +- Use query result caching for reports + +## Best Practices + +1. **Schema Design** + - Use appropriate field types + - Define relationships clearly + - Add validation rules early + - Index frequently queried fields + +2. **Query Design** + - Select only needed fields + - Use efficient filters + - Implement pagination + - Avoid N+1 queries + +3. **Security** + - Define OWD models + - Set field-level security + - Use sharing rules appropriately + - Audit access patterns + +4. **Performance** + - Add database indexes + - Use formula fields sparingly + - Optimize rollup calculations + - Monitor query performance + +## Related Documentation + +- [Field Types Guide](../../content/docs/guides/field-types.mdx) +- [Query Protocol Guide](../../packages/spec/QUERY_PROTOCOL_GUIDE.md) +- [Schema Definition Specification](../../content/docs/specifications/data/schema-definition.mdx) +- [Driver Interface](../../content/docs/references/system/DriverInterface.mdx) + +For complete API reference, see [Data Protocol References](../../content/docs/references/data/). diff --git a/docs/architecture/system-layer.md b/docs/architecture/system-layer.md new file mode 100644 index 000000000..b701dfc38 --- /dev/null +++ b/docs/architecture/system-layer.md @@ -0,0 +1,449 @@ +# ObjectOS - System Layer Architecture + +> Deep dive into the ObjectOS (Operating System) runtime architecture + +## Overview + +ObjectOS is the **runtime kernel** that orchestrates the entire ObjectStack ecosystem. It manages application lifecycle, plugins, identity, and system resources. + +## Key Components + +### 1. Manifest & Packaging (`src/system/manifest.zod.ts`) + +Application packaging and dependencies: + +```typescript +// objectstack.config.ts +export default { + name: 'sales_crm', + version: '1.0.0', + label: 'Sales CRM', + description: 'Customer relationship management system', + + dependencies: { + '@objectstack/core': '^1.0.0', + '@objectstack/plugin-analytics': '^0.5.0', + }, + + objects: ['./src/objects/**/*.object.ts'], + flows: ['./src/flows/**/*.flow.ts'], + apps: ['./src/apps/**/*.app.ts'], + + features: ['workflows', 'reports', 'ai_assistant'], + + license: 'MIT', +}; +``` + +### 2. Plugin Architecture (`src/system/plugin.zod.ts`) + +Extensibility through plugins: + +```typescript +interface Plugin { + name: string; + version: string; + + // Lifecycle hooks + onLoad?(context: PluginContext): Promise; + onUnload?(): Promise; + onActivate?(): Promise; + onDeactivate?(): Promise; + + // Extension points + registerRoutes?(router: Router): void; + registerDrivers?(): Driver[]; + registerWidgets?(): FieldWidget[]; + registerValidators?(): Validator[]; +} + +// Example plugin +export class AnalyticsPlugin implements Plugin { + name = 'analytics'; + version = '1.0.0'; + + async onLoad(context: PluginContext) { + // Initialize analytics service + const analytics = new AnalyticsService(context.ql); + context.services.set('analytics', analytics); + } + + registerRoutes(router: Router) { + router.get('/analytics/reports', this.listReports); + router.post('/analytics/query', this.executeQuery); + } +} +``` + +### 3. Identity & Authentication (`src/system/identity/`) + +User authentication and authorization: + +#### Authentication Strategies + +```typescript +const authConfig = { + providers: [ + { + type: 'email_password', + enabled: true, + requireEmailVerification: true, + passwordPolicy: { + minLength: 12, + requireUppercase: true, + requireLowercase: true, + requireNumbers: true, + requireSpecialChars: true, + }, + }, + { + type: 'oauth', + provider: 'google', + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + }, + { + type: 'saml', + entityId: 'https://myapp.com/saml', + ssoUrl: 'https://idp.example.com/sso', + certificate: process.env.SAML_CERT, + }, + ], + + session: { + lifetime: 86400, // 24 hours + extendOnActivity: true, + singleSessionPerUser: false, + }, + + twoFactor: { + enabled: true, + methods: ['totp', 'sms'], + }, +}; +``` + +#### Role-Based Access Control + +```typescript +const role = { + name: 'sales_manager', + label: 'Sales Manager', + permissionSets: ['sales_user', 'report_viewer'], + inheritsFrom: 'sales_user', +}; +``` + +### 4. Driver System (`src/system/driver.zod.ts`) + +Database abstraction layer: + +```typescript +interface DriverInterface { + name: string; + type: 'sql' | 'nosql' | 'rest' | 'graphql'; + + capabilities: { + transactions: boolean; + queryFilters: boolean; + queryAggregations: boolean; + querySorting: boolean; + queryPagination: boolean; + queryWindowFunctions: boolean; + querySubqueries: boolean; + }; + + // CRUD operations + create(params: CreateParams): Promise; + read(params: ReadParams): Promise; + update(params: UpdateParams): Promise; + delete(params: DeleteParams): Promise; + + // Query operations + query(params: QueryParams): Promise; + + // Schema operations + syncSchema(objects: Object[]): Promise; +} + +// Example: PostgreSQL driver +export class PostgreSQLDriver implements DriverInterface { + name = 'postgresql'; + type = 'sql' as const; + + capabilities = { + transactions: true, + queryFilters: true, + queryAggregations: true, + querySorting: true, + queryPagination: true, + queryWindowFunctions: true, + querySubqueries: true, + }; + + async query(params: QueryParams): Promise { + const sql = this.buildSQL(params.query); + return this.execute(sql); + } +} +``` + +### 5. API Gateway (`src/system/integration/`) + +External integrations and webhooks: + +```typescript +const webhook = { + name: 'salesforce_sync', + url: 'https://api.salesforce.com/webhook', + events: ['record.created', 'record.updated'], + objects: ['customer_account', 'opportunity'], + headers: { + 'Authorization': 'Bearer ${SALESFORCE_TOKEN}', + 'Content-Type': 'application/json', + }, + retryPolicy: { + maxRetries: 3, + backoffStrategy: 'exponential', + }, +}; +``` + +### 6. Multi-Tenancy (`src/system/organization/`) + +Tenant isolation and management: + +```typescript +const organization = { + id: 'org_123', + name: 'Acme Corporation', + subdomain: 'acme', + + limits: { + maxUsers: 100, + maxStorage: 10 * 1024 * 1024 * 1024, // 10 GB + maxAPICallsPerDay: 100000, + }, + + features: ['workflows', 'ai_assistant', 'advanced_analytics'], + + datasources: [ + { + name: 'primary', + driver: 'postgresql', + connectionString: process.env.DATABASE_URL, + } + ], +}; +``` + +## System Architecture + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ API Gateway β”‚ +β”‚ REST, GraphQL, WebSocket endpoints β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ ObjectOS Kernel β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Plugin Manager β”‚ β”‚ +β”‚ β”‚ - Plugin discovery and loading β”‚ β”‚ +β”‚ β”‚ - Dependency resolution β”‚ β”‚ +β”‚ β”‚ - Lifecycle management β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Identity Service β”‚ β”‚ +β”‚ β”‚ - Authentication β”‚ β”‚ +β”‚ β”‚ - Authorization β”‚ β”‚ +β”‚ β”‚ - Session management β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Data Access Layer (ObjectQL) β”‚ β”‚ +β”‚ β”‚ - Query building β”‚ β”‚ +β”‚ β”‚ - Permission checking β”‚ β”‚ +β”‚ β”‚ - Validation β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Driver Manager β”‚ β”‚ +β”‚ β”‚ - Driver registration β”‚ β”‚ +β”‚ β”‚ - Connection pooling β”‚ β”‚ +β”‚ β”‚ - Query translation β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Storage Layer (Drivers) β”‚ +β”‚ PostgreSQL | MongoDB | MySQL | Redis | etc. β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Plugin System + +### Plugin Discovery + +1. **Static Registration**: Import and register plugins explicitly +2. **Auto-Discovery**: Scan `node_modules/@objectstack/plugin-*` +3. **Remote Registry**: Fetch plugins from marketplace + +### Plugin Lifecycle + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Installed β”‚ ──register──> β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ Loaded β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + activate β”‚ + ↓ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Active β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + deactivate β”‚ + ↓ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Inactive β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + unload β”‚ + ↓ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Unloaded β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Extension Points + +Plugins can extend: + +- **Routes**: Add custom API endpoints +- **Drivers**: Add database/API connectors +- **Widgets**: Add custom field widgets +- **Validators**: Add validation logic +- **Workflows**: Add workflow actions +- **Reports**: Add chart types +- **Themes**: Add UI themes + +## Security Features + +### 1. Authentication + +- Email/Password +- OAuth 2.0 (Google, GitHub, etc.) +- SAML 2.0 +- LDAP/Active Directory +- Magic Links +- Passkeys (WebAuthn) + +### 2. Authorization + +- Role-Based Access Control (RBAC) +- Permission Sets +- Organization-Wide Defaults (OWD) +- Sharing Rules +- Field-Level Security + +### 3. Audit & Compliance + +```typescript +const auditPolicy = { + enabled: true, + retention: 90, // days + events: [ + 'user.login', + 'user.logout', + 'record.created', + 'record.updated', + 'record.deleted', + 'permission.changed', + ], + storage: { + driver: 'postgresql', + table: 'audit_logs', + }, +}; +``` + +### 4. Rate Limiting + +```typescript +const rateLimit = { + enabled: true, + limits: { + api: { + window: 60, // seconds + max: 100, // requests + }, + login: { + window: 300, // 5 minutes + max: 5, // attempts + }, + }, +}; +``` + +## Performance Optimizations + +### 1. Caching + +- **Metadata Cache**: Object/field definitions +- **Permission Cache**: User permissions +- **Query Cache**: Frequently accessed data +- **Session Cache**: User sessions + +### 2. Connection Pooling + +```typescript +const datasource = { + driver: 'postgresql', + pool: { + min: 2, + max: 10, + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 2000, + }, +}; +``` + +### 3. Lazy Loading + +- Load plugins on-demand +- Defer non-critical initialization +- Stream large datasets + +## Best Practices + +1. **Plugin Development** + - Keep plugins focused and modular + - Declare all dependencies + - Handle errors gracefully + - Provide clear documentation + +2. **Security** + - Use environment variables for secrets + - Implement rate limiting + - Enable audit logging + - Regular security updates + +3. **Performance** + - Use connection pooling + - Implement caching strategies + - Monitor resource usage + - Optimize database queries + +4. **Multi-Tenancy** + - Isolate tenant data + - Enforce quota limits + - Monitor per-tenant metrics + - Scale horizontally + +## Related Documentation + +- [Plugin Architecture](../../content/docs/concepts/plugin-architecture.mdx) +- [Kernel Architecture](../../content/docs/specifications/server/kernel-architecture.mdx) +- [Authentication Standard](../AUTHENTICATION_STANDARD.md) +- [System Protocol References](../../content/docs/references/system/) + +For complete API reference, see [System Protocol References](../../content/docs/references/system/). diff --git a/docs/architecture/ui-layer.md b/docs/architecture/ui-layer.md new file mode 100644 index 000000000..e72a6744d --- /dev/null +++ b/docs/architecture/ui-layer.md @@ -0,0 +1,362 @@ +# ObjectUI - UI Layer Architecture + +> Deep dive into the ObjectUI (Server-Driven UI) protocol architecture + +## Overview + +ObjectUI is the **presentation protocol** that defines how user interfaces are configured and rendered. It enables building dynamic UIs without hardcoding components. + +## Key Components + +### 1. Application Structure (`src/ui/app.zod.ts`) + +Defines the top-level application configuration: + +```typescript +const app = { + name: 'sales_app', + label: 'Sales CRM', + branding: { + logo: '/assets/logo.png', + primaryColor: '#0066CC', + secondaryColor: '#FF6B00', + }, + navigation: [ + { type: 'object', object: 'customer_account', label: 'Accounts' }, + { type: 'object', object: 'opportunity', label: 'Opportunities' }, + { type: 'dashboard', dashboard: 'sales_dashboard', label: 'Dashboard' }, + ], +}; +``` + +### 2. View Configuration (`src/ui/view.zod.ts`) + +#### List Views +Display collections of records: + +**Grid View** - Tabular data display: +```typescript +{ + type: 'grid', + columns: ['name', 'email', 'revenue', 'status'], + filters: ['status:active'], + sortBy: 'revenue:desc', + pageSize: 25, +} +``` + +**Kanban View** - Card-based workflow: +```typescript +{ + type: 'kanban', + groupByField: 'status', + cardTitle: 'name', + cardFields: ['email', 'revenue'], +} +``` + +**Calendar View** - Time-based display: +```typescript +{ + type: 'calendar', + dateField: 'event_date', + titleField: 'name', + defaultView: 'month', +} +``` + +**Gantt View** - Timeline and dependencies: +```typescript +{ + type: 'gantt', + startDateField: 'start_date', + endDateField: 'end_date', + titleField: 'task_name', + parentField: 'parent_task', +} +``` + +#### Form Views +Display/edit single records: + +**Simple Form** - Basic layout: +```typescript +{ + type: 'simple', + sections: [ + { + title: 'Basic Information', + columns: 2, + fields: ['name', 'email', 'phone'], + } + ], +} +``` + +**Tabbed Form** - Organized by tabs: +```typescript +{ + type: 'tabbed', + tabs: [ + { title: 'Details', fields: ['name', 'email'] }, + { title: 'Address', fields: ['street', 'city', 'country'] }, + ], +} +``` + +**Wizard Form** - Multi-step process: +```typescript +{ + type: 'wizard', + steps: [ + { title: 'Step 1', fields: ['name', 'email'] }, + { title: 'Step 2', fields: ['company', 'role'] }, + ], +} +``` + +### 3. Analytics (`src/ui/analytics/`) + +#### Reports +Data analysis and visualization: + +```typescript +const report = { + type: 'tabular', + object: 'customer_account', + columns: ['name', 'industry', 'revenue'], + groupBy: ['industry'], + aggregations: [ + { field: 'revenue', function: 'SUM' }, + { field: 'id', function: 'COUNT' }, + ], + filters: [{ field: 'status', operator: 'eq', value: 'active' }], + sortBy: [{ field: 'revenue', direction: 'desc' }], +}; +``` + +#### Dashboards +Multiple widgets in a grid layout: + +```typescript +const dashboard = { + name: 'sales_dashboard', + label: 'Sales Dashboard', + layout: [ + { x: 0, y: 0, w: 6, h: 4, widget: 'revenue_chart' }, + { x: 6, y: 0, w: 6, h: 4, widget: 'pipeline_summary' }, + { x: 0, y: 4, w: 12, h: 6, widget: 'top_accounts' }, + ], + widgets: [ + { + id: 'revenue_chart', + type: 'chart', + chartType: 'line', + report: 'monthly_revenue', + }, + { + id: 'pipeline_summary', + type: 'metric', + label: 'Pipeline Value', + aggregation: { field: 'amount', function: 'SUM' }, + }, + ], +}; +``` + +### 4. Theming (`src/ui/theme.zod.ts`) + +Consistent design system: + +```typescript +const theme = { + colors: { + primary: '#0066CC', + secondary: '#FF6B00', + success: '#28A745', + warning: '#FFC107', + error: '#DC3545', + background: '#FFFFFF', + surface: '#F8F9FA', + text: '#212529', + }, + typography: { + fontFamily: 'Inter, sans-serif', + fontSize: { + xs: '0.75rem', + sm: '0.875rem', + base: '1rem', + lg: '1.125rem', + xl: '1.25rem', + }, + }, + spacing: { + xs: '0.25rem', + sm: '0.5rem', + md: '1rem', + lg: '1.5rem', + xl: '2rem', + }, + borderRadius: { + sm: '0.25rem', + md: '0.5rem', + lg: '1rem', + }, +}; +``` + +### 5. Actions (`src/ui/action.zod.ts`) + +User-triggered operations: + +```typescript +const action = { + name: 'approve_record', + label: 'Approve', + type: 'flow', + flowName: 'approval_flow', + confirmMessage: 'Are you sure you want to approve this record?', + successMessage: 'Record approved successfully', + icon: 'check', + variant: 'primary', +}; +``` + +## Rendering Flow + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User Action (Navigate, Click, Edit) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ UI Protocol Resolver β”‚ +β”‚ - Resolves view configuration β”‚ +β”‚ - Fetches object metadata β”‚ +β”‚ - Checks user permissions β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Data Fetcher (ObjectQL) β”‚ +β”‚ - Builds query from view config β”‚ +β”‚ - Executes query via driver β”‚ +β”‚ - Returns data with metadata β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Renderer (React, Vue, etc.) β”‚ +β”‚ - Renders components from protocol β”‚ +β”‚ - Applies theme configuration β”‚ +β”‚ - Binds data to UI elements β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Browser / Mobile App β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Field Widget System + +Custom field rendering: + +```typescript +interface FieldWidgetProps { + value: any; + onChange: (value: any) => void; + field: Field; + readonly: boolean; + required: boolean; + error?: string; +} + +// Example: Custom email field widget +const EmailWidget: React.FC = (props) => { + return ( + props.onChange(e.target.value)} + disabled={props.readonly} + required={props.required} + className={props.error ? 'error' : ''} + /> + ); +}; +``` + +## Page Layouts (FlexiPage) + +Flexible page composition: + +```typescript +const page = { + name: 'account_detail', + label: 'Account Details', + regions: [ + { + name: 'header', + components: [ + { type: 'record_header', showActions: true }, + ], + }, + { + name: 'main', + columns: [ + { + components: [ + { type: 'record_detail', layout: 'two_column' }, + { type: 'related_list', relatedObject: 'opportunity' }, + ], + }, + { + components: [ + { type: 'activity_timeline' }, + { type: 'chatter_feed' }, + ], + }, + ], + }, + ], +}; +``` + +## Best Practices + +1. **View Configuration** + - Keep views focused and simple + - Use appropriate view types for data + - Optimize column count for readability + - Provide meaningful default filters + +2. **Form Design** + - Group related fields in sections + - Use 2-column layouts for efficiency + - Show only necessary fields + - Provide clear labels and help text + +3. **Dashboard Design** + - Limit widgets to 6-8 per dashboard + - Use consistent chart types + - Provide drill-down capabilities + - Update data in real-time or near-real-time + +4. **Theme Consistency** + - Use design tokens + - Maintain color contrast ratios + - Follow accessibility guidelines + - Test on multiple screen sizes + +5. **Performance** + - Lazy load components + - Paginate large lists + - Cache view configurations + - Minimize re-renders + +## Related Documentation + +- [View Configuration Guide](../../content/docs/guides/view-configuration.mdx) +- [SDUI Protocol Specification](../../content/docs/specifications/ui/sdui-protocol.mdx) +- [Component Schema](../../content/docs/specifications/ui/component-schema.mdx) +- [UI Protocol References](../../content/docs/references/ui/) + +For complete API reference, see [UI Protocol References](../../content/docs/references/ui/). diff --git a/docs/standards/api-design.md b/docs/standards/api-design.md new file mode 100644 index 000000000..cdf3c1bc7 --- /dev/null +++ b/docs/standards/api-design.md @@ -0,0 +1,320 @@ +# API Design Principles + +> Guidelines for designing consistent and developer-friendly APIs in ObjectStack + +## Core Principles + +### 1. Protocol-First Design + +All APIs must be defined as **Zod schemas** before implementation: + +```typescript +// βœ… Correct - Define schema first +export const CreateRecordRequestSchema = z.object({ + objectName: z.string(), + data: z.record(z.any()), + options: z.object({ + returnFields: z.array(z.string()).optional(), + validateOnly: z.boolean().default(false), + }).optional(), +}); + +export type CreateRecordRequest = z.infer; +``` + +### 2. Consistent Response Envelopes + +All API responses use standardized envelope schemas from `@objectstack/spec/api`: + +```typescript +import { BaseResponseSchema, SingleRecordResponseSchema } from '@objectstack/spec'; + +// Success response +{ + success: true, + data: { /* record data */ }, + metadata: { /* optional metadata */ } +} + +// Error response +{ + success: false, + error: { + code: 'VALIDATION_ERROR', + message: 'Field "email" is required', + details: { /* error details */ } + } +} +``` + +### 3. Resource-Oriented Design + +Follow RESTful resource conventions: + +``` +GET /api/v1/objects/{object}/records # List records +GET /api/v1/objects/{object}/records/{id} # Get single record +POST /api/v1/objects/{object}/records # Create record +PATCH /api/v1/objects/{object}/records/{id} # Update record +DELETE /api/v1/objects/{object}/records/{id} # Delete record +``` + +### 4. Versioning + +Use URL path versioning: + +``` +/api/v1/... # Current stable version +/api/v2/... # Next version (if needed) +``` + +## Request Design + +### Query Parameters + +Use `camelCase` for query parameters: + +```typescript +GET /api/v1/objects/account/records? + fields=name,email& + filter=status:active& + orderBy=created_date& + limit=25& + offset=0 +``` + +### Request Body + +Use `camelCase` for JSON properties: + +```typescript +POST /api/v1/objects/account/records + +{ + "data": { + "account_name": "Acme Corp", // Field name - snake_case + "annual_revenue": 1000000 // Field name - snake_case + }, + "options": { + "returnFields": ["id", "name"], // Config - camelCase + "validateOnly": false // Config - camelCase + } +} +``` + +## Response Design + +### Success Response Structure + +```typescript +{ + "success": true, + "data": { /* primary response data */ }, + "metadata": { + "timestamp": "2026-01-22T10:00:00Z", + "requestId": "req_abc123", + "duration": 45 // milliseconds + } +} +``` + +### Error Response Structure + +```typescript +{ + "success": false, + "error": { + "code": "ERROR_CODE", + "message": "Human-readable error message", + "details": { + "field": "email", + "reason": "invalid_format" + } + }, + "metadata": { + "timestamp": "2026-01-22T10:00:00Z", + "requestId": "req_abc123" + } +} +``` + +### Error Codes + +Use consistent error code patterns: + +- `VALIDATION_ERROR` - Input validation failed +- `NOT_FOUND` - Resource not found +- `UNAUTHORIZED` - Authentication required +- `FORBIDDEN` - Insufficient permissions +- `CONFLICT` - Resource conflict (e.g., duplicate) +- `INTERNAL_ERROR` - Server error + +## Pagination + +### Offset-Based Pagination + +```typescript +GET /api/v1/objects/account/records?limit=25&offset=0 + +{ + "success": true, + "data": [/* records */], + "pagination": { + "total": 150, + "limit": 25, + "offset": 0, + "hasMore": true + } +} +``` + +### Cursor-Based Pagination + +```typescript +GET /api/v1/objects/account/records?limit=25&cursor=abc123 + +{ + "success": true, + "data": [/* records */], + "pagination": { + "limit": 25, + "nextCursor": "def456", + "hasMore": true + } +} +``` + +## Filtering and Sorting + +### Filter Syntax + +Use structured filter objects: + +```typescript +GET /api/v1/objects/account/records?filter={"status":"active","revenue_gt":100000} + +// Or use query string operators: +GET /api/v1/objects/account/records?status=active&revenue_gt=100000 +``` + +### Sort Syntax + +```typescript +GET /api/v1/objects/account/records?orderBy=created_date:desc,name:asc +``` + +## Best Practices + +### 1. Use Proper HTTP Methods + +- `GET` - Read operations (safe, idempotent) +- `POST` - Create operations +- `PUT` - Full update (replace) +- `PATCH` - Partial update +- `DELETE` - Delete operations + +### 2. Return Appropriate Status Codes + +- `200 OK` - Successful GET, PATCH, DELETE +- `201 Created` - Successful POST +- `400 Bad Request` - Invalid input +- `401 Unauthorized` - Authentication required +- `403 Forbidden` - Insufficient permissions +- `404 Not Found` - Resource not found +- `409 Conflict` - Resource conflict +- `500 Internal Server Error` - Server error + +### 3. Support Partial Responses + +Allow clients to request specific fields: + +```typescript +GET /api/v1/objects/account/records?fields=id,name,email +``` + +### 4. Provide Metadata + +Include helpful metadata in responses: + +```typescript +{ + "success": true, + "data": { /* data */ }, + "metadata": { + "timestamp": "2026-01-22T10:00:00Z", + "requestId": "req_abc123", + "duration": 45, + "version": "1.0" + } +} +``` + +## Examples + +### Create Record + +```typescript +POST /api/v1/objects/customer_account/records + +Request: +{ + "data": { + "account_name": "Acme Corp", + "annual_revenue": 1000000, + "industry": "technology" + }, + "options": { + "returnFields": ["id", "account_name", "created_date"], + "validateOnly": false + } +} + +Response (201 Created): +{ + "success": true, + "data": { + "id": "acc_123", + "account_name": "Acme Corp", + "created_date": "2026-01-22T10:00:00Z" + }, + "metadata": { + "timestamp": "2026-01-22T10:00:00Z", + "requestId": "req_abc123" + } +} +``` + +### Query Records + +```typescript +GET /api/v1/objects/customer_account/records? + fields=id,account_name,annual_revenue& + filter={"industry":"technology","revenue_gt":500000}& + orderBy=annual_revenue:desc& + limit=10 + +Response (200 OK): +{ + "success": true, + "data": [ + { + "id": "acc_123", + "account_name": "Acme Corp", + "annual_revenue": 1000000 + } + // ... more records + ], + "pagination": { + "total": 45, + "limit": 10, + "offset": 0, + "hasMore": true + } +} +``` + +## Related + +- [Naming Conventions](./naming-conventions.md) +- [Error Handling](./error-handling.md) +- [REST API Specification](../../content/docs/specifications/server/rest-api.mdx) diff --git a/docs/standards/error-handling.md b/docs/standards/error-handling.md new file mode 100644 index 000000000..33b070d95 --- /dev/null +++ b/docs/standards/error-handling.md @@ -0,0 +1,179 @@ +# Error Handling Patterns + +> Consistent error handling strategies for ObjectStack Protocol + +## Error Categories + +### 1. Validation Errors + +Errors from schema validation or business logic validation. + +```typescript +{ + "success": false, + "error": { + "code": "VALIDATION_ERROR", + "message": "Validation failed for field 'email'", + "details": { + "field": "email", + "constraint": "format", + "value": "invalid-email", + "expected": "valid email format" + } + } +} +``` + +### 2. Not Found Errors + +Resource does not exist. + +```typescript +{ + "success": false, + "error": { + "code": "NOT_FOUND", + "message": "Record not found", + "details": { + "object": "customer_account", + "id": "acc_999" + } + } +} +``` + +### 3. Permission Errors + +Insufficient permissions to perform operation. + +```typescript +{ + "success": false, + "error": { + "code": "FORBIDDEN", + "message": "Insufficient permissions to delete this record", + "details": { + "required": "DELETE", + "object": "customer_account", + "recordId": "acc_123" + } + } +} +``` + +### 4. Conflict Errors + +Resource conflicts (e.g., uniqueness violations). + +```typescript +{ + "success": false, + "error": { + "code": "CONFLICT", + "message": "Email already exists", + "details": { + "field": "email", + "constraint": "unique", + "value": "user@example.com" + } + } +} +``` + +## Error Schema + +All errors follow the `ApiError` schema: + +```typescript +export const ApiErrorSchema = z.object({ + code: z.string(), + message: z.string(), + details: z.record(z.any()).optional(), + stack: z.string().optional(), // Only in development +}); +``` + +## Error Codes + +### Standard HTTP-Aligned Codes + +- `BAD_REQUEST` (400) - Invalid request +- `UNAUTHORIZED` (401) - Authentication required +- `FORBIDDEN` (403) - Insufficient permissions +- `NOT_FOUND` (404) - Resource not found +- `CONFLICT` (409) - Resource conflict +- `VALIDATION_ERROR` (422) - Validation failed +- `INTERNAL_ERROR` (500) - Server error + +### Domain-Specific Codes + +- `FIELD_REQUIRED` - Required field missing +- `FIELD_INVALID` - Field validation failed +- `DUPLICATE_VALUE` - Uniqueness constraint violated +- `REFERENCE_INVALID` - Lookup reference invalid +- `WORKFLOW_ERROR` - Workflow execution failed +- `PERMISSION_DENIED` - Specific permission denied + +## Best Practices + +### 1. Always Include Context + +```typescript +// βœ… Good - Includes context +{ + "code": "VALIDATION_ERROR", + "message": "Field 'email' must be a valid email address", + "details": { + "field": "email", + "value": "invalid-email", + "constraint": "format" + } +} + +// ❌ Bad - No context +{ + "code": "VALIDATION_ERROR", + "message": "Invalid input" +} +``` + +### 2. Use Consistent Error Structures + +Always return errors in the standard envelope: + +```typescript +{ + "success": false, + "error": { /* ApiError */ }, + "metadata": { /* request metadata */ } +} +``` + +### 3. Don't Leak Sensitive Information + +```typescript +// βœ… Good - Safe error message +{ + "code": "UNAUTHORIZED", + "message": "Invalid credentials" +} + +// ❌ Bad - Leaks information +{ + "code": "UNAUTHORIZED", + "message": "Password incorrect for user john@example.com" +} +``` + +### 4. Include Stack Traces in Development Only + +```typescript +if (process.env.NODE_ENV === 'development') { + error.stack = err.stack; +} +``` + +## Related + +- [API Design Principles](./api-design.md) +- [Security Best Practices](../guides/security/best-practices.md) diff --git a/docs/standards/naming-conventions.md b/docs/standards/naming-conventions.md new file mode 100644 index 000000000..92fcdf4e4 --- /dev/null +++ b/docs/standards/naming-conventions.md @@ -0,0 +1,76 @@ +# Naming Conventions + +> Standardized naming rules for ObjectStack Protocol schemas and configurations + +## Overview + +ObjectStack uses **two distinct naming conventions** depending on the context: +- **Configuration Keys** (TypeScript properties): `camelCase` +- **Machine Names** (Data identifiers): `snake_case` + +This dual-convention approach aligns with industry best practices from Salesforce, ServiceNow, and Kubernetes. + +## Configuration Keys (camelCase) + +### When to Use + +Use `camelCase` for **all TypeScript property names** in schema definitions: +- Schema property keys +- Function parameters +- Object configuration options +- API request/response fields (at the protocol level) + +### Examples + +```typescript +// βœ… Correct +export const FieldSchema = z.object({ + maxLength: z.number().optional(), + minLength: z.number().optional(), + defaultValue: z.any().optional(), + referenceFilters: z.array(z.string()).optional(), + isRequired: z.boolean().default(false), + isUnique: z.boolean().default(false), +}); +``` + +### Rationale + +- **TypeScript Convention**: Matches TypeScript/JavaScript ecosystem standards +- **Developer Experience**: Familiar to frontend and backend developers +- **IDE Support**: Better autocomplete and type inference +- **Industry Alignment**: Matches REST API conventions (JSON payloads) + +## Machine Names (snake_case) + +### When to Use + +Use `snake_case` for **all data identifiers** that represent database or system entities: +- Object names (e.g., `project_task`, `customer_account`) +- Field names (e.g., `first_name`, `email_address`) +- Workflow names, Report names +- Any identifier stored as data + +### Examples + +```typescript +// βœ… Correct - Machine names in snake_case +const field = { + name: 'first_name', // Data identifier - snake_case + label: 'First Name', // Display text - Title Case + type: 'text', // Enum value - lowercase + maxLength: 50, // Config property - camelCase +}; +``` + +## Summary + +| Context | Convention | Example | +|---------|-----------|---------| +| **Configuration Keys** | `camelCase` | `maxLength`, `isRequired`, `defaultValue` | +| **Machine Names** | `snake_case` | `customer_account`, `first_name` | +| **Display Text** | Title Case | `Customer Account`, `First Name` | +| **Enum Values** | lowercase | `text`, `number`, `date` | +| **Constants** | UPPER_SNAKE_CASE | `MAX_LENGTH`, `DEFAULT_TIMEOUT` | + +For complete details and validation patterns, see [CONTRIBUTING.md](../../CONTRIBUTING.md#naming-conventions). From db88d6103d3168c1158446f9701c6a62859ec44e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 22 Jan 2026 10:33:26 +0000 Subject: [PATCH 3/3] feat: complete documentation structure with guides, templates, and code of conduct Co-authored-by: xuyushun441-sys <255036401+xuyushun441-sys@users.noreply.github.com> --- CHANGELOG.md | 136 +++++++++++++++++ CODE_OF_CONDUCT.md | 79 ++++++++++ docs/guides/ai-integration/quick-start.md | 173 ++++++++++++++++++++++ docs/guides/performance/optimization.md | 135 +++++++++++++++++ docs/guides/security/best-practices.md | 100 +++++++++++++ docs/migration/v0-to-v1.md | 149 +++++++++++++++++++ 6 files changed, 772 insertions(+) create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 docs/guides/ai-integration/quick-start.md create mode 100644 docs/guides/performance/optimization.md create mode 100644 docs/guides/security/best-practices.md create mode 100644 docs/migration/v0-to-v1.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..ab4e1efb5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to the ObjectStack Protocol will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Comprehensive documentation structure with CONTRIBUTING.md +- Documentation hub at docs/README.md +- Standards documentation (naming-conventions, api-design, error-handling) +- Architecture deep dives (data-layer, ui-layer, system-layer) +- Code of Conduct +- Changelog template +- Migration guides structure +- Security and performance guides + +### Changed +- Updated README.md with improved documentation navigation +- Enhanced documentation organization following industry best practices + +### Deprecated + +### Removed + +### Fixed + +### Security + +## [0.1.1] - 2026-01-20 + +### Added +- Initial protocol specifications +- Zod schemas for data, UI, system, AI, and API protocols +- JSON schema generation +- Basic documentation site with Fumadocs +- Example implementations (CRM, Todo) + +## Template for Future Releases + +```markdown +## [X.Y.Z] - YYYY-MM-DD + +### Added +- New features or capabilities + +### Changed +- Changes to existing functionality + +### Deprecated +- Features that will be removed in upcoming releases + +### Removed +- Features that have been removed + +### Fixed +- Bug fixes + +### Security +- Security-related changes +``` + +## How to Use This Changelog + +### For Contributors + +When making changes: + +1. **Add entries under `[Unreleased]`** section +2. **Choose the appropriate category**: Added, Changed, Deprecated, Removed, Fixed, Security +3. **Write clear, concise descriptions** of your changes +4. **Link to PRs or issues** where applicable: `- Feature description (#PR_NUMBER)` + +Example: +```markdown +### Added +- New encrypted field type for sensitive data (#123) +- Support for PostgreSQL window functions in query protocol (#124) + +### Fixed +- Validation error when using lookup fields with filters (#125) +``` + +### For Maintainers + +When releasing a new version: + +1. **Create a new version section** from the `[Unreleased]` content +2. **Move entries** from `[Unreleased]` to the new version section +3. **Add release date** in YYYY-MM-DD format +4. **Tag the release** in git: `git tag -a v0.2.0 -m "Release v0.2.0"` +5. **Update links** at the bottom of the file + +### Versioning Guide + +Following [Semantic Versioning](https://semver.org/): + +- **MAJOR** version (X.0.0): Incompatible API changes +- **MINOR** version (0.X.0): Add functionality in a backward compatible manner +- **PATCH** version (0.0.X): Backward compatible bug fixes + +### Categories + +- **Added**: New features, protocols, schemas, or capabilities +- **Changed**: Changes to existing functionality +- **Deprecated**: Features marked for removal (but still working) +- **Removed**: Features that have been removed +- **Fixed**: Bug fixes +- **Security**: Security vulnerability fixes or improvements + +### Breaking Changes + +Mark breaking changes clearly: + +```markdown +### Changed +- **BREAKING**: Renamed `maxLength` to `maxLen` in FieldSchema (#126) + Migration: Update all field definitions to use `maxLen` instead of `maxLength` +``` + +## Release Process + +1. Update CHANGELOG.md with release notes +2. Update version in package.json files +3. Run `pnpm changeset version` to update package versions +4. Commit changes: `git commit -m "chore: release vX.Y.Z"` +5. Create git tag: `git tag -a vX.Y.Z -m "Release vX.Y.Z"` +6. Push: `git push && git push --tags` +7. Run `pnpm release` to publish packages + +--- + +[Unreleased]: https://github.com/objectstack-ai/spec/compare/v0.1.1...HEAD +[0.1.1]: https://github.com/objectstack-ai/spec/releases/tag/v0.1.1 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..77ac1df64 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,79 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers responsible for enforcement at [INSERT CONTACT EMAIL]. All complaints will be reviewed and investigated promptly and fairly. + +All project maintainers are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from project maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/docs/guides/ai-integration/quick-start.md b/docs/guides/ai-integration/quick-start.md new file mode 100644 index 000000000..86cf3fd53 --- /dev/null +++ b/docs/guides/ai-integration/quick-start.md @@ -0,0 +1,173 @@ +# AI Integration Quick Start + +> Quick guide to integrating AI features into ObjectStack applications + +## Overview + +ObjectStack provides built-in AI capabilities through the AI Protocol. This guide covers the essentials. + +## Agent Setup + +### 1. Define an AI Agent + +```typescript +const agent = { + name: 'sales_assistant', + label: 'Sales Assistant', + model: { + provider: 'openai', + modelName: 'gpt-4', + temperature: 0.7, + }, + tools: [ + 'query_records', + 'create_record', + 'send_email', + ], + systemPrompt: 'You are a helpful sales assistant...', +}; +``` + +### 2. Configure Model Registry + +```typescript +const modelRegistry = { + models: [ + { + id: 'gpt-4', + provider: 'openai', + capabilities: ['chat', 'function_calling'], + limits: { + maxTokens: 8192, + maxContextLength: 128000, + }, + }, + ], +}; +``` + +## RAG Pipeline + +### Basic RAG Configuration + +```typescript +const ragConfig = { + knowledgeBases: ['product_docs', 'sales_playbook'], + + chunking: { + strategy: 'semantic', + chunkSize: 512, + overlap: 50, + }, + + embedding: { + model: 'text-embedding-ada-002', + provider: 'openai', + }, + + vectorStore: { + provider: 'pinecone', + config: { + apiKey: process.env.PINECONE_API_KEY, + environment: 'production', + }, + }, + + retrieval: { + topK: 5, + minScore: 0.7, + }, +}; +``` + +## Natural Language Queries + +### Enable NLQ for Objects + +```typescript +const nlqConfig = { + enabled: true, + objects: ['customer_account', 'opportunity'], + + fieldMappings: [ + { + synonyms: ['revenue', 'sales', 'income'], + field: 'annual_revenue', + }, + { + synonyms: ['company', 'business', 'organization'], + field: 'account_name', + }, + ], + + examples: [ + { + query: 'show me high value customers', + intent: 'list', + filters: [{ field: 'annual_revenue', operator: 'gt', value: 1000000 }], + }, + ], +}; +``` + +## Using AI Tools + +### Query with Natural Language + +```typescript +const result = await ai.query({ + prompt: 'Show me all accounts in the technology industry with revenue over $1M', + object: 'customer_account', +}); + +// Returns: QueryResult with structured data +``` + +### Generate with AI + +```typescript +const generated = await ai.generate({ + prompt: 'Write a follow-up email for this customer', + context: { + customer: customerData, + lastInteraction: interactionData, + }, +}); +``` + +## Best Practices + +1. **Prompt Engineering** + - Be specific and clear + - Provide context + - Use examples + +2. **Model Selection** + - Use appropriate model for task + - Balance cost vs. capability + - Consider latency requirements + +3. **RAG Optimization** + - Chunk documents semantically + - Use appropriate embedding models + - Filter results by relevance score + +4. **Error Handling** + - Handle model failures gracefully + - Implement retry logic + - Provide fallbacks + +## Examples + +See the following example implementations: + +- [AI Sales Assistant](../../../examples/ai-sales/) +- [AI Support Agent](../../../examples/ai-support/) +- [AI Code Generator](../../../examples/ai-codegen/) +- [AI Analyst](../../../examples/ai-analyst/) + +For complete documentation, see [AI_INTEGRATION_GUIDE.md](../../AI_INTEGRATION_GUIDE.md) + +--- + +**Last Updated**: 2026-01-22 diff --git a/docs/guides/performance/optimization.md b/docs/guides/performance/optimization.md new file mode 100644 index 000000000..ba537b27b --- /dev/null +++ b/docs/guides/performance/optimization.md @@ -0,0 +1,135 @@ +# Performance Optimization Guide + +> Strategies for optimizing ObjectStack Protocol implementations + +## Query Optimization + +### Select Only Needed Fields +```typescript +// βœ… Good +const query = { + select: ['id', 'name', 'email'], + from: 'customer_account', +}; + +// ❌ Bad +const query = { + select: ['*'], // Unnecessary data + from: 'customer_account', +}; +``` + +### Use Efficient Filters +- Apply filters at database level +- Use indexed fields in WHERE clauses +- Implement pagination + +### Avoid N+1 Queries +- Use joins instead of loops +- Batch load related data +- Use DataLoader pattern + +## Caching Strategies + +### Metadata Caching +- Cache object/field definitions (1 hour TTL) +- Cache user permissions (10 minutes TTL) +- Use Redis for distributed caching + +### Query Result Caching +```typescript +const cacheKey = `query:${JSON.stringify(query)}`; +const cached = await redis.get(cacheKey); +if (cached) return JSON.parse(cached); + +const results = await executeQuery(query); +await redis.setEx(cacheKey, 300, JSON.stringify(results)); +``` + +### Cache Invalidation +- Invalidate on data changes +- Use cache tags/patterns +- Implement TTL strategies + +## Database Indexing + +### Index Strategy +```typescript +const indexes = [ + { fields: ['email'], unique: true }, + { fields: ['status'] }, + { fields: ['industry', 'revenue'] }, // Composite +]; +``` + +### Best Practices +- Index frequently queried fields +- Use composite indexes for multi-field queries +- Monitor and remove unused indexes + +## API Performance + +### Connection Pooling +```typescript +const pool = new Pool({ + min: 2, + max: 10, + idleTimeoutMillis: 30000, +}); +``` + +### Response Compression +- Enable gzip compression +- Only compress responses > 1KB +- Use level 6 compression + +### Async Operations +```typescript +// Parallel execution +const [accounts, opportunities] = await Promise.all([ + queryAccounts(), + queryOpportunities(), +]); +``` + +## Frontend Optimization + +### Lazy Loading +- Load components on demand +- Code splitting +- Dynamic imports + +### Virtualization +- Use virtual scrolling for long lists +- Render only visible items +- Implement infinite scroll + +### Memoization +- Cache expensive computations +- Use React.memo for components +- useMemo for derived data + +## Monitoring + +### Performance Metrics +- Track query duration +- Log slow queries (> 1s) +- Monitor cache hit rates + +### Profiling +- Use EXPLAIN ANALYZE for queries +- Profile application code +- Monitor resource usage + +## Performance Targets + +| Metric | Target | +|--------|--------| +| API Response (p95) | < 500ms | +| Database Query (p95) | < 200ms | +| Page Load | < 2s | +| Cache Hit Rate | > 80% | + +--- + +**Last Updated**: 2026-01-22 diff --git a/docs/guides/security/best-practices.md b/docs/guides/security/best-practices.md new file mode 100644 index 000000000..4b315a97a --- /dev/null +++ b/docs/guides/security/best-practices.md @@ -0,0 +1,100 @@ +# Security Best Practices Guide + +> Comprehensive security guidelines for ObjectStack Protocol implementations + +## Authentication & Authorization + +### Strong Authentication +```typescript +const authConfig = { + providers: [ + { + type: 'email_password', + passwordPolicy: { + minLength: 12, + requireUppercase: true, + requireNumbers: true, + requireSpecialChars: true, + }, + }, + ], + twoFactor: { + enabled: true, + required: true, + }, +}; +``` + +### Session Management +- Use short session lifetimes (1-24 hours) +- Set secure cookie flags (httpOnly, secure, sameSite) +- Invalidate sessions on password change + +### RBAC +- Implement least privilege principle +- Use role-based access control +- Apply field-level security + +## Data Protection + +### Encryption +- Encrypt sensitive fields at rest +- Use HTTPS/TLS for all traffic +- Implement proper key management + +### Data Masking +- Mask sensitive data in logs +- Sanitize error messages +- Redact PII in responses + +## API Security + +### Rate Limiting +- Limit API requests per user +- Block brute force attacks +- Implement exponential backoff + +### Input Validation +- Validate all inputs with Zod schemas +- Use parameterized queries +- Prevent SQL/NoSQL injection + +### CORS & CSRF +- Configure CORS properly +- Enable CSRF protection +- Validate origin headers + +## Secrets Management + +- Store secrets in environment variables +- Never commit secrets to git +- Rotate secrets regularly +- Use secret management services + +## Audit & Compliance + +### Audit Logging +- Log security events +- Track data access +- Monitor authentication attempts + +### Compliance +- GDPR data export/erasure +- HIPAA encryption requirements +- SOC2 audit trails + +## Security Checklist + +- [ ] HTTPS enforced +- [ ] MFA enabled +- [ ] Rate limiting configured +- [ ] Input validation on all endpoints +- [ ] Secrets in environment variables +- [ ] Audit logging enabled +- [ ] Regular security updates + +For detailed information, see [AUTHENTICATION_STANDARD.md](../../../AUTHENTICATION_STANDARD.md) + +--- + +**Last Updated**: 2026-01-22 diff --git a/docs/migration/v0-to-v1.md b/docs/migration/v0-to-v1.md new file mode 100644 index 000000000..830bd48a2 --- /dev/null +++ b/docs/migration/v0-to-v1.md @@ -0,0 +1,149 @@ +# Migration Guide: v0.1.x to v1.0.0 + +> Guide for migrating from version 0.1.x to 1.0.0 + +## Overview + +This guide helps you migrate your ObjectStack Protocol implementation from version 0.1.x to 1.0.0. + +## Breaking Changes + +### 1. Naming Convention Changes + +**Configuration keys now use camelCase:** + +```typescript +// Before (0.1.x) +const field = { + max_length: 100, + is_required: true, + default_value: '', +}; + +// After (1.0.0) +const field = { + maxLength: 100, + isRequired: true, + defaultValue: '', +}; +``` + +**Machine names still use snake_case:** + +```typescript +// Correct in both versions +const object = { + name: 'customer_account', // snake_case for machine names + fields: { + first_name: { // snake_case for field names + maxLength: 100, // camelCase for config + } + } +}; +``` + +### 2. Schema Changes + +**Field type changes:** + +```typescript +// Before (0.1.x) +type: 'string' + +// After (1.0.0) +type: 'text' +``` + +### 3. API Response Structure + +**New envelope format:** + +```typescript +// Before (0.1.x) +{ + data: { /* response */ }, + error: null +} + +// After (1.0.0) +{ + success: true, + data: { /* response */ }, + metadata: { + timestamp: "2026-01-22T10:00:00Z", + requestId: "req_123" + } +} +``` + +## Migration Steps + +### Step 1: Update Dependencies + +```bash +# Update package.json +pnpm update @objectstack/spec@^1.0.0 + +# Install dependencies +pnpm install +``` + +### Step 2: Update Schema Definitions + +Run the migration script: + +```bash +pnpm migrate:schemas +``` + +Or manually update: + +```typescript +// Update all configuration keys to camelCase +// Keep machine names in snake_case +``` + +### Step 3: Update API Calls + +```typescript +// Update response handling +const response = await api.createRecord({ + object: 'customer_account', + data: { /* ... */ } +}); + +// Before +if (!response.error) { /* ... */ } + +// After +if (response.success) { /* ... */ } +``` + +### Step 4: Test Your Application + +```bash +# Run tests +pnpm test + +# Build +pnpm build +``` + +## Deprecation Warnings + +The following features are deprecated and will be removed in v2.0.0: + +- `old_api_format` - Use new envelope format +- `snake_case_configs` - Use camelCase for configuration + +## Getting Help + +If you encounter issues: + +1. Check the [CHANGELOG.md](../../CHANGELOG.md) +2. Review [CONTRIBUTING.md](../../CONTRIBUTING.md) +3. Open an issue on GitHub + +--- + +**Last Updated**: 2026-01-22