@tamyla/clodo-framework 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -93,6 +93,119 @@ export class ErrorHandler {
93
93
  console.error(' - Review service logs for startup errors');
94
94
  }
95
95
 
96
+ /**
97
+ * Handle D1 database related errors specifically
98
+ * @param {Error} error - The D1 database error
99
+ * @param {Object} context - Context information (environment, service, etc.)
100
+ */
101
+ static handleD1DatabaseError(error, context = {}) {
102
+ console.error(`\nāŒ D1 Database Error`);
103
+ console.error(` Environment: ${context.environment || 'unknown'}`);
104
+ console.error(` Service: ${context.service || 'unknown'}`);
105
+ console.error(` Error: ${error.message}`);
106
+ const errorMessage = error.message.toLowerCase();
107
+ if (errorMessage.includes("couldn't find a d1 db")) {
108
+ console.error('\nšŸ—„ļø D1 Database Not Found:');
109
+ console.error(' - The database specified in wrangler.toml does not exist');
110
+ console.error(' - Check database name and ID in [[d1_databases]] section');
111
+ console.error(' - List available databases: wrangler d1 list');
112
+ console.error(' - Create missing database: wrangler d1 create <database-name>');
113
+ console.error(' - Verify you\'re authenticated to the correct Cloudflare account');
114
+ } else if (errorMessage.includes('binding') && errorMessage.includes('not found')) {
115
+ console.error('\nšŸ”— D1 Binding Configuration Error:');
116
+ console.error(' - Check [[d1_databases]] section in wrangler.toml');
117
+ console.error(' - Ensure binding name matches what your code expects');
118
+ console.error(' - Verify database_name and database_id are correct');
119
+ console.error(' - Example configuration:');
120
+ console.error(' [[d1_databases]]');
121
+ console.error(' binding = "DB"');
122
+ console.error(' database_name = "my-database"');
123
+ console.error(' database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"');
124
+ } else if (errorMessage.includes('unauthorized') || errorMessage.includes('forbidden')) {
125
+ console.error('\nšŸ”’ D1 Permission Error:');
126
+ console.error(' - Verify Cloudflare API token has D1 permissions');
127
+ console.error(' - Check if you have access to the specified database');
128
+ console.error(' - Ensure you\'re authenticated to the correct account');
129
+ console.error(' - Re-authenticate: wrangler auth login');
130
+ } else if (errorMessage.includes('migration')) {
131
+ console.error('\nšŸ”„ D1 Migration Error:');
132
+ console.error(' - Check migration files for syntax errors');
133
+ console.error(' - Verify migration file names follow correct format');
134
+ console.error(' - List migrations: wrangler d1 migrations list <database>');
135
+ console.error(' - Apply migrations manually: wrangler d1 migrations apply <database>');
136
+ } else {
137
+ console.error('\nšŸ’” General D1 Troubleshooting:');
138
+ console.error(' - Check Cloudflare account has D1 enabled');
139
+ console.error(' - Verify wrangler is up to date: npm install -g wrangler');
140
+ console.error(' - List available databases: wrangler d1 list');
141
+ console.error(' - Check database status in Cloudflare Dashboard');
142
+ console.error(' - Review wrangler.toml configuration file');
143
+ }
144
+ console.error('\nšŸ“š Additional Resources:');
145
+ console.error(' - D1 Documentation: https://developers.cloudflare.com/d1/');
146
+ console.error(' - Wrangler D1 Commands: wrangler d1 --help');
147
+ console.error(' - Framework D1 Integration Guide: docs/guides/d1-setup.md');
148
+ }
149
+
150
+ /**
151
+ * Analyze error and provide specific D1 recovery suggestions
152
+ * @param {Error} error - The error to analyze
153
+ * @returns {Object} Analysis result with suggestions
154
+ */
155
+ static analyzeD1Error(error) {
156
+ const errorMessage = error.message.toLowerCase();
157
+ const analysis = {
158
+ isD1Error: false,
159
+ category: 'unknown',
160
+ severity: 'medium',
161
+ autoFixable: false,
162
+ suggestions: []
163
+ };
164
+
165
+ // Check if this is a D1 related error
166
+ if (errorMessage.includes('d1') || errorMessage.includes('database') || errorMessage.includes('binding')) {
167
+ analysis.isD1Error = true;
168
+ }
169
+ if (errorMessage.includes("couldn't find a d1 db")) {
170
+ analysis.category = 'database_not_found';
171
+ analysis.severity = 'high';
172
+ analysis.autoFixable = true;
173
+ analysis.suggestions = ['Run automated D1 recovery: Check available databases and create/configure as needed', 'Manual fix: wrangler d1 list && wrangler d1 create <name>', 'Update wrangler.toml with correct database_id'];
174
+ } else if (errorMessage.includes('binding') && errorMessage.includes('not found')) {
175
+ analysis.category = 'binding_configuration';
176
+ analysis.severity = 'medium';
177
+ analysis.autoFixable = true;
178
+ analysis.suggestions = ['Run configuration validator to check [[d1_databases]] section', 'Verify binding name matches code expectations', 'Update database_name and database_id in wrangler.toml'];
179
+ } else if (errorMessage.includes('unauthorized') || errorMessage.includes('forbidden')) {
180
+ analysis.category = 'authentication';
181
+ analysis.severity = 'high';
182
+ analysis.autoFixable = false;
183
+ analysis.suggestions = ['Re-authenticate with Cloudflare: wrangler auth login', 'Check API token permissions include D1 access', 'Verify correct Cloudflare account is selected'];
184
+ } else if (errorMessage.includes('migration')) {
185
+ analysis.category = 'migration';
186
+ analysis.severity = 'medium';
187
+ analysis.autoFixable = false;
188
+ analysis.suggestions = ['Check migration files for syntax errors', 'Apply migrations manually: wrangler d1 migrations apply', 'Reset migrations if needed: wrangler d1 migrations list'];
189
+ }
190
+ return analysis;
191
+ }
192
+
193
+ /**
194
+ * Get step-by-step D1 troubleshooting guide
195
+ * @param {string} errorType - Type of D1 error
196
+ * @returns {Array<string>} Step-by-step guide
197
+ */
198
+ static getD1TroubleshootingSteps(errorType) {
199
+ const guides = {
200
+ database_not_found: ['1. List available databases: wrangler d1 list', '2. Check if database name in wrangler.toml matches an existing database', '3. If database doesn\'t exist, create it: wrangler d1 create <database-name>', '4. Copy the database ID from the creation output', '5. Update database_id in wrangler.toml [[d1_databases]] section', '6. Retry deployment: npm run deploy'],
201
+ binding_configuration: ['1. Open wrangler.toml and locate [[d1_databases]] section', '2. Verify binding name matches what your code expects (usually "DB")', '3. Check database_name is correct (no typos)', '4. Verify database_id is a valid UUID format', '5. Test configuration: wrangler deploy --dry-run', '6. If issues persist, validate with: wrangler d1 info <database-name>'],
202
+ authentication: ['1. Log out of current session: wrangler logout', '2. Re-authenticate: wrangler auth login', '3. Verify correct account: wrangler whoami', '4. Check API token permissions if using token authentication', '5. Ensure token has D1:Edit permissions in Cloudflare dashboard', '6. Retry the operation after successful authentication'],
203
+ migration: ['1. Check migration files in migrations/ directory', '2. Validate SQL syntax in migration files', '3. List current migration status: wrangler d1 migrations list <database>', '4. Apply pending migrations: wrangler d1 migrations apply <database>', '5. If errors occur, check migration file format and naming', '6. Consider rolling back problematic migrations if needed'],
204
+ general: ['1. Check Cloudflare account has D1 enabled and available', '2. Update wrangler to latest version: npm install -g wrangler', '3. Verify wrangler.toml file exists and has correct format', '4. Test authentication: wrangler whoami', '5. List available D1 databases: wrangler d1 list', '6. Check Cloudflare Dashboard for any service issues']
205
+ };
206
+ return guides[errorType] || guides.general;
207
+ }
208
+
96
209
  /**
97
210
  * Handle configuration errors
98
211
  * @param {Error} error - The configuration error
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Scripts Manager
3
+ *
4
+ * Manages and executes development scripts from the scripts/ directory
5
+ * Provides interactive access to generated deployment and utility scripts
6
+ */
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import { exec } from 'child_process';
11
+ import { promisify } from 'util';
12
+ const execAsync = promisify(exec);
13
+ class ScriptsManager {
14
+ constructor() {
15
+ this.scriptsDir = path.join(process.cwd(), 'scripts');
16
+ this.scripts = new Map();
17
+ }
18
+
19
+ /**
20
+ * Load available scripts from scripts/ directory
21
+ */
22
+ async loadScripts() {
23
+ if (!fs.existsSync(this.scriptsDir)) {
24
+ return;
25
+ }
26
+ const subdirs = ['database', 'deployment', 'service-management', 'testing', 'utilities'];
27
+ for (const subdir of subdirs) {
28
+ const subdirPath = path.join(this.scriptsDir, subdir);
29
+ if (fs.existsSync(subdirPath)) {
30
+ await this.loadScriptsFromDir(subdirPath, subdir);
31
+ }
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Load scripts from a specific directory
37
+ */
38
+ async loadScriptsFromDir(dirPath, category) {
39
+ const files = fs.readdirSync(dirPath).filter(f => f.endsWith('.js') || f.endsWith('.ps1') || f.endsWith('.sh'));
40
+ for (const file of files) {
41
+ const filePath = path.join(dirPath, file);
42
+ const scriptName = path.basename(file, path.extname(file));
43
+ const scriptKey = `${category}/${scriptName}`;
44
+ this.scripts.set(scriptKey, {
45
+ name: scriptName,
46
+ path: filePath,
47
+ category,
48
+ extension: path.extname(file),
49
+ description: await this.getScriptDescription(filePath)
50
+ });
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Get script description from file content or comments
56
+ */
57
+ async getScriptDescription(filePath) {
58
+ try {
59
+ const content = fs.readFileSync(filePath, 'utf8');
60
+ const lines = content.split('\n').slice(0, 10);
61
+ for (const line of lines) {
62
+ const commentMatch = line.match(/^\s*\/\*\*\s*@description\s+(.+)\s*\*\//) || line.match(/^\s*#\s*@description\s+(.+)/) || line.match(/^\s*\/\/\s*@description\s+(.+)/);
63
+ if (commentMatch) {
64
+ return commentMatch[1].trim();
65
+ }
66
+ }
67
+
68
+ // Fallback: first comment line
69
+ for (const line of lines) {
70
+ const commentMatch = line.match(/^\s*\/\*\*\s*(.+)\s*\*\//) || line.match(/^\s*#\s*(.+)/) || line.match(/^\s*\/\/\s*(.+)/);
71
+ if (commentMatch && !commentMatch[1].includes('@')) {
72
+ return commentMatch[1].trim();
73
+ }
74
+ }
75
+ } catch (error) {
76
+ // Ignore errors
77
+ }
78
+ return 'No description available';
79
+ }
80
+
81
+ /**
82
+ * Get all available scripts
83
+ */
84
+ getAllScripts() {
85
+ return Array.from(this.scripts.values());
86
+ }
87
+
88
+ /**
89
+ * Get scripts by category
90
+ */
91
+ getScriptsByCategory(category) {
92
+ return Array.from(this.scripts.values()).filter(script => script.category === category);
93
+ }
94
+
95
+ /**
96
+ * Execute a script
97
+ */
98
+ async executeScript(scriptKey, args = []) {
99
+ const script = this.scripts.get(scriptKey);
100
+ if (!script) {
101
+ throw new Error(`Script not found: ${scriptKey}`);
102
+ }
103
+ const command = this.buildCommand(script, args);
104
+ try {
105
+ const {
106
+ stdout,
107
+ stderr
108
+ } = await execAsync(command);
109
+ return {
110
+ stdout,
111
+ stderr,
112
+ success: true
113
+ };
114
+ } catch (error) {
115
+ return {
116
+ stdout: error.stdout,
117
+ stderr: error.stderr,
118
+ success: false,
119
+ error: error.message
120
+ };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Build execution command based on script type
126
+ */
127
+ buildCommand(script, args) {
128
+ const argsStr = args.join(' ');
129
+ switch (script.extension) {
130
+ case '.js':
131
+ return `node "${script.path}" ${argsStr}`;
132
+ case '.ps1':
133
+ return `powershell -ExecutionPolicy Bypass -File "${script.path}" ${argsStr}`;
134
+ case '.sh':
135
+ return `bash "${script.path}" ${argsStr}`;
136
+ default:
137
+ throw new Error(`Unsupported script type: ${script.extension}`);
138
+ }
139
+ }
140
+
141
+ /**
142
+ * List available scripts in a formatted way
143
+ */
144
+ listScripts() {
145
+ const scripts = this.getAllScripts();
146
+ const categories = {};
147
+ scripts.forEach(script => {
148
+ if (!categories[script.category]) {
149
+ categories[script.category] = [];
150
+ }
151
+ categories[script.category].push(script);
152
+ });
153
+ let output = 'Available Scripts:\n\n';
154
+ for (const [category, scripts] of Object.entries(categories)) {
155
+ output += `${category.toUpperCase()}:\n`;
156
+ scripts.forEach(script => {
157
+ output += ` ${script.name}: ${script.description}\n`;
158
+ });
159
+ output += '\n';
160
+ }
161
+ return output;
162
+ }
163
+ }
164
+
165
+ // Export singleton instance
166
+ export const scriptsManager = new ScriptsManager();
167
+ export default scriptsManager;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * UI Structures Loader
3
+ *
4
+ * Loads and provides access to UI templates from ui-structures directory
5
+ * These templates define the interactive data collection workflows
6
+ */
7
+
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ class UIStructuresLoader {
11
+ constructor() {
12
+ this.templates = new Map();
13
+ this.loaded = false;
14
+ }
15
+
16
+ /**
17
+ * Load all UI structure templates
18
+ */
19
+ async loadTemplates() {
20
+ if (this.loaded) return;
21
+ const uiStructuresDir = path.join(process.cwd(), 'ui-structures');
22
+
23
+ // Load creation templates
24
+ const creationDir = path.join(uiStructuresDir, 'creation');
25
+ if (fs.existsSync(creationDir)) {
26
+ const creationFiles = fs.readdirSync(creationDir).filter(f => f.endsWith('.json'));
27
+ for (const file of creationFiles) {
28
+ const filePath = path.join(creationDir, file);
29
+ const content = fs.readFileSync(filePath, 'utf8');
30
+ const template = JSON.parse(content);
31
+ this.templates.set(template.template.name, template);
32
+ }
33
+ }
34
+
35
+ // Load reference templates
36
+ const referenceDir = path.join(uiStructuresDir, 'reference');
37
+ if (fs.existsSync(referenceDir)) {
38
+ const referenceFiles = fs.readdirSync(referenceDir).filter(f => f.endsWith('.json'));
39
+ for (const file of referenceFiles) {
40
+ const filePath = path.join(referenceDir, file);
41
+ const content = fs.readFileSync(filePath, 'utf8');
42
+ const template = JSON.parse(content);
43
+ // Use template.name if available, otherwise filename
44
+ const name = template.template?.name || path.basename(file, '.json');
45
+ this.templates.set(name, template);
46
+ }
47
+ }
48
+ this.loaded = true;
49
+ }
50
+
51
+ /**
52
+ * Get a specific template by name
53
+ */
54
+ getTemplate(name) {
55
+ return this.templates.get(name);
56
+ }
57
+
58
+ /**
59
+ * Get all templates
60
+ */
61
+ getAllTemplates() {
62
+ return Array.from(this.templates.values());
63
+ }
64
+
65
+ /**
66
+ * Get templates by category
67
+ */
68
+ getTemplatesByCategory(category) {
69
+ return Array.from(this.templates.values()).filter(template => template.template?.category === category);
70
+ }
71
+
72
+ /**
73
+ * Get core inputs UI template
74
+ */
75
+ getCoreInputsTemplate() {
76
+ return this.getTemplate('core-inputs-ui');
77
+ }
78
+
79
+ /**
80
+ * Get smart confirmable UI template
81
+ */
82
+ getSmartConfirmableTemplate() {
83
+ return this.getTemplate('smart-confirmable-ui');
84
+ }
85
+
86
+ /**
87
+ * Get automated generation UI template
88
+ */
89
+ getAutomatedGenerationTemplate() {
90
+ return this.getTemplate('automated-generation-ui');
91
+ }
92
+
93
+ /**
94
+ * Get service manifest template
95
+ */
96
+ getServiceManifestTemplate() {
97
+ return this.getTemplate('service-manifest');
98
+ }
99
+
100
+ /**
101
+ * Get absolutely required inputs reference
102
+ */
103
+ getAbsolutelyRequiredInputs() {
104
+ return this.getTemplate('absolutely-required-inputs');
105
+ }
106
+ }
107
+
108
+ // Export singleton instance
109
+ export const uiStructuresLoader = new UIStructuresLoader();
110
+ export default uiStructuresLoader;
package/docs/README.md CHANGED
@@ -1,82 +1,35 @@
1
- # Clodo Framework Documentation
1
+ # CLODO Framework Documentation
2
2
 
3
3
  > A comprehensive framework for building Clodo-style microservices on Cloudflare Workers + D1
4
4
 
5
- ## šŸ“š Documentation Structure
5
+ ## šŸ“š Essential Documentation
6
6
 
7
- ### **Getting Started**
8
- - **[Overview](./overview.md)** - Framework philosophy and core concepts
9
- - **[Developer Guide](./guides/developer-guide.md)** - Comprehensive guide for external developers
10
- - **[Quick Start Guide](./guides/getting-started.md)** - Build your first service in 5 minutes
11
- - **[Installation](./guides/installation.md)** - Setup and prerequisites
12
-
13
- ### **Architecture**
14
- - **[Framework Architecture Overview](./FRAMEWORK-ARCHITECTURE-OVERVIEW.md)** - User-friendly architecture guide
15
- - **[Framework Architecture Analysis](./FRAMEWORK-ARCHITECTURE-ANALYSIS.md)** - Detailed technical analysis (internal)
16
- - **[Core Components](./architecture/components.md)** - Deep dive into framework modules
17
- - **[Configuration System](./architecture/configuration.md)** - Domain and feature management
18
- - **[Data Layer](./architecture/data-layer.md)** - Services, schemas, and database integration
19
- - **[Worker Integration](./architecture/worker-integration.md)** - Cloudflare Workers patterns
20
-
21
- ### **Guides**
22
- - **[Creating Services](./guides/creating-services.md)** - Service generation and templates
23
- - **[Domain Configuration](./guides/domain-configuration.md)** - Multi-tenant setup
24
- - **[Feature Management](./guides/feature-flags.md)** - Feature flags and runtime control
25
- - **[Authentication](./guides/authentication.md)** - Security patterns and implementation
26
- - **[Database Operations](./guides/database-operations.md)** - CRUD patterns and data modeling
27
-
28
- ### **Deployment**
29
- - **[Environment Setup](./deployment/environment-setup.md)** - Cloudflare and local development
30
- - **[Deployment Guide](./deployment/deployment-guide.md)** - Production deployment strategies
31
- - **[CI/CD Integration](./deployment/ci-cd.md)** - Automated deployment pipelines
32
- - **[Monitoring](./deployment/monitoring.md)** - Observability and debugging
33
-
34
- ### **API Reference**
35
- - **[Core Classes](./api/core-classes.md)** - Framework class references
36
- - **[Configuration API](./api/configuration.md)** - Domain and feature APIs
37
- - **[Service API](./api/services.md)** - Data service interfaces
38
- - **[Worker Helpers](./api/worker-helpers.md)** - Cloudflare Worker utilities
39
- - **[CLI Tools](./api/cli-tools.md)** - Command-line interface documentation
7
+ This folder contains **only essential, public-facing documentation** that is distributed with the npm package. For comprehensive documentation, examples, and guides, visit the [GitHub repository](https://github.com/tamylaa/clodo-framework).
40
8
 
41
- ### **Examples**
42
- - **[Basic CRUD Service](./examples/basic-crud.md)** - Simple data service example
43
- - **[Multi-Tenant SaaS](./examples/multi-tenant-saas.md)** - Complex multi-domain setup
44
- - **[Authentication Service](./examples/auth-service.md)** - JWT-based authentication
45
- - **[API Gateway](./examples/api-gateway.md)** - Service orchestration patterns
9
+ ### **Core Documentation**
10
+ - **[Overview](./overview.md)** - Framework philosophy and core concepts
11
+ - **[Security](./SECURITY.md)** - Security considerations and best practices
12
+ - **[API Reference](./api-reference.md)** - Complete API documentation
46
13
 
47
- ### **Decision Framework**
48
- - **[When to Use](./decision-framework.md)** - Use cases and anti-patterns
49
- - **[Alternatives](./alternatives.md)** - Other approaches and trade-offs
50
- - **[Migration Guide](./migration-guide.md)** - Moving to/from the framework
14
+ ### **Package Contents**
15
+ This documentation is included in the npm package distribution to provide essential information for developers using the framework.
51
16
 
52
- ## šŸš€ Quick Navigation
17
+ ## šŸ†˜ Getting Help
53
18
 
54
- | I want to... | Go to |
55
- |--------------|--------|
56
- | **Understand the framework** | [Overview](./overview.md) |
57
- | **Learn comprehensive usage** | [Developer Guide](./guides/developer-guide.md) |
58
- | **Build my first service** | [Getting Started](./guides/getting-started.md) |
59
- | **Configure domains** | [Domain Configuration](./guides/domain-configuration.md) |
60
- | **Deploy to production** | [Deployment Guide](./deployment/deployment-guide.md) |
61
- | **Find API documentation** | [API Reference](./api/README.md) |
62
- | **See real examples** | [Examples](./examples/README.md) |
63
- | **Decide if this is right for me** | [Decision Framework](./decision-framework.md) |
19
+ - **Framework Issues**: [GitHub Issues](https://github.com/tamylaa/clodo-framework/issues)
20
+ - **Security Concerns**: Review [Security Documentation](./SECURITY.md)
21
+ - **API Questions**: See [API Reference](./api-reference.md)
64
22
 
65
- ## šŸ†˜ Getting Help
23
+ ## šŸ“¦ Package Information
66
24
 
67
- - **Documentation Issues**: Open an issue in the repository
68
- - **Framework Bugs**: Report via GitHub Issues
69
- - **Questions**: Check existing issues or create a new discussion
70
- - **Contributing**: See [Contributing Guide](../CONTRIBUTING.md)
25
+ - **Version**: 1.0.0
26
+ - **License**: See repository LICENSE file
27
+ - **Repository**: [GitHub](https://github.com/tamylaa/clodo-framework)
71
28
 
72
- ## šŸ”— External Resources
29
+ ---
73
30
 
74
- - **[Cloudflare Workers Documentation](https://developers.cloudflare.com/workers/)**
75
- - **[D1 Database Documentation](https://developers.cloudflare.com/d1/)**
76
- - **[Wrangler CLI Documentation](https://developers.cloudflare.com/workers/wrangler/)**
31
+ **For comprehensive documentation, visit the [GitHub repository](https://github.com/tamylaa/clodo-framework).**
77
32
 
78
33
  ---
79
34
 
80
- **Framework Version**: 1.0.0
81
- **Last Updated**: September 27, 2025
82
- **Cloudflare Workers Runtime**: Compatible with 2023-05-18 and later
35
+ **For comprehensive documentation, visit the [GitHub repository](https://github.com/tamylaa/clodo-framework).**