jsgui3-server 0.0.138 → 0.0.140

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 (57) hide show
  1. package/AGENTS.md +87 -0
  2. package/README.md +12 -0
  3. package/docs/GUIDE_TO_AGENTIC_WORKFLOWS_BY_GROK.md +19 -0
  4. package/docs/advanced-usage-examples.md +1360 -0
  5. package/docs/agent-development-guide.md +386 -0
  6. package/docs/api-reference.md +916 -0
  7. package/docs/broken-functionality-tracker.md +285 -0
  8. package/docs/bundling-system-deep-dive.md +525 -0
  9. package/docs/cli-reference.md +393 -0
  10. package/docs/comprehensive-documentation.md +1403 -0
  11. package/docs/configuration-reference.md +808 -0
  12. package/docs/controls-development.md +859 -0
  13. package/docs/documentation-review/CURRENT_REVIEW.md +95 -0
  14. package/docs/function-publishers-json-apis.md +847 -0
  15. package/docs/getting-started-with-json.md +518 -0
  16. package/docs/minification-compression-sourcemaps-status.md +482 -0
  17. package/docs/minification-compression-sourcemaps-test-results.md +205 -0
  18. package/docs/publishers-guide.md +313 -0
  19. package/docs/resources-guide.md +615 -0
  20. package/docs/serve-helpers.md +406 -0
  21. package/docs/simple-server-api-design.md +13 -0
  22. package/docs/system-architecture.md +275 -0
  23. package/docs/troubleshooting.md +698 -0
  24. package/examples/json/README.md +115 -0
  25. package/examples/json/basic-api/README.md +345 -0
  26. package/examples/json/basic-api/server.js +199 -0
  27. package/examples/json/simple-api/README.md +125 -0
  28. package/examples/json/simple-api/diagnostic-report.json +73 -0
  29. package/examples/json/simple-api/diagnostic-test.js +433 -0
  30. package/examples/json/simple-api/server-debug.md +58 -0
  31. package/examples/json/simple-api/server.js +91 -0
  32. package/examples/json/simple-api/test.js +215 -0
  33. package/http/responders/static/Static_Route_HTTP_Responder.js +1 -2
  34. package/package.json +19 -8
  35. package/publishers/helpers/assigners/static-compressed-response-buffers/Single_Control_Webpage_Server_Static_Compressed_Response_Buffers_Assigner.js +65 -12
  36. package/publishers/helpers/preparers/static/bundle/Static_Routes_Responses_Webpage_Bundle_Preparer.js +6 -1
  37. package/publishers/http-function-publisher.js +59 -38
  38. package/publishers/http-webpage-publisher.js +48 -1
  39. package/resources/processors/bundlers/js/esbuild/Advanced_JS_Bundler_Using_ESBuild.js +38 -146
  40. package/resources/processors/bundlers/js/esbuild/Core_JS_Non_Minifying_Bundler_Using_ESBuild.js +54 -5
  41. package/resources/processors/bundlers/js/esbuild/Core_JS_Single_File_Minifying_Bundler_Using_ESBuild.js +36 -4
  42. package/serve-factory.js +36 -9
  43. package/server.js +10 -4
  44. package/test-report.json +0 -0
  45. package/tests/README.md +250 -0
  46. package/tests/assigners.test.js +316 -0
  47. package/tests/bundlers.test.js +329 -0
  48. package/tests/configuration-validation.test.js +530 -0
  49. package/tests/content-analysis.test.js +641 -0
  50. package/tests/end-to-end.test.js +496 -0
  51. package/tests/error-handling.test.js +746 -0
  52. package/tests/performance.test.js +653 -0
  53. package/tests/publishers.test.js +395 -0
  54. package/tests/temp_invalid.js +7 -0
  55. package/tests/temp_invalid_utf8.js +1 -0
  56. package/tests/temp_malformed.js +10 -0
  57. package/tests/test-runner.js +261 -0
