hola-server 1.0.10 → 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.
Files changed (83) hide show
  1. package/README.md +196 -1
  2. package/core/array.js +79 -142
  3. package/core/bash.js +208 -259
  4. package/core/chart.js +26 -16
  5. package/core/cron.js +14 -3
  6. package/core/date.js +15 -44
  7. package/core/encrypt.js +19 -9
  8. package/core/file.js +42 -29
  9. package/core/lhs.js +32 -6
  10. package/core/meta.js +213 -289
  11. package/core/msg.js +20 -7
  12. package/core/number.js +105 -103
  13. package/core/obj.js +15 -12
  14. package/core/random.js +9 -6
  15. package/core/role.js +69 -77
  16. package/core/thread.js +12 -2
  17. package/core/type.js +300 -261
  18. package/core/url.js +20 -12
  19. package/core/validate.js +29 -26
  20. package/db/db.js +297 -227
  21. package/db/entity.js +631 -963
  22. package/db/gridfs.js +120 -166
  23. package/design/add_default_field_attr.md +56 -0
  24. package/http/context.js +22 -8
  25. package/http/cors.js +25 -8
  26. package/http/error.js +27 -9
  27. package/http/express.js +70 -41
  28. package/http/params.js +70 -42
  29. package/http/router.js +51 -40
  30. package/http/session.js +59 -36
  31. package/index.js +85 -9
  32. package/package.json +2 -2
  33. package/router/clone.js +28 -36
  34. package/router/create.js +21 -26
  35. package/router/delete.js +24 -28
  36. package/router/read.js +137 -123
  37. package/router/update.js +38 -56
  38. package/setting.js +22 -6
  39. package/skills/array.md +155 -0
  40. package/skills/bash.md +91 -0
  41. package/skills/chart.md +54 -0
  42. package/skills/code.md +422 -0
  43. package/skills/context.md +177 -0
  44. package/skills/date.md +58 -0
  45. package/skills/express.md +255 -0
  46. package/skills/file.md +60 -0
  47. package/skills/lhs.md +54 -0
  48. package/skills/meta.md +1023 -0
  49. package/skills/msg.md +30 -0
  50. package/skills/number.md +88 -0
  51. package/skills/obj.md +36 -0
  52. package/skills/params.md +206 -0
  53. package/skills/random.md +22 -0
  54. package/skills/role.md +59 -0
  55. package/skills/session.md +281 -0
  56. package/skills/storage.md +743 -0
  57. package/skills/thread.md +22 -0
  58. package/skills/type.md +547 -0
  59. package/skills/url.md +34 -0
  60. package/skills/validate.md +48 -0
  61. package/test/cleanup/close-db.js +5 -0
  62. package/test/core/array.js +226 -0
  63. package/test/core/chart.js +51 -0
  64. package/test/core/file.js +59 -0
  65. package/test/core/lhs.js +44 -0
  66. package/test/core/number.js +167 -12
  67. package/test/core/obj.js +47 -0
  68. package/test/core/random.js +24 -0
  69. package/test/core/thread.js +20 -0
  70. package/test/core/type.js +216 -0
  71. package/test/core/validate.js +67 -0
  72. package/test/db/db-ops.js +99 -0
  73. package/test/db/pipe_test.txt +0 -0
  74. package/test/db/test_case_design.md +528 -0
  75. package/test/db/test_db_class.js +613 -0
  76. package/test/db/test_entity_class.js +414 -0
  77. package/test/db/test_gridfs_class.js +234 -0
  78. package/test/entity/create.js +1 -1
  79. package/test/entity/delete-mixed.js +156 -0
  80. package/test/entity/ref-filter.js +63 -0
  81. package/tool/gen_i18n.js +55 -21
  82. package/test/crud/router.js +0 -99
  83. package/test/router/user.js +0 -17
