### Project Setup with ts-morph Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Initializes a new TypeScript project, installs necessary dependencies (typescript, ts-morph, @types/node), and sets up a basic tsconfig.json file. ```bash mkdir ts-morph-plugin-tutorial cd ts-morph-plugin-tutorial npm init -y npm install --save-dev typescript ts-morph @types/node ``` -------------------------------- ### JSON Schema Example Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md An example JSON file defining schemas for 'User' and 'Post' entities, including properties, types, descriptions, and required fields. ```json // examples/input.json [ { "name": "User", "description": "Represents a user in the system", "properties": { "id": { "type": "string", "description": "Unique identifier for the user" }, "email": { "type": "string", "description": "User's email address" }, "name": { "type": "string", "description": "User's full name" }, "age": { "type": "number", "description": "User's age in years" }, "isActive": { "type": "boolean", "description": "Whether the user account is active", "default": true }, "roles": { "type": "array", "items": { "type": "string" }, "description": "User's assigned roles" }, "profile": { "type": "object", "properties": { "bio": { "type": "string" }, "avatar": { "type": "string" } }, "description": "User's profile information" }, "createdAt": { "type": "string", "description": "Account creation timestamp" } }, "required": ["id", "email", "name"] }, { "name": "Post", "description": "Represents a blog post", "properties": { "id": { "type": "string", "description": "Unique identifier for the post" }, "title": { "type": "string", "description": "Post title" }, "content": { "type": "string", "description": "Post content" }, "authorId": { "type": "string", "description": "ID of the post author" }, "tags": { "type": "array", "items": { "type": "string" }, "description": "Post tags" }, "publishedAt": { "type": "string", "description": "Publication timestamp" } }, "required": ["id", "title", "content", "authorId"] } ] ``` -------------------------------- ### Generate Example JSON Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Generates a JSON object with example values for a given model, iterating through columns and using a helper function to determine appropriate example data based on type and attributes. ```JavaScript function generateJSONExample(model, schema) { const example = {}; for (const column of model.columns || []) { const value = generateExampleValue(column, schema); if (value !== undefined) { example[column.name] = value; } } return JSON.stringify(example, null, 2); } ``` -------------------------------- ### Install ts-morph Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Installs the ts-morph library as a development dependency for npm, yarn, or Deno projects. ```bash # Using npm npm install --save-dev ts-morph # Using yarn yarn add --dev ts-morph # Using Deno deno add ts-morph@jsr:@ts-morph/ts-morph ``` -------------------------------- ### Generate Model Examples in TypeScript Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Generates example JSON structures and schema definitions for a given model. It calls `generateJSONExample` and `generateSchemaExample` to create the examples and formats them within code blocks. ```typescript function generateModelExamples(modelName: string, model: any, schema: any, options: any): string { let content = '#### Examples\n\n'; // Generate JSON example content += '##### JSON Structure\n\n'; content += '```json\n'; content += generateJSONExample(model, schema); content += '\n```\n\n'; // Generate schema definition example content += '##### Schema Definition\n\n'; content += '```idea\n'; content += generateSchemaExample(modelName, model); content += '\n```\n\n'; return content; } ``` -------------------------------- ### Working with Existing Code Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Provides an example of loading existing TypeScript files, getting specific files, finding interfaces, and modifying them by adding properties and JSDoc comments. ```typescript // Load existing files project.addSourceFilesAtPaths("src/**/*.ts"); // Get a specific file const existingFile = project.getSourceFile("src/models/User.ts"); // Find and modify existing constructs const userInterface = existingFile?.getInterface("User"); if (userInterface) { // Add a new property userInterface.addProperty({ name: "email", type: "string", hasQuestionToken: true, // Makes it optional }); // Add JSDoc comments userInterface.addJsDoc({ description: "Represents a user in the system", tags: [ { tagName: "example", text: "const user: User = { id: '1', name: 'John' };" }, ], }); } ``` -------------------------------- ### Install @stackpress/idea-parser Source: https://github.com/stackpress/idea/blob/main/docs/parser/README.md Installs the Idea Parser library using npm. ```bash npm install @stackpress/idea-parser ``` -------------------------------- ### Install @stackpress/idea-transformer Source: https://github.com/stackpress/idea/blob/main/docs/transformer/README.md Installs the idea-transformer library using npm. This is the first step to using the schema transformation tool. ```bash npm install @stackpress/idea-transformer ``` -------------------------------- ### Basic CLI Usage Examples Source: https://github.com/stackpress/idea/blob/main/docs/transformer/Terminal.md Provides examples of how to use the terminal's 'transform' command directly from the command line, including basic usage and using the short flag alias. ```bash ## Basic usage node cli.js transform --input ./schema.idea ## Using short flag node cli.js transform --i ./schema.idea ## With custom working directory cd /path/to/project && node cli.js transform --i ./schema.idea ``` -------------------------------- ### Generated Client Usage Example Source: https://github.com/stackpress/idea/blob/main/docs/plugins/api-client-plugin.md Shows how to use the generated API client in TypeScript, including initialization, setting authentication tokens, and making example requests for fetching, creating, updating, and deleting users. ```typescript import APIClient from './api-client'; // Initialize client const client = new APIClient('https://api.example.com'); // Set authentication token client.setAuthToken('your-jwt-token'); // Use the client async function example() { // Get all users with pagination const usersResponse = await client.user.getAll({ page: 1, limit: 10, search: 'john' }); if (usersResponse.success) { console.log('Users:', usersResponse.data); console.log('Total:', usersResponse.total); } // Get user by ID const userResponse = await client.user.getById('user-123'); if (userResponse.success) { console.log('User:', userResponse.data); } // Create new user const newUserResponse = await client.user.create({ email: 'john@example.com', name: 'John Doe', role: UserRole.USER }); if (newUserResponse.success) { console.log('Created user:', newUserResponse.data); } // Update user const updateResponse = await client.user.update('user-123', { name: 'John Smith' }); // Delete user const deleteResponse = await client.user.delete('user-123'); } ``` -------------------------------- ### Install OpenAPI Dependencies Source: https://github.com/stackpress/idea/blob/main/docs/plugins/openapi-spec-plugin.md Lists the necessary npm packages to install for working with OpenAPI specifications, including tools for handling YAML, serving UI, parsing, and code generation. ```bash # Install required dependencies npm install --save-dev yaml swagger-ui-dist # For validation npm install --save-dev swagger-parser # For code generation npm install --save-dev @openapitools/openapi-generator-cli ``` -------------------------------- ### Install Idea Transformer CLI Source: https://github.com/stackpress/idea/blob/main/packages/idea-transformer/README.md Instructions for installing the Idea Transformer CLI using npm or yarn. ```bash $ npm install @stackpress/idea-transformer ... or ... $ yarn add @stackpress/idea-transformer ``` -------------------------------- ### Stackpress Idea CLI Installation Source: https://github.com/stackpress/idea/blob/main/README.md Installs the Stackpress Idea CLI tool as a development dependency using npm. ```bash $ npm i -D @stackpress/idea ``` -------------------------------- ### Schema Structure Example Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md An example of a processed schema structure, including models, enums, types, and props, which serves as the input for the documentation generator. ```typescript // Example processed schema { model: { User: { mutable: false, columns: [ { name: 'id', type: 'String', required: true, multiple: false, attributes: { id: true, label: 'User ID', default: 'nanoid()', description: 'Unique identifier for the user' } }, { name: 'email', type: 'String', required: true, multiple: false, attributes: { unique: true, label: 'Email Address', field: { input: { type: 'email' } }, description: 'User email address for authentication' } } ] } }, enum: { UserRole: { ADMIN: 'Administrator', USER: 'Regular User', GUEST: 'Guest User' } }, type: { Address: { mutable: true, columns: [ { name: 'street', type: 'String', required: true, multiple: false, attributes: { label: 'Street Address' } } ] } }, prop: { Text: { type: 'text', placeholder: 'Enter text', maxLength: 255 } } } ``` -------------------------------- ### Plugin Configuration Examples Source: https://github.com/stackpress/idea/blob/main/docs/Specifications.md Demonstrates configuring various plugins for type generation, database schema creation, API documentation generation, and form generation. ```typescript // Type generation plugin "./plugins/typescript-generator.js" { output "./src/types/schema.ts" namespace "Schema" } // Database schema plugin "./plugins/database-generator.js" { output "./database/schema.sql" dialect "postgresql" } // API documentation plugin "./plugins/openapi-generator.js" { output "./docs/api.yaml" version "1.0.0" } // Form generation plugin "./plugins/form-generator.js" { output "./src/components/forms/" framework "react" styling "tailwind" } ``` -------------------------------- ### Add Examples to OpenAPI Specification Source: https://github.com/stackpress/idea/blob/main/docs/plugins/openapi-spec-plugin.md Adds example data to schemas and endpoints within an OpenAPI specification. It recursively generates examples for properties based on their types and formats. ```typescript function addExamples(spec: any, schema: any): void { // Add examples to schemas for (const [name, schemaObj] of Object.entries(spec.components.schemas)) { if (schemaObj.type === 'object') { schemaObj.example = generateExample(schemaObj, schema); } } // Add examples to endpoints for (const [path, pathObj] of Object.entries(spec.paths)) { for (const [method, operation] of Object.entries(pathObj)) { if (operation.requestBody?.content?.['application/json']?.schema) { const schema = operation.requestBody.content['application/json'].schema; if (!schema.example) { schema.example = generateExample(schema, schema); } } } } } function generateExample(schemaObj: any, fullSchema: any): any { if (schemaObj.$ref) { const refName = schemaObj.$ref.split('/').pop(); return generateExample(fullSchema.components?.schemas?.[refName] || {}, fullSchema); } if (schemaObj.type === 'object') { const example: any = {}; for (const [propName, propSchema] of Object.entries(schemaObj.properties || {})) { example[propName] = generatePropertyExample(propSchema); } return example; } if (schemaObj.type === 'array') { return [generateExample(schemaObj.items, fullSchema)]; } return generatePropertyExample(schemaObj); } function generatePropertyExample(propSchema: any): any { if (propSchema.example !== undefined) { return propSchema.example; } if (propSchema.enum) { return propSchema.enum[0]; } switch (propSchema.type) { case 'string': if (propSchema.format === 'email') return 'user@example.com'; if (propSchema.format === 'date-time') return new Date().toISOString(); if (propSchema.format === 'date') return new Date().toISOString().split('T')[0]; return 'string'; case 'number': return 42.5; case 'integer': return 42; case 'boolean': return true; case 'array': return [generatePropertyExample(propSchema.items)]; case 'object': return {}; default: return null; } } ``` -------------------------------- ### Generate JSON Example in TypeScript Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Generates a JSON example based on the model and schema. The function iterates through the model's columns. ```typescript function generateJSONExample(model: any, schema: any): string { const example: any = {}; for (const column of model.columns || []) { ``` -------------------------------- ### Complete Schema Example in TypeScript Source: https://github.com/stackpress/idea/blob/main/docs/parser/README.md Provides a comprehensive example of a `.idea` schema file, including plugins, props, enums, types, and models, parsed using the `final` function. ```typescript import { final } from '@stackpress/idea-parser'; const schemaCode = ` plugin "./database-plugin" { provider "postgresql" url env("DATABASE_URL") } prop Text { type "text" } prop Email { type "email" format "email" } enum UserRole { ADMIN "Administrator" USER "Regular User" GUEST "Guest User" } type Address { street String @field.input(Text) @is.required city String @field.input(Text) @is.required country String @field.select postal String @field.input(Text) } model User! { id String @id @default("nanoid()") email String @field.input(Email) @is.required @is.unique name String @field.input(Text) @is.required role UserRole @default("USER") address Address? active Boolean @default(true) created Date @default("now()") updated Date @default("updated()") } `; const result = final(schemaCode); console.log(JSON.stringify(result, null, 2)); ``` -------------------------------- ### Generate Example Value by Type Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Generates an example value for a given column based on its type and attributes. It handles defaults, specific formats like email/URL, numeric ranges, booleans, dates, enums, and nested types. ```TypeScript function generateExampleValue(column: any, schema: any): any { const { type, attributes = {} } = column; // Use default value if available if (attributes.default !== undefined) { return attributes.default; } // Generate example based on type switch (type) { case 'String': if (attributes.email) { return 'user@example.com'; } if (attributes.url) { return 'https://example.com'; } if (attributes.id) { return 'abc123def456'; } return `Example ${column.name}`; case 'Number': if (attributes.min && attributes.max) { return Math.floor((attributes.min + attributes.max) / 2); } if (attributes.min) { return attributes.min + 10; } if (attributes.max) { return Math.floor(attributes.max / 2); } return 42; case 'Boolean': return true; case 'Date': return new Date().toISOString(); default: // Check if it's an enum if (schema.enum && schema.enum[type]) { const enumValues = Object.keys(schema.enum[type]); return enumValues[0]; } // Check if it's a type if (schema.type && schema.type[type]) { return generateJSONExample(schema.type[type], schema); } return null; } } ``` -------------------------------- ### Install @stackpress/idea Package Source: https://github.com/stackpress/idea/blob/main/packages/idea/README.md This snippet shows how to install the @stackpress/idea package as a development dependency using npm. ```bash $ npm i -D @stackpress/idea ``` -------------------------------- ### Plugin Development Example Source: https://github.com/stackpress/idea/blob/main/docs/transformer/README.md Provides an example of how to develop a custom plugin for the idea-transformer, including accessing schema context and generating output. ```typescript import type { PluginProps } from '@stackpress/idea-transformer/types'; export default async function myPlugin(props: PluginProps<{}>) { const { config, schema, transformer, cwd } = props; // Process schema and generate output const content = generateFromSchema(schema); const outputPath = await transformer.loader.absolute(config.output); await writeFile(outputPath, content); } ``` -------------------------------- ### Stackpress Plugin Development Example Source: https://github.com/stackpress/idea/blob/main/docs/Specifications.md A TypeScript example demonstrating how to develop a custom plugin for the Stackpress idea transformer. It shows how to access configuration, schema, and transformer utilities to generate and write output files. ```typescript import type { PluginProps } from '@stackpress/idea-transformer/types'; export default async function myPlugin(props: PluginProps<{}>) { const { config, schema, transformer } = props; // Process schema and generate output const content = generateFromSchema(schema); // Write to configured output path const outputPath = await transformer.loader.absolute(config.output); await writeFile(outputPath, content); } ``` -------------------------------- ### ts-morph Project and SourceFile Basics Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Demonstrates creating a ts-morph Project, creating a new source file, adding an interface with properties, and retrieving the generated code. ```typescript import { Project, ScriptTarget, ModuleKind } from "ts-morph"; // Create a new project const project = new Project({ compilerOptions: { target: ScriptTarget.ES2020, module: ModuleKind.CommonJS, }, }); // Create a source file const sourceFile = project.createSourceFile("example.ts", ""); // Add content to the file sourceFile.addInterface({ name: "User", properties: [ { name: "id", type: "string" }, { name: "name", type: "string" }, ], }); // Get the generated code console.log(sourceFile.getFullText()); // Output: // interface User { // id: string; // name: string; // } ``` -------------------------------- ### Stackpress Plugin Declaration Example Source: https://github.com/stackpress/idea/blob/main/docs/Specifications.md An example of how to declare a plugin within the .idea file format, specifying the plugin path, output file, format, and options. ```typescript plugin "./path/to/plugin.js" { output "./generated/output.ts" format "typescript" options { strict true comments true } } ``` -------------------------------- ### Basic tsconfig.json Configuration Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md A sample tsconfig.json file for a TypeScript project using ts-morph, configuring target, module, output directories, and strictness. ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "declaration": true, "declarationMap": true, "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ``` -------------------------------- ### Run Plugin Tests Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Command to execute the unit tests for the Stackpress plugin using npm. ```bash npm test ``` -------------------------------- ### Namespace Support Example Source: https://github.com/stackpress/idea/blob/main/docs/plugins/typescript-interfaces-plugin.md Demonstrates how to configure and generate TypeScript code within a namespace using the plugin's namespace and exportType options. ```typescript // With namespace configuration namespace: "MyApp" exportType: "namespace" // Generated output: export namespace MyApp { export enum UserRole { ADMIN = "admin", USER = "user", } export interface User { id: string; name: string; role: UserRole; } } ``` -------------------------------- ### Generate Axios Instance Setup for API Client (TypeScript) Source: https://github.com/stackpress/idea/blob/main/docs/plugins/api-client-plugin.md This function generates the configuration and setup code for an Axios instance within the `BaseAPIClient`. It initializes Axios with a base URL and timeout, and configures request and response interceptors to automatically add authentication headers and handle API errors consistently. ```typescript function generateAxiosSetup(): string { return ` this.axiosInstance = axios.create({ baseURL: this.baseUrl, timeout: 10000, }); // Request interceptor for auth this.axiosInstance.interceptors.request.use((config) => { const authHeaders = this.getAuthHeaders(); config.headers = { ...config.headers, ...authHeaders }; return config; }); // Response interceptor for error handling this.axiosInstance.interceptors.response.use( (response) => response, (error: AxiosError) => { throw this.handleError(error); } ); `; } ``` -------------------------------- ### Integration: NPM Scripts Source: https://github.com/stackpress/idea/blob/main/docs/transformer/Terminal.md Provides examples of NPM scripts for building, developing, and watching schema transformations. ```json { "scripts": { "schema:build": "node -e \"import('./cli.js').then(m => m.default(['transform', '--i', './schema.idea']))\"", "schema:dev": "node -e \"import('./cli.js').then(m => m.default(['transform', '--i', './dev-schema.idea']))\"", "schema:watch": "nodemon --watch schema.idea --exec \"npm run schema:build\"" } } ``` -------------------------------- ### Generated Markdown: Profile Type Documentation Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Markdown documentation for the 'Profile' type, detailing its properties including bio, avatar, and website, along with a JSON example. ```markdown ## Types Types define reusable data structures that can be embedded in models. ### Profile **Mutability:** Mutable #### Properties | Name | Type | Required | Multiple | Description | |------|------|----------|----------|-------------| | bio | `String` | ✓ | ✗ | User biography | | avatar | `String` | ✓ | ✗ | Profile picture URL | | website | `String` | ✓ | ✗ | Personal website URL | #### Example ```json { "bio": "Example bio", "avatar": "Example avatar", "website": "https://example.com" } ``` ``` -------------------------------- ### Stackpress Idea Basic Schema Example Source: https://github.com/stackpress/idea/blob/main/README.md A minimal `.idea` schema defining a 'User' model and configuring the TypeScript generator plugin. ```typescript model User { id String @id @default("nanoid()") name String @required email String @unique @required created Date @default("now()") } plugin "./plugins/typescript-generator.js" { output "./generated/types.ts" } ``` -------------------------------- ### Parse Prop Declarations Source: https://github.com/stackpress/idea/blob/main/docs/parser/Trees.md Provides an example of parsing prop (property configuration) declarations from a string using PropTree.parse. It demonstrates accessing the parsed AST for prop definitions. ```typescript import { PropTree } from '@stackpress/idea-parser'; const propCode = `prop EmailInput { type "email" format "email" placeholder "Enter your email" required true }`; const ast = PropTree.parse(propCode); console.log(ast.kind); // 'prop' console.log(ast.declarations[0].id.name); // 'EmailInput' ``` -------------------------------- ### JSDoc Comment Generation for Schema Properties Source: https://github.com/stackpress/idea/blob/main/docs/plugins/ts-morph-plugin-guide.md Provides a utility function `generateJSDocComment` to create JSDoc comments for schema properties. It includes support for descriptions, default values, examples, and deprecation notices, enhancing code documentation. ```typescript function generateJSDocComment( property: SchemaProperty, includeExamples: boolean = true ): string { const parts: string[] = []; if (property.description) { parts.push(property.description); } if (property.default !== undefined) { parts.push(`@default ${JSON.stringify(property.default)}`); } if (includeExamples && property.example) { parts.push(`@example ${property.example}`); } if (property.deprecated) { parts.push(`@deprecated ${property.deprecated}`); } return parts.length > 0 ? parts.join('\n') : ''; } ``` -------------------------------- ### CLI Commands for OpenAPI Specification Source: https://github.com/stackpress/idea/blob/main/docs/plugins/openapi-spec-plugin.md Provides essential command-line instructions for managing the OpenAPI specification. This includes transforming the schema, serving the documentation locally, validating the specification file, and generating client SDKs in various languages. ```bash # Generate OpenAPI specification npm run transform # Serve documentation locally npx swagger-ui-serve docs/api-spec.json # Validate specification npx swagger-codegen validate -i docs/api-spec.json # Generate client SDKs npx swagger-codegen generate -i docs/api-spec.json -l typescript-fetch -o ./sdk/typescript npx swagger-codegen generate -i docs/api-spec.json -l python -o ./sdk/python ``` -------------------------------- ### Add Validation Examples to OpenAPI Spec Source: https://github.com/stackpress/idea/blob/main/docs/plugins/openapi-spec-plugin.md Adds valid and invalid examples to request bodies in an OpenAPI specification to aid in validation and testing. It iterates through paths and methods, generating examples based on the JSON schema. ```typescript function addValidationExamples(spec: any): void { // Add validation examples to request bodies for (const [path, pathObj] of Object.entries(spec.paths)) { for (const [method, operation] of Object.entries(pathObj)) { if (operation.requestBody?.content?.['application/json']?.schema) { const schema = operation.requestBody.content['application/json'].schema; // Add valid example if (!schema.example) { schema.example = generateValidExample(schema); } // Add examples for validation errors if (!schema.examples) { schema.examples = { valid: { summary: 'Valid request', value: generateValidExample(schema) }, invalid: { summary: 'Invalid request (validation errors)', value: generateInvalidExample(schema) } }; } } } } } function generateValidExample(schema: any): any { // Generate a valid example based on schema if (schema.$ref) { return { id: '123', name: 'Example' }; } const example: any = {}; for (const [propName, propSchema] of Object.entries(schema.properties || {})) { example[propName] = generatePropertyExample(propSchema); } return example; } function generateInvalidExample(schema: any): any { // Generate an invalid example to show validation errors const example: any = {}; for (const [propName, propSchema] of Object.entries(schema.properties || {})) { // Intentionally create invalid values if (propSchema.type === 'string' && propSchema.format === 'email') { example[propName] = 'invalid-email'; } else if (propSchema.type === 'string' && propSchema.minLength) { example[propName] = 'x'; // Too short } else if (propSchema.type === 'number' && propSchema.minimum) { example[propName] = propSchema.minimum - 1; // Below minimum } else { example[propName] = null; // Invalid type } } return example; } ``` -------------------------------- ### Basic Schema with API Client Plugin Source: https://github.com/stackpress/idea/blob/main/docs/plugins/api-client-plugin.md Demonstrates a basic schema definition including an enum and models, with the API Client plugin configured to generate a REST client using fetch. ```idea enum UserRole { ADMIN "admin" USER "user" GUEST "guest" } model User { id String @id @default("nanoid()") email String @unique @required name String @required role UserRole @default("USER") active Boolean @default(true) createdAt Date @default("now()") } model Post { id String @id @default("nanoid()") title String @required content String @required authorId String @required published Boolean @default(false) createdAt Date @default("now()") } plugin "./plugins/api-client.js" { output "./api-client.ts" clientType "rest" httpLibrary "fetch" baseUrl "/api/v1" generateTypes true } ``` -------------------------------- ### .idea Enum Definition Example Source: https://github.com/stackpress/idea/blob/main/docs/Specifications.md Provides examples of defining enumerations (Enums) in the .idea format for representing fixed sets of options. ```typescript enum EnumName { KEY1 "Display Value 1" KEY2 "Display Value 2" KEY3 "Display Value 3" } enum UserRole { ADMIN "Administrator" MODERATOR "Moderator" USER "Regular User" GUEST "Guest User" } enum OrderStatus { PENDING "Pending Payment" PAID "Payment Confirmed" SHIPPED "Order Shipped" DELIVERED "Order Delivered" CANCELLED "Order Cancelled" } enum Priority { LOW "Low Priority" MEDIUM "Medium Priority" HIGH "High Priority" URGENT "Urgent" } ``` -------------------------------- ### Generated Markdown: User Model Documentation Source: https://github.com/stackpress/idea/blob/main/docs/plugins/markdown-docs-plugin.md Markdown documentation for the 'User' model, including a table of columns with types, requirements, and descriptions, as well as detailed column information and JSON examples. ```markdown # My Application Schema API Reference documentation for the schema definitions. ## Overview This document provides comprehensive API documentation for all schema elements including models, types, enums, and properties. Generated on: 2024-01-15T10:30:00.000Z ## Table of Contents - [Models](#models) - [User](#user) - [Types](#types) - [Profile](#profile) - [Enums](#enums) - [UserRole](#userrole) - [Props](#props) - [Email](#email) ## Models Models represent the main data structures in your application. ### User **Mutability:** Immutable #### Columns | Name | Type | Required | Multiple | Description | |------|------|----------|----------|-------------| | id | `String` | ✓ | ✗ | Unique identifier for the user | | email | `String` | ✓ | ✗ | User email address for authentication | | name | `String` | ✓ | ✗ | Full name of the user | | role | [UserRole](#userrole) | ✓ | ✗ | User's role in the system | | profile | [Profile](#profile) | ✗ | ✗ | Optional user profile information | | active | `Boolean` | ✓ | ✗ | Whether the user account is active | | created | `Date` | ✓ | ✗ | Account creation timestamp | #### Column Details ##### id - **Type:** `String` - **Required:** Yes - **Default:** `nanoid()` - **Description:** Unique identifier for the user - **Database:** Primary key ##### email - **Type:** `String` - **Required:** Yes - **Description:** User email address for authentication - **Validation:** - Must be a valid email address - **Field Configuration:** - Input type: email - **Database:** Unique constraint ##### name - **Type:** `String` - **Required:** Yes - **Description:** Full name of the user - **Field Configuration:** - Input type: text ##### role - **Type:** [UserRole](#userrole) - **Required:** Yes - **Default:** `USER` - **Description:** User's role in the system - **Field Configuration:** - Rendered as: Select dropdown ##### profile - **Type:** [Profile](#profile) - **Required:** No - **Description:** Optional user profile information ##### active - **Type:** `Boolean` - **Required:** Yes - **Default:** `true` - **Description:** Whether the user account is active - **Field Configuration:** - Rendered as: Checkbox ##### created - **Type:** `Date` - **Required:** Yes - **Default:** `now()` - **Description:** Account creation timestamp #### Examples ##### JSON Structure ```json { "id": "abc123def456", "email": "user@example.com", "name": "Example name", "role": "ADMIN", "profile": { "bio": "Example bio", "avatar": "Example avatar", "website": "https://example.com" }, "active": true, "created": "2024-01-15T10:30:00.000Z" } ``` ##### Schema Definition ```idea model User! { id String @id @default("nanoid()") email String @unique @default("USER") name String @optional role UserRole @optional profile Profile? @optional active Boolean @optional created Date @optional } ``` ``` -------------------------------- ### Basic Schema Definition and Plugin Configuration Source: https://github.com/stackpress/idea/blob/main/docs/plugins/graphql-schema-plugin.md Example of defining a GraphQL schema using Stackpress Idea's syntax, including enums, models, and plugin configuration for schema generation. It demonstrates how to specify the output file and enable query and mutation generation. ```idea enum UserRole { ADMIN "admin" USER "user" GUEST "guest" } model User { id String @id @default("nanoid()") email String @unique @required name String @required role UserRole @default("USER") active Boolean @default(true) createdAt Date @default("now()") } plugin "./plugins/graphql-schema.js" { output "./schema.graphql" includeQueries true includeMutations true } ``` -------------------------------- ### Example CSS for Theming Source: https://github.com/stackpress/idea/blob/main/docs/plugins/html-form-plugin.md Provides example CSS rules for styling buttons, demonstrating theme-specific background colors and hover effects. ```CSS .btn-primary { background: #2980b9; } .btn-secondary { background: #95a5a6; color: white; } .btn-secondary:hover { background: #7f8c8d; } ``` -------------------------------- ### Load and Run Terminal Instance Source: https://github.com/stackpress/idea/blob/main/docs/transformer/Terminal.md Demonstrates loading a Terminal instance with command-line arguments and executing its operations. This is the primary way to interact with the terminal for schema transformations. ```typescript import Terminal from '@stackpress/idea-transformer/Terminal'; const terminal = await Terminal.load(['transform', '--input', './schema.idea']); await terminal.run(); ``` -------------------------------- ### Schema Validation Examples Source: https://github.com/stackpress/idea/blob/main/docs/parser/README.md Shows examples of valid and invalid schema structures for models in Stackpress Idea. It highlights the importance of including required properties like 'columns' for models. ```typescript // Good: Proper model structure model User { id String @id name String } // Bad: Missing required properties model User { // Missing columns - will throw error } ``` -------------------------------- ### Configure Lexer for Schema Parsing Source: https://github.com/stackpress/idea/blob/main/docs/parser/Trees.md Demonstrates how to initialize a Lexer and configure it with schema parsing definitions using SchemaTree.definitions(). This prepares the lexer to recognize schema constructs. ```typescript import { SchemaTree, Lexer } from '@stackpress/idea-parser'; const lexer = new Lexer(); SchemaTree.definitions(lexer); // Lexer now has definitions for all schema constructs: // enum, prop, type, model, plugin, use keywords and structures ``` -------------------------------- ### Basic Schema Example Source: https://github.com/stackpress/idea/blob/main/docs/plugins/typescript-interfaces-plugin.md Demonstrates a basic schema definition including an enum, a custom type, and a model. It also shows the plugin configuration for generating TypeScript interfaces. ```idea enum UserRole { ADMIN "admin" USER "user" GUEST "guest" } type Address { street String @required city String @required country String @required postal String } model User { id String @id @default("nanoid()") email String @unique @required name String @required role UserRole @default("USER") address Address? active Boolean @default(true) createdAt Date @default("now()") } plugin "./plugins/typescript-interfaces.js" { output "./types.ts" generateUtilityTypes true includeComments true } ``` -------------------------------- ### Main API Client Initialization Source: https://github.com/stackpress/idea/blob/main/docs/plugins/api-client-plugin.md Initializes the main API client, which can manage both RESTful and GraphQL clients based on the configuration. It provides a unified interface for interacting with different API types. ```typescript // Main API Client // Assuming BaseAPIClient, APIClientConfig, and GraphQLClient are defined elsewhere // Placeholder for model-specific client generation class SomeModelClient { // ... client methods ... } function generateGraphQLClients(models: Record, config: APIClientConfig): string { let content = '// GraphQL API Clients\n'; content += ` export class GraphQLClient extends BaseAPIClient { private apolloClient: ApolloClient; constructor(baseUrl: string = '${config.baseUrl || '/graphql'}') { super(baseUrl); this.apolloClient = new ApolloClient({ uri: this.baseUrl, cache: new InMemoryCache(), }); } private async executeQuery(query: DocumentNode, variables?: any): Promise> { try { const result = await this.apolloClient.query({ query, variables, }); return { success: true, data: result.data }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'GraphQL query failed', }; } } private async executeMutation(mutation: DocumentNode, variables?: any): Promise> { try { const result = await this.apolloClient.mutate({ mutation, variables, }); return { success: true, data: result.data }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'GraphQL mutation failed', }; } } `; for (const [modelName, model] of Object.entries(models)) { const lowerName = modelName.toLowerCase(); const pluralName = `${lowerName}s`; content += ` // ${modelName} GraphQL operations async get${pluralName}(variables?: { limit?: number; offset?: number }): Promise> { const query = gql` query Get${pluralName}($limit: Int, $offset: Int) { ${pluralName}(limit: $limit, offset: $offset) { ${generateGraphQLFields(model)} } } `; return this.executeQuery<${modelName}[]>(query, variables); } async get${modelName}(id: string): Promise> { const query = gql` query Get${modelName}($id: ID!) { ${lowerName}(id: $id) { ${generateGraphQLFields(model)} } } `; return this.executeQuery<${modelName}>(query, { id }); } async create${modelName}(input: Create${modelName}Input): Promise> { const mutation = gql` mutation Create${modelName}($input: ${modelName}Input!) { create${modelName}(input: $input) { ${generateGraphQLFields(model)} } } `; return this.executeMutation<${modelName}>(mutation, { input }); } async update${modelName}(id: string, input: Update${modelName}Input): Promise> { const mutation = gql` mutation Update${modelName}($id: ID!, $input: ${modelName}UpdateInput!) { update${modelName}(id: $id, input: $input) { ${generateGraphQLFields(model)} } } `; return this.executeMutation<${modelName}>(mutation, { id, input }); } async delete${modelName}(id: string): Promise> { const mutation = gql` mutation Delete${modelName}($id: ID!) { delete${modelName}(id: $id) } `; return this.executeMutation(mutation, { id }); } `; } content += '} '; return content; } function generateGraphQLFields(model: any): string { return model.columns?.map((col: any) => col.name).join('\n ') || 'id'; } function generateMainClient(schema: any, config: APIClientConfig): string { let content = '// Main API Client\n'; content += `export class APIClient extends BaseAPIClient { `; if (schema.model) { for (const [modelName] of Object.entries(schema.model)) { const lowerName = modelName.toLowerCase(); if (config.clientType === 'rest' || config.clientType === 'both') { content += ` public ${lowerName}: ${modelName}Client; `; } } if (config.clientType === 'graphql' || config.clientType === 'both') { content += ` public graphql: GraphQLClient; `; } } content += ` constructor(baseUrl?: string) { super(baseUrl); `; if (schema.model) { for (const [modelName] of Object.entries(schema.model)) { const lowerName = modelName.toLowerCase(); if (config.clientType === 'rest' || config.clientType === 'both') { content += ` this.${lowerName} = new ${modelName}Client(baseUrl); `; } } if (config.clientType === 'graphql' || config.clientType === 'both') { content += ` this.graphql = new GraphQLClient(baseUrl); `; } } content += ` } // Set auth token for all clients setAuthToken(token: string): void { super.setAuthToken(token); `; if (schema.model) { // Logic to set auth token for sub-clients if needed } content += ` } } `; return content; } ``` -------------------------------- ### Parse Schema Content with Custom Start Position Source: https://github.com/stackpress/idea/blob/main/docs/parser/Trees.md Illustrates parsing schema content using an instance of SchemaTree, allowing for a custom starting position within the code string. This returns a SchemaToken with parsed declarations. ```typescript import { SchemaTree } from '@stackpress/idea-parser'; const tree = new SchemaTree(); const schemaCode = 'enum Status { ACTIVE "Active" }'; const result = tree.parse(schemaCode, 0); console.log(result.body[0].kind); // 'enum' ``` -------------------------------- ### Plugin Structure and Configuration Source: https://github.com/stackpress/idea/blob/main/docs/plugins/api-client-plugin.md Defines the structure of the API client generator plugin and its configuration interface, including output path, client type, HTTP library, authentication, and error handling options. ```typescript import type { PluginProps } from '@stackpress/idea-transformer/types'; import fs from 'fs/promises'; import path from 'path'; interface APIClientConfig { output: string; clientType: 'rest' | 'graphql' | 'both'; httpLibrary?: 'fetch' | 'axios'; baseUrl?: string; authentication?: { type: 'bearer' | 'apikey' | 'basic' | 'custom'; headerName?: string; }; generateTypes?: boolean; includeValidation?: boolean; errorHandling?: 'throw' | 'return' | 'callback'; } export default async function generateAPIClient( props: PluginProps<{ config: APIClientConfig }> ) { const { config, schema, transformer } = props; // Implementation here... } ```