@@ -0,0 +1,518 @@
1
+ # Getting Started with JSON APIs in JSGUI3 Server
2
+
3
+ **Version 0.0.1 - Provisional Guide**
4
+
5
+ *This guide is provisional and intended to be helpful, but needs verification. It documents the current understanding of JSON API functionality in JSGUI3 Server based on code analysis. Please verify examples work in your environment and report any discrepancies.*
6
+
7
+ ## When to Read
8
+
9
+ This guide is for developers who want to create JSON APIs with JSGUI3 Server. Read this when:
10
+ - You want to build backend services that serve JSON data
11
+ - You're creating REST APIs for frontend applications
12
+ - You need to understand how JSGUI3 Server handles HTTP requests and responses
13
+ - You're migrating from other web frameworks to JSGUI3 Server
14
+
15
+ **Important:** This is version 0.0.1 of this guide. It may contain inaccuracies or incomplete information. Please verify all examples and report issues.
16
+
17
+ ## Quick Start: Your First JSON API
18
+
19
+ ### Minimal JSON API Server
20
+
21
+ ```javascript
22
+ // server.js
23
+ const Server = require('jsgui3-server');
24
+
25
+ Server.serve({
26
+ // No UI control needed for pure API server
27
+ // ctrl: MyControl, // commented out
28
+
29
+ // Define API endpoints
30
+ api: {
31
+ 'hello': () => ({ message: 'Hello, World!', timestamp: new Date() }),
32
+ 'echo': (data) => ({ received: data, echoed: true })
33
+ },
34
+
35
+ port: 3000
36
+ });
37
+ ```
38
+
39
+ **Start the server:**
40
+ ```bash
41
+ node server.js
42
+ ```
43
+
44
+ **Test the API:**
45
+ ```bash
46
+ # GET request (no body)
47
+ curl http://localhost:3000/api/hello
48
+ # Response: {"message":"Hello, World!","timestamp":"2025-11-02T01:00:00.000Z"}
49
+
50
+ # POST request with JSON body
51
+ curl -X POST http://localhost:3000/api/echo \
52
+ -H "Content-Type: application/json" \
53
+ -d '{"name":"Alice","age":30}'
54
+ # Response: {"received":{"name":"Alice","age":30},"echoed":true}
55
+ ```
56
+
57
+ ## How JSON APIs Work in JSGUI3 Server
58
+
59
+ ### The `api` Configuration Option
60
+
61
+ The `api` option in `Server.serve()` automatically creates HTTP endpoints:
62
+
63
+ ```javascript
64
+ Server.serve({
65
+ api: {
66
+ // This creates: GET/POST /api/endpoint-name
67
+ 'endpoint-name': (requestData) => {
68
+ // Your function logic here
69
+ return responseData;
70
+ }
71
+ }
72
+ });
73
+ ```
74
+
75
+ ### Automatic Features
76
+
77
+ 1. **Route Prefixing**: All API endpoints automatically get `/api/` prefix
78
+ 2. **HTTP Methods**: Both GET and POST requests are supported
79
+ 3. **Content-Type Handling**: Automatic JSON parsing and serialization
80
+ 4. **Promise Support**: Async functions work automatically
81
+ 5. **Error Handling**: Exceptions become JSON error responses
82
+
83
+ ## API Endpoint Examples
84
+
85
+ ### Simple Data Endpoints
86
+
87
+ ```javascript
88
+ Server.serve({
89
+ api: {
90
+ // Static data
91
+ 'version': () => ({ version: '1.0.0', api: 'json' }),
92
+
93
+ // Dynamic data
94
+ 'time': () => ({
95
+ serverTime: new Date().toISOString(),
96
+ uptime: process.uptime()
97
+ }),
98
+
99
+ // Random data
100
+ 'random': () => ({
101
+ number: Math.random(),
102
+ dice: Math.floor(Math.random() * 6) + 1
103
+ })
104
+ },
105
+ port: 3000
106
+ });
107
+ ```
108
+
109
+ ### Working with Request Data
110
+
111
+ ```javascript
112
+ Server.serve({
113
+ api: {
114
+ // Access request body data
115
+ 'greet': (data) => {
116
+ const name = data.name || 'Anonymous';
117
+ return { greeting: `Hello, ${name}!` };
118
+ },
119
+
120
+ // Process form data
121
+ 'calculate': (data) => {
122
+ const { a, b, operation } = data;
123
+ let result;
124
+
125
+ switch (operation) {
126
+ case 'add': result = a + b; break;
127
+ case 'subtract': result = a - b; break;
128
+ case 'multiply': result = a * b; break;
129
+ case 'divide': result = a / b; break;
130
+ default: throw new Error('Unknown operation');
131
+ }
132
+
133
+ return { a, b, operation, result };
134
+ },
135
+
136
+ // Handle arrays
137
+ 'process-list': (data) => {
138
+ const numbers = data.numbers || [];
139
+ return {
140
+ original: numbers,
141
+ sum: numbers.reduce((a, b) => a + b, 0),
142
+ average: numbers.length > 0 ? numbers.reduce((a, b) => a + b, 0) / numbers.length : 0,
143
+ sorted: [...numbers].sort((a, b) => a - b)
144
+ };
145
+ }
146
+ },
147
+ port: 3000
148
+ });
149
+ ```
150
+
151
+ ### Async Operations and External APIs
152
+
153
+ ```javascript
154
+ Server.serve({
155
+ api: {
156
+ // Simulate async operation
157
+ 'delayed-response': async (data) => {
158
+ const delay = data.delay || 1000;
159
+
160
+ // Simulate async work
161
+ await new Promise(resolve => setTimeout(resolve, delay));
162
+
163
+ return {
164
+ message: 'Response after delay',
165
+ delay: delay,
166
+ timestamp: new Date()
167
+ };
168
+ },
169
+
170
+ // External API call (simulated)
171
+ 'weather': async (data) => {
172
+ const city = data.city || 'London';
173
+
174
+ // In real app, call actual weather API
175
+ // const response = await fetch(`https://api.weather.com/${city}`);
176
+ // const weather = await response.json();
177
+
178
+ // Simulated response
179
+ const mockWeather = {
180
+ city: city,
181
+ temperature: Math.floor(Math.random() * 30) + 5,
182
+ condition: ['Sunny', 'Cloudy', 'Rainy'][Math.floor(Math.random() * 3)],
183
+ humidity: Math.floor(Math.random() * 100)
184
+ };
185
+
186
+ return mockWeather;
187
+ }
188
+ },
189
+ port: 3000
190
+ });
191
+ ```
192
+
193
+ ## Error Handling
194
+
195
+ ### Automatic Error Responses
196
+
197
+ ```javascript
198
+ Server.serve({
199
+ api: {
200
+ 'safe-divide': (data) => {
201
+ const { a, b } = data;
202
+
203
+ if (typeof a !== 'number' || typeof b !== 'number') {
204
+ throw new Error('Both a and b must be numbers');
205
+ }
206
+
207
+ if (b === 0) {
208
+ throw new Error('Division by zero');
209
+ }
210
+
211
+ return { result: a / b };
212
+ },
213
+
214
+ 'validate-user': (data) => {
215
+ const { name, email, age } = data;
216
+
217
+ if (!name || name.length < 2) {
218
+ throw new Error('Name must be at least 2 characters');
219
+ }
220
+
221
+ if (!email || !email.includes('@')) {
222
+ throw new Error('Valid email required');
223
+ }
224
+
225
+ if (!age || age < 0 || age > 150) {
226
+ throw new Error('Age must be between 0 and 150');
227
+ }
228
+
229
+ return { valid: true, user: { name, email, age } };
230
+ }
231
+ },
232
+ port: 3000
233
+ });
234
+ ```
235
+
236
+ **Error response format:**
237
+ ```json
238
+ {
239
+ "error": "Division by zero"
240
+ }
241
+ ```
242
+
243
+ ## Database Integration Example
244
+
245
+ ```javascript
246
+ // In-memory "database" for demonstration
247
+ const users = [
248
+ { id: 1, name: 'Alice', email: 'alice@example.com', age: 25 },
249
+ { id: 2, name: 'Bob', email: 'bob@example.com', age: 30 }
250
+ ];
251
+
252
+ let nextId = 3;
253
+
254
+ Server.serve({
255
+ api: {
256
+ // GET /api/users - List all users
257
+ 'users': () => users,
258
+
259
+ // GET /api/user?id=1 - Get specific user
260
+ 'user': (data) => {
261
+ const id = parseInt(data.id);
262
+ const user = users.find(u => u.id === id);
263
+
264
+ if (!user) {
265
+ throw new Error('User not found');
266
+ }
267
+
268
+ return user;
269
+ },
270
+
271
+ // POST /api/create-user - Create new user
272
+ 'create-user': (data) => {
273
+ const { name, email, age } = data;
274
+
275
+ if (!name || !email) {
276
+ throw new Error('Name and email are required');
277
+ }
278
+
279
+ const newUser = {
280
+ id: nextId++,
281
+ name,
282
+ email,
283
+ age: age || null
284
+ };
285
+
286
+ users.push(newUser);
287
+ return { success: true, user: newUser };
288
+ },
289
+
290
+ // POST /api/update-user - Update user
291
+ 'update-user': (data) => {
292
+ const { id, ...updates } = data;
293
+ const userIndex = users.findIndex(u => u.id === parseInt(id));
294
+
295
+ if (userIndex === -1) {
296
+ throw new Error('User not found');
297
+ }
298
+
299
+ // Update user
300
+ Object.assign(users[userIndex], updates);
301
+
302
+ return { success: true, user: users[userIndex] };
303
+ },
304
+
305
+ // POST /api/delete-user - Delete user
306
+ 'delete-user': (data) => {
307
+ const id = parseInt(data.id);
308
+ const userIndex = users.findIndex(u => u.id === id);
309
+
310
+ if (userIndex === -1) {
311
+ throw new Error('User not found');
312
+ }
313
+
314
+ const deletedUser = users.splice(userIndex, 1)[0];
315
+ return { success: true, deletedUser };
316
+ }
317
+ },
318
+ port: 3000
319
+ });
320
+ ```
321
+
322
+ ## Testing Your JSON APIs
323
+
324
+ ### Using curl
325
+
326
+ ```bash
327
+ # Test GET endpoint
328
+ curl http://localhost:3000/api/users
329
+
330
+ # Test POST with JSON data
331
+ curl -X POST http://localhost:3000/api/create-user \
332
+ -H "Content-Type: application/json" \
333
+ -d '{"name":"Charlie","email":"charlie@example.com","age":35}'
334
+
335
+ # Test error handling
336
+ curl -X POST http://localhost:3000/api/safe-divide \
337
+ -H "Content-Type: application/json" \
338
+ -d '{"a":10,"b":0}'
339
+ ```
340
+
341
+ ### Using JavaScript (Browser or Node.js)
342
+
343
+ ```javascript
344
+ // Test from browser console or Node.js
345
+ async function testAPI() {
346
+ try {
347
+ // GET request
348
+ const users = await fetch('http://localhost:3000/api/users')
349
+ .then(r => r.json());
350
+ console.log('Users:', users);
351
+
352
+ // POST request
353
+ const newUser = await fetch('http://localhost:3000/api/create-user', {
354
+ method: 'POST',
355
+ headers: { 'Content-Type': 'application/json' },
356
+ body: JSON.stringify({
357
+ name: 'Diana',
358
+ email: 'diana@example.com',
359
+ age: 28
360
+ })
361
+ }).then(r => r.json());
362
+ console.log('New user:', newUser);
363
+
364
+ } catch (error) {
365
+ console.error('API test failed:', error);
366
+ }
367
+ }
368
+
369
+ testAPI();
370
+ ```
371
+
372
+ ## Advanced Patterns
373
+
374
+ ### Combining APIs with UI Controls
375
+
376
+ ```javascript
377
+ // server.js - API + UI
378
+ const Server = require('jsgui3-server');
379
+ const { controls } = require('./client');
380
+
381
+ Server.serve({
382
+ // Serve UI control
383
+ ctrl: controls.UserDashboard,
384
+
385
+ // Provide API for the UI
386
+ api: {
387
+ 'users': () => users,
388
+ 'create-user': (data) => {
389
+ // ... create user logic
390
+ },
391
+ 'analytics': () => ({
392
+ totalUsers: users.length,
393
+ activeUsers: users.filter(u => u.active).length
394
+ })
395
+ },
396
+
397
+ port: 3000
398
+ });
399
+ ```
400
+
401
+ ### Middleware and Authentication
402
+
403
+ ```javascript
404
+ // Basic authentication middleware concept
405
+ function authMiddleware(req, res, next) {
406
+ const auth = req.headers.authorization;
407
+
408
+ if (!auth || !auth.startsWith('Bearer ')) {
409
+ res.writeHead(401, { 'Content-Type': 'application/json' });
410
+ res.end(JSON.stringify({ error: 'No token provided' }));
411
+ return;
412
+ }
413
+
414
+ // In real app, verify JWT token
415
+ const token = auth.substring(7);
416
+ if (token !== 'valid-token') {
417
+ res.writeHead(401, { 'Content-Type': 'application/json' });
418
+ res.end(JSON.stringify({ error: 'Invalid token' }));
419
+ return;
420
+ }
421
+
422
+ // Token valid, proceed
423
+ next();
424
+ }
425
+
426
+ Server.serve({
427
+ api: {
428
+ 'protected-data': (data) => ({ secret: 'This requires authentication' }),
429
+ 'public-data': () => ({ message: 'This is public' })
430
+ },
431
+
432
+ // Note: Middleware integration may need verification
433
+ middleware: [authMiddleware],
434
+
435
+ port: 3000
436
+ });
437
+ ```
438
+
439
+ ## Common Issues and Solutions
440
+
441
+ ### Issue: "Route not found" Error
442
+
443
+ **Problem:** API endpoint returns 404
444
+ **Possible causes:**
445
+ - Server not restarted after adding API
446
+ - Typo in endpoint name
447
+ - API object not properly defined
448
+
449
+ **Solution:**
450
+ ```bash
451
+ # Restart server
452
+ Ctrl+C then node server.js
453
+
454
+ # Check endpoint name matches
455
+ curl http://localhost:3000/api/your-endpoint
456
+ ```
457
+
458
+ ### Issue: "Unexpected token" Error
459
+
460
+ **Problem:** JSON parsing fails
461
+ **Possible causes:**
462
+ - Wrong Content-Type header
463
+ - Malformed JSON in request body
464
+ - Server expects JSON but receives text
465
+
466
+ **Solution:**
467
+ ```bash
468
+ # Ensure correct Content-Type
469
+ curl -X POST http://localhost:3000/api/endpoint \
470
+ -H "Content-Type: application/json" \
471
+ -d '{"key":"value"}'
472
+ ```
473
+
474
+ ### Issue: Function returns undefined
475
+
476
+ **Problem:** API returns empty response
477
+ **Possible causes:**
478
+ - Function doesn't return anything
479
+ - Async function not awaited properly
480
+ - Error thrown but not caught
481
+
482
+ **Solution:**
483
+ ```javascript
484
+ api: {
485
+ 'working-endpoint': (data) => {
486
+ // Always return something
487
+ return { result: 'success', data: data };
488
+ }
489
+ }
490
+ ```
491
+
492
+ ## Current Limitations (v0.0.1)
493
+
494
+ This guide is provisional. Based on code analysis, the following may need verification:
495
+
496
+ 1. **Middleware Support**: Authentication and custom middleware may not be fully implemented
497
+ 2. **HTTP Methods**: Only GET/POST may be supported (PUT/DELETE unverified)
498
+ 3. **File Uploads**: Multipart form data handling may be limited
499
+ 4. **CORS**: Cross-origin request handling may need configuration
500
+ 5. **Rate Limiting**: No built-in rate limiting (would need custom middleware)
501
+ 6. **Request Size Limits**: No apparent request body size limits implemented
502
+
503
+ ## Next Steps
504
+
505
+ 1. **Verify Examples**: Test all examples in this guide
506
+ 2. **Report Issues**: Document any discrepancies found
507
+ 3. **Extend Functionality**: Add missing features like authentication, CORS, etc.
508
+ 4. **Update Guide**: Incorporate verified information and remove provisional status
509
+
510
+ ## Resources
511
+
512
+ - [Function Publishers and JSON APIs](docs/function-publishers-json-apis.md) - Detailed technical documentation
513
+ - [Advanced Usage Examples](docs/advanced-usage-examples.md) - Complex API patterns
514
+ - [Troubleshooting](docs/troubleshooting.md) - Common issues and solutions
515
+
516
+ ---
517
+
518
+ **Please verify these examples work in your environment and report any issues. This guide will be updated based on community feedback.**