@@ -0,0 +1,255 @@
1
+ # Express Server Initialization Skill
2
+
3
+ ## Overview
4
+
5
+ The `hola-server/http/express.js` module provides the main entry point for initializing an Express server with all Hola framework middleware and configurations.
6
+
7
+ ## Importing
8
+
9
+ ```javascript
10
+ const { init_express_server } = require("hola-server/http/express");
11
+ ```
12
+
13
+ ## API Reference
14
+
15
+ ### `init_express_server(base_dir, port_attr, callback)`
16
+
17
+ Initializes and starts an Express server with the Hola framework stack.
18
+
19
+ **Parameters:**
20
+ - `base_dir` (string): Base directory containing router files (e.g., `__dirname + "/router"`)
21
+ - `port_attr` (string): Property name in settings.server for the port (e.g., `"port"` or `"api_port"`)
22
+ - `callback` (Function, optional): Async function called after server starts
23
+
24
+ **Returns:** Express app instance
25
+
26
+ **Throws:** Error if server settings are invalid or port not found
27
+
28
+ ## Initialization Flow
29
+
30
+ When you call `init_express_server()`, the following happens in order:
31
+
32
+ 1. **CORS Configuration**: `init_cors()` - Sets up cross-origin resource sharing
33
+ 2. **Body Parser**: Configures JSON and URL-encoded body parsing with optional size limits
34
+ 3. **Session**: `init_session()` - Sets up session middleware with MongoDB store
35
+ 4. **Authentication**: Creates middleware to check session and excluded URLs
36
+ 5. **Context**: Sets up AsyncLocalStorage for request context
37
+ 6. **Routers**: `init_router_dirs()` - Auto-loads all router files from base directory
38
+ 7. **Error Handling**: `handle_exception()` - Sets up global error handler
39
+ 8. **Server Start**: Listens on specified port and invokes callback
40
+
41
+ ## Basic Usage
42
+
43
+ ```javascript
44
+ const { init_express_server } = require("hola-server/http/express");
45
+
46
+ // Start server on port from settings.server.port
47
+ init_express_server(__dirname + "/router", "port", async () => {
48
+ console.log("Server started successfully");
49
+ });
50
+ ```
51
+
52
+ ## Configuration
53
+
54
+ The server relies on settings from `get_settings()`. Required settings structure:
55
+
56
+ ```javascript
57
+ // settings.json
58
+ {
59
+ "server": {
60
+ "port": 3000,
61
+ "check_user": true, // Enable authentication
62
+ "exclude_urls": [ // URLs to skip auth
63
+ "/api/login",
64
+ "/api/register",
65
+ "/public/.*"
66
+ ],
67
+ "threshold": {
68
+ "body_limit": "10mb" // Optional body size limit
69
+ },
70
+ "keep_session": true,
71
+ "session": {
72
+ "secret": "your-secret-key",
73
+ "cookie_max_age": 86400000 // 24 hours
74
+ }
75
+ },
76
+ "mongo": {
77
+ "url": "mongodb://localhost:27017/mydb"
78
+ }
79
+ }
80
+ ```
81
+
82
+ ## Advanced Usage
83
+
84
+ ### Multiple Servers (API + Admin)
85
+
86
+ ```javascript
87
+ // Start API server
88
+ init_express_server(__dirname + "/api_router", "api_port", async () => {
89
+ console.log("API server started on port from settings.server.api_port");
90
+ });
91
+
92
+ // Start admin server
93
+ init_express_server(__dirname + "/admin_router", "admin_port", async () => {
94
+ console.log("Admin server started on port from settings.server.admin_port");
95
+ });
96
+ ```
97
+
98
+ ### With Database Connection
99
+
100
+ ```javascript
101
+ const { init_express_server } = require("hola-server/http/express");
102
+ const { connect_db } = require("hola-server/db/db");
103
+
104
+ init_express_server(__dirname + "/router", "port", async () => {
105
+ await connect_db();
106
+ console.log("Server and database ready");
107
+ });
108
+ ```
109
+
110
+ ### With Custom Initialization
111
+
112
+ ```javascript
113
+ init_express_server(__dirname + "/router", "port", async () => {
114
+ // Connect to database
115
+ await connect_db();
116
+
117
+ // Load initial data
118
+ await seed_database();
119
+
120
+ // Start background jobs
121
+ start_cron_jobs();
122
+
123
+ console.log("Application fully initialized");
124
+ });
125
+ ```
126
+
127
+ ## Authentication Configuration
128
+
129
+ ### Enable Authentication
130
+
131
+ ```javascript
132
+ // settings.json
133
+ {
134
+ "server": {
135
+ "check_user": true
136
+ }
137
+ }
138
+ ```
139
+
140
+ When `check_user` is true:
141
+ - All requests require valid session with user
142
+ - Returns `{ code: NO_SESSION, err: "authentication required" }` if no session
143
+ - Excluded URLs bypass this check
144
+
145
+ ### Exclude URLs from Authentication
146
+
147
+ ```javascript
148
+ {
149
+ "server": {
150
+ "check_user": true,
151
+ "exclude_urls": [
152
+ "/api/login",
153
+ "/api/register",
154
+ "/api/public/.*", // Regex pattern
155
+ "/health"
156
+ ]
157
+ }
158
+ }
159
+ ```
160
+
161
+ Patterns are tested as case-insensitive regular expressions against `req.originalUrl`.
162
+
163
+ ## Body Size Limits
164
+
165
+ ```javascript
166
+ {
167
+ "server": {
168
+ "threshold": {
169
+ "body_limit": "50mb" // For file uploads
170
+ }
171
+ }
172
+ }
173
+ ```
174
+
175
+ If not specified, uses Express defaults (100kb for JSON).
176
+
177
+ ## Session Configuration
178
+
179
+ ### Enable Sessions
180
+
181
+ ```javascript
182
+ {
183
+ "server": {
184
+ "keep_session": true,
185
+ "session": {
186
+ "secret": "change-this-in-production",
187
+ "cookie_max_age": 86400000 // 1 day in milliseconds
188
+ }
189
+ }
190
+ }
191
+ ```
192
+
193
+ ### Disable Sessions
194
+
195
+ ```javascript
196
+ {
197
+ "server": {
198
+ "keep_session": false // Or omit keep_session
199
+ }
200
+ }
201
+ ```
202
+
203
+ ## Complete Example
204
+
205
+ ```javascript
206
+ // server/main.js
207
+ const { init_express_server } = require("hola-server/http/express");
208
+ const { connect_db } = require("hola-server/db/db");
209
+ const { validate_all_metas } = require("hola-server/core/meta");
210
+
211
+ init_express_server(__dirname + "/router", "port", async () => {
212
+ try {
213
+ // Connect to MongoDB
214
+ await connect_db();
215
+ console.log("✓ Database connected");
216
+
217
+ // Validate all entity meta definitions
218
+ validate_all_metas();
219
+ console.log("✓ All meta definitions validated");
220
+
221
+ console.log("✓ Server ready on port", process.env.PORT || 3000);
222
+ } catch (error) {
223
+ console.error("Server initialization failed:", error);
224
+ process.exit(1);
225
+ }
226
+ });
227
+ ```
228
+
229
+ ## Error Handling
230
+
231
+ The server automatically handles:
232
+ - Invalid settings (throws error before starting)
233
+ - Missing port configuration (throws error)
234
+ - Duplicate initialization (returns existing app instance)
235
+ - Unhandled route errors (via `handle_exception`)
236
+
237
+ ## Best Practices
238
+
239
+ 1. **Call once per server**: `init_express_server()` should be called once per port/app instance.
240
+
241
+ 2. **Use callback for initialization**: Put database connections and setup in the callback.
242
+
243
+ 3. **Validate early**: Run meta validation in the callback before accepting requests.
244
+
245
+ 4. **Environment-specific configs**: Use different settings files for dev/prod.
246
+
247
+ 5. **Graceful shutdown**: Handle `SIGTERM` and `SIGINT` to close connections properly.
248
+
249
+ ```javascript
250
+ process.on('SIGTERM', async () => {
251
+ console.log('SIGTERM received, shutting down gracefully');
252
+ // Close database connections, etc.
253
+ process.exit(0);
254
+ });
255
+ ```
package/skills/file.md ADDED
@@ -0,0 +1,60 @@
1
+ # File Utilities Skill
2
+
3
+ ## Overview
4
+
5
+ The `hola-server/core/file.js` module provides helpers for file path manipulation, file system checks, and reading from zip archives.
6
+
7
+ ## Importing
8
+
9
+ ```javascript
10
+ const {
11
+ file_extension, file_prefix, is_file_exist, get_file_size,
12
+ read_from_zip_by_extension, read_from_zip_by_prefix
13
+ } = require("hola-server/core/file");
14
+ ```
15
+
16
+ ## API Reference
17
+
18
+ ### Path & File System
19
+
20
+ #### `file_extension(file_name)`
21
+ Gets extension from filename (without dot).
22
+ - **param**: `file_name` (string)
23
+ - **returns**: `string`
24
+
25
+ ```javascript
26
+ file_extension("image.png"); // "png"
27
+ ```
28
+
29
+ #### `file_prefix(file_name)`
30
+ Gets filename without extension.
31
+ - **param**: `file_name` (string)
32
+ - **returns**: `string`
33
+
34
+ ```javascript
35
+ file_prefix("data.json"); // "data"
36
+ ```
37
+
38
+ #### `is_file_exist(path)`
39
+ Synchronous check if file exists.
40
+ - **param**: `path` (string)
41
+ - **returns**: `boolean`
42
+
43
+ #### `get_file_size(path)`
44
+ Asynchronously gets file size in bytes.
45
+ - **param**: `path` (string)
46
+ - **returns**: `Promise<number>`
47
+
48
+ ### Zip Archive Handling
49
+
50
+ #### `read_from_zip_by_extension(path, extension)`
51
+ Reads entries from a zip file matching the extension.
52
+ - **param**: `path` (string) - Path to zip file.
53
+ - **param**: `extension` (string) - Extension to filter (e.g., "json").
54
+ - **returns**: `Promise<Object[]>` - Array of unzipper file entries.
55
+
56
+ #### `read_from_zip_by_prefix(path, prefix)`
57
+ Reads entries from a zip file matching the filename prefix.
58
+ - **param**: `path` (string)
59
+ - **param**: `prefix` (string)
60
+ - **returns**: `Promise<Object[]>`
package/skills/lhs.md ADDED
@@ -0,0 +1,54 @@
1
+ # Template & VM Utilities Skill (LHS)
2
+
3
+ ## Overview
4
+
5
+ The `hola-server/core/lhs.js` module provides utilities for safe template execution and string interpolation using Node.js's `vm` module. It creates a sandboxed context with specific helper functions.
6
+
7
+ ## Importing
8
+
9
+ ```javascript
10
+ const {
11
+ get_context, run_in_context,
12
+ verify_template, execute_template
13
+ } = require("hola-server/core/lhs");
14
+ ```
15
+
16
+ ## API Reference
17
+
18
+ ### `get_context()`
19
+ Returns a default context object containing number utility functions (`range`, `scale`, `space`).
20
+ - **returns**: `Object` - Context with helpers.
21
+
22
+ ### `run_in_context(code, ctx)`
23
+ Executes JavaScript code within a provided context object.
24
+ - **param**: `code` (string) - JS code to run.
25
+ - **param**: `ctx` (Object) - Context object (modified by execution).
26
+ - **returns**: `Object` - The modified context.
27
+
28
+ ```javascript
29
+ const ctx = { x: 10 };
30
+ run_in_context("y = x * 2", ctx);
31
+ // ctx.y is now 20
32
+ ```
33
+
34
+ ### `verify_template(template, knob)`
35
+ Verifies if a template string acts as valid JavaScript template literal when executed.
36
+ - **param**: `template` (string) - Template string (content inside backticks).
37
+ - **param**: `knob` (Object) - Variables available to the template.
38
+ - **returns**: `string|null` - Error message if invalid, `null` if valid.
39
+
40
+ ```javascript
41
+ const err = verify_template("Hello ${name}", { name: "World" });
42
+ // err is null (valid)
43
+ ```
44
+
45
+ ### `execute_template(template, knob)`
46
+ Executes a template string using the provided variables.
47
+ - **param**: `template` (string) - Template content (without backticks).
48
+ - **param**: `knob` (Object) - Context variables.
49
+ - **returns**: `string` - interpolated result.
50
+
51
+ ```javascript
52
+ const result = execute_template("Value: ${val * 2}", { val: 5 });
53
+ // result: "Value: 10"
54
+ ```