stigmergy 1.0.94 → 1.0.97

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 (67) hide show
  1. package/README.md +20 -0
  2. package/bin/stigmergy +37 -12
  3. package/docs/HASH_TABLE.md +83 -0
  4. package/docs/WEATHER_PROCESSOR_API.md +230 -0
  5. package/docs/best_practices.md +135 -0
  6. package/docs/development_guidelines.md +392 -0
  7. package/docs/http-request-handler.md +289 -0
  8. package/docs/json-parser.md +102 -0
  9. package/docs/requirements_specification.md +148 -0
  10. package/docs/rest_client.md +144 -0
  11. package/docs/system_design.md +314 -0
  12. package/docs/tdd_implementation_plan.md +384 -0
  13. package/docs/test_report.md +49 -0
  14. package/examples/calculator-example.js +72 -0
  15. package/examples/encryption-example.js +67 -0
  16. package/examples/json-parser-example.js +120 -0
  17. package/examples/json-validation-example.js +64 -0
  18. package/examples/rest-client-example.js +52 -0
  19. package/examples/rest_client_example.js +54 -0
  20. package/package.json +26 -21
  21. package/scripts/post-deployment-config.js +9 -2
  22. package/src/auth.js +173 -0
  23. package/src/auth_command.js +208 -0
  24. package/src/calculator.js +313 -0
  25. package/src/core/cli_help_analyzer.js +674 -563
  26. package/src/core/cli_parameter_handler.js +127 -0
  27. package/src/core/cli_tools.js +89 -0
  28. package/src/core/error_handler.js +406 -0
  29. package/src/core/memory_manager.js +83 -0
  30. package/src/core/rest_client.js +160 -0
  31. package/src/core/smart_router.js +146 -0
  32. package/src/data_encryption.js +143 -0
  33. package/src/data_structures.js +440 -0
  34. package/src/deploy.js +56 -0
  35. package/src/index.js +9 -9
  36. package/src/main.js +889 -752
  37. package/src/main_english.js +1305 -977
  38. package/src/main_fixed.js +1172 -0
  39. package/src/utils.js +916 -0
  40. package/src/weatherProcessor.js +228 -0
  41. package/test/calculator.test.js +215 -0
  42. package/test/collision-test.js +26 -0
  43. package/test/csv-processing-test.js +36 -0
  44. package/test/e2e/claude-cli-test.js +128 -0
  45. package/test/e2e/collaboration-test.js +75 -0
  46. package/test/e2e/comprehensive-test.js +431 -0
  47. package/test/e2e/error-handling-test.js +90 -0
  48. package/test/e2e/individual-tool-test.js +143 -0
  49. package/test/e2e/other-cli-test.js +130 -0
  50. package/test/e2e/qoder-cli-test.js +128 -0
  51. package/test/e2e/run-e2e-tests.js +73 -0
  52. package/test/e2e/test-data.js +88 -0
  53. package/test/e2e/test-utils.js +222 -0
  54. package/test/encryption-simple-test.js +110 -0
  55. package/test/encryption.test.js +129 -0
  56. package/test/hash-table-demo.js +33 -0
  57. package/test/hash-table-test.js +26 -0
  58. package/test/hash_table_test.js +114 -0
  59. package/test/json-parser-test.js +161 -0
  60. package/test/json-validation-test.js +164 -0
  61. package/test/rest-client-test.js +56 -0
  62. package/test/rest_client.test.js +85 -0
  63. package/test/unit/calculator-full.test.js +191 -0
  64. package/test/unit/calculator-simple.test.js +96 -0
  65. package/test/unit/calculator.test.js +97 -0
  66. package/test/unit/cli_parameter_handler.test.js +116 -0
  67. package/test/weather-processor.test.js +104 -0
@@ -0,0 +1,384 @@
1
+ # Stigmergy CLI 测试驱动开发实施计划
2
+
3
+ ## 1. 测试策略
4
+
5
+ ### 1.1 测试类型
6
+ - **单元测试**:针对各个模块的独立功能测试
7
+ - **集成测试**:模块间协作和数据流测试
8
+ - **端到端测试**:完整的用户场景测试
9
+ - **性能测试**:关键路径性能验证
10
+
11
+ ### 1.2 测试工具
12
+ - **测试框架**:Jest
13
+ - **断言库**:内置Jest断言
14
+ - **测试覆盖率**:nyc/istanbul
15
+ - **模拟工具**:Jest Mock功能
16
+
17
+ ## 2. 测试计划
18
+
19
+ ### 2.1 智能路由模块测试
20
+
21
+ #### 2.1.1 单元测试用例
22
+ ```javascript
23
+ // tests/unit/smart_router.test.js
24
+
25
+ describe('SmartRouter', () => {
26
+ let router;
27
+
28
+ beforeEach(() => {
29
+ router = new SmartRouter();
30
+ });
31
+
32
+ describe('smartRoute', () => {
33
+ test('should route to claude when claude keyword is detected', async () => {
34
+ const result = await router.smartRoute('用claude分析这段代码');
35
+ expect(result.tool).toBe('claude');
36
+ expect(result.prompt).toBe('分析这段代码');
37
+ });
38
+
39
+ test('should route to qwen when qwen keyword is detected', async () => {
40
+ const result = await router.smartRoute('用qwen写一个hello world程序');
41
+ expect(result.tool).toBe('qwen');
42
+ expect(result.prompt).toBe('写一个hello world程序');
43
+ });
44
+
45
+ test('should route to default tool when no keyword is detected', async () => {
46
+ const result = await router.smartRoute('分析项目架构');
47
+ expect(result.tool).toBe('claude');
48
+ expect(result.prompt).toBe('分析项目架构');
49
+ });
50
+ });
51
+
52
+ describe('extractKeywords', () => {
53
+ test('should extract correct keywords for claude', () => {
54
+ const keywords = router.extractKeywords('claude');
55
+ expect(keywords).toContain('claude');
56
+ expect(keywords).toContain('anthropic');
57
+ });
58
+
59
+ test('should extract correct keywords for qwen', () => {
60
+ const keywords = router.extractKeywords('qwen');
61
+ expect(keywords).toContain('qwen');
62
+ expect(keywords).toContain('alibaba');
63
+ expect(keywords).toContain('tongyi');
64
+ });
65
+ });
66
+ });
67
+ ```
68
+
69
+ #### 2.1.2 集成测试用例
70
+ ```javascript
71
+ // tests/integration/routing_integration.test.js
72
+
73
+ describe('Routing Integration', () => {
74
+ test('should successfully route and execute CLI command', async () => {
75
+ // 模拟CLI工具执行
76
+ const mockSpawn = jest.spyOn(require('child_process'), 'spawn');
77
+ mockSpawn.mockImplementation(() => {
78
+ return {
79
+ on: jest.fn().mockImplementation((event, callback) => {
80
+ if (event === 'close') {
81
+ setTimeout(() => callback(0), 10);
82
+ }
83
+ }),
84
+ stdout: { on: jest.fn() },
85
+ stderr: { on: jest.fn() }
86
+ };
87
+ });
88
+
89
+ // 执行路由
90
+ const router = new SmartRouter();
91
+ const route = await router.smartRoute('用claude分析代码');
92
+
93
+ // 验证路由结果
94
+ expect(route.tool).toBe('claude');
95
+ expect(route.prompt).toBe('分析代码');
96
+
97
+ // 验证CLI执行
98
+ expect(mockSpawn).toHaveBeenCalledWith('claude', ['分析代码'], expect.any(Object));
99
+ });
100
+ });
101
+ ```
102
+
103
+ ### 2.2 上下文管理模块测试
104
+
105
+ #### 2.2.1 单元测试用例
106
+ ```javascript
107
+ // tests/unit/memory_manager.test.js
108
+
109
+ describe('MemoryManager', () => {
110
+ let memoryManager;
111
+ let tempDir;
112
+
113
+ beforeEach(async () => {
114
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'stigmergy-test-'));
115
+ memoryManager = new MemoryManager();
116
+ memoryManager.globalMemoryFile = path.join(tempDir, 'memory.json');
117
+ });
118
+
119
+ afterEach(async () => {
120
+ await fs.rm(tempDir, { recursive: true, force: true });
121
+ });
122
+
123
+ describe('getGlobalMemory', () => {
124
+ test('should return empty memory when file does not exist', async () => {
125
+ const memory = await memoryManager.getGlobalMemory();
126
+ expect(memory).toEqual({
127
+ interactions: [],
128
+ collaborations: []
129
+ });
130
+ });
131
+
132
+ test('should return parsed memory when file exists', async () => {
133
+ const testData = {
134
+ interactions: [{ tool: 'claude', prompt: 'test' }],
135
+ collaborations: []
136
+ };
137
+ await fs.writeFile(memoryManager.globalMemoryFile, JSON.stringify(testData));
138
+
139
+ const memory = await memoryManager.getGlobalMemory();
140
+ expect(memory).toEqual(testData);
141
+ });
142
+ });
143
+
144
+ describe('updateGlobalMemory', () => {
145
+ test('should update memory and return updated data', async () => {
146
+ const updateFn = (memory) => {
147
+ memory.interactions.push({ tool: 'qwen', prompt: 'test' });
148
+ return memory;
149
+ };
150
+
151
+ const updatedMemory = await memoryManager.updateGlobalMemory(updateFn);
152
+
153
+ expect(updatedMemory.interactions).toHaveLength(1);
154
+ expect(updatedMemory.interactions[0].tool).toBe('qwen');
155
+ });
156
+ });
157
+ });
158
+ ```
159
+
160
+ ### 2.3 CLI模式分析模块测试
161
+
162
+ #### 2.3.1 单元测试用例
163
+ ```javascript
164
+ // tests/unit/cli_help_analyzer.test.js
165
+
166
+ describe('CLIHelpAnalyzer', () => {
167
+ let analyzer;
168
+ let tempDir;
169
+
170
+ beforeEach(async () => {
171
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'stigmergy-analyzer-test-'));
172
+ analyzer = new CLIHelpAnalyzer();
173
+ analyzer.configDir = tempDir;
174
+ analyzer.persistentConfig = path.join(tempDir, 'cli-patterns.json');
175
+ });
176
+
177
+ afterEach(async () => {
178
+ await fs.rm(tempDir, { recursive: true, force: true });
179
+ });
180
+
181
+ describe('initialize', () => {
182
+ test('should create config directory and initialize config file', async () => {
183
+ await analyzer.initialize();
184
+
185
+ const configExists = await fs.access(analyzer.persistentConfig).then(() => true).catch(() => false);
186
+ expect(configExists).toBe(true);
187
+
188
+ const config = JSON.parse(await fs.readFile(analyzer.persistentConfig, 'utf8'));
189
+ expect(config.version).toBe('1.0.0');
190
+ expect(config.cliPatterns).toEqual({});
191
+ });
192
+ });
193
+
194
+ describe('analyzeCLI', () => {
195
+ test('should throw error when CLI is not configured', async () => {
196
+ await expect(analyzer.analyzeCLI('nonexistent-cli')).rejects.toThrow();
197
+ });
198
+
199
+ test('should cache analysis results', async () => {
200
+ // 模拟CLI工具帮助信息
201
+ const mockSpawnSync = jest.spyOn(require('child_process'), 'spawnSync');
202
+ mockSpawnSync.mockReturnValue({
203
+ status: 0,
204
+ stdout: 'Usage: claude [options] [command]\n\nCommands:\n analyze Analyze code\n generate Generate code',
205
+ stderr: ''
206
+ });
207
+
208
+ const result = await analyzer.analyzeCLI('claude');
209
+
210
+ expect(result.success).toBe(true);
211
+ expect(result.cliName).toBe('claude');
212
+ expect(result.patterns.commands).toHaveLength(2);
213
+
214
+ // 验证缓存
215
+ const cached = await analyzer.getCachedAnalysis('claude');
216
+ expect(cached).toEqual(result);
217
+ });
218
+ });
219
+ });
220
+ ```
221
+
222
+ ## 3. 实施路线图
223
+
224
+ ### 3.1 第一阶段:基础模块测试 (Week 1-2)
225
+ - [ ] 智能路由模块单元测试
226
+ - [ ] 上下文管理模块单元测试
227
+ - [ ] CLI模式分析模块单元测试
228
+ - [ ] 建立测试基础设施
229
+
230
+ ### 3.2 第二阶段:集成测试 (Week 3)
231
+ - [ ] 模块间集成测试
232
+ - [ ] 数据流测试
233
+ - [ ] 错误处理测试
234
+
235
+ ### 3.3 第三阶段:端到端测试 (Week 4)
236
+ - [ ] 完整用户场景测试
237
+ - [ ] 性能测试
238
+ - [ ] 兼容性测试
239
+
240
+ ### 3.4 第四阶段:测试优化 (Week 5)
241
+ - [ ] 测试覆盖率分析
242
+ - [ ] 测试稳定性优化
243
+ - [ ] 自动化测试流程
244
+
245
+ ## 4. 质量门禁
246
+
247
+ ### 4.1 测试覆盖率要求
248
+ - **行覆盖率**:≥ 80%
249
+ - **函数覆盖率**:≥ 85%
250
+ - **分支覆盖率**:≥ 75%
251
+
252
+ ### 4.2 代码质量要求
253
+ - **ESLint**:无警告和错误
254
+ - **代码复杂度**:函数圈复杂度 ≤ 10
255
+ - **重复代码**:≤ 5%
256
+
257
+ ## 5. 持续集成配置
258
+
259
+ ### 5.1 GitHub Actions 配置
260
+ ```yaml
261
+ # .github/workflows/test.yml
262
+ name: Test
263
+ on: [push, pull_request]
264
+ jobs:
265
+ test:
266
+ runs-on: ubuntu-latest
267
+ strategy:
268
+ matrix:
269
+ node-version: [16.x, 18.x, 20.x]
270
+ steps:
271
+ - uses: actions/checkout@v3
272
+ - name: Use Node.js ${{ matrix.node-version }}
273
+ uses: actions/setup-node@v3
274
+ with:
275
+ node-version: ${{ matrix.node-version }}
276
+ - run: npm ci
277
+ - run: npm test
278
+ - run: npm run coverage
279
+ ```
280
+
281
+ ### 5.2 测试脚本配置
282
+ ```json
283
+ // package.json
284
+ {
285
+ "scripts": {
286
+ "test": "jest",
287
+ "test:unit": "jest tests/unit",
288
+ "test:integration": "jest tests/integration",
289
+ "test:e2e": "jest tests/e2e",
290
+ "coverage": "jest --coverage",
291
+ "test:watch": "jest --watch"
292
+ },
293
+ "jest": {
294
+ "testEnvironment": "node",
295
+ "collectCoverageFrom": [
296
+ "src/**/*.js",
297
+ "!src/index.js"
298
+ ],
299
+ "coverageThreshold": {
300
+ "global": {
301
+ "branches": 75,
302
+ "functions": 85,
303
+ "lines": 80,
304
+ "statements": 80
305
+ }
306
+ }
307
+ }
308
+ }
309
+ ```
310
+
311
+ ## 6. 测试数据管理
312
+
313
+ ### 6.1 测试数据工厂
314
+ ```javascript
315
+ // tests/factories/test_data_factory.js
316
+
317
+ class TestDataFactory {
318
+ static createInteraction(tool = 'claude', prompt = 'test prompt') {
319
+ return {
320
+ timestamp: new Date().toISOString(),
321
+ tool,
322
+ prompt,
323
+ response: 'test response',
324
+ duration: 100
325
+ };
326
+ }
327
+
328
+ static createCLIConfig(name = 'test-cli') {
329
+ return {
330
+ name: `${name} CLI`,
331
+ version: `${name} --version`,
332
+ install: `npm install -g ${name}-cli`,
333
+ hooksDir: path.join(os.homedir(), `.${name}`, 'hooks'),
334
+ config: path.join(os.homedir(), `.${name}`, 'config.json')
335
+ };
336
+ }
337
+ }
338
+ ```
339
+
340
+ ### 6.2 测试环境配置
341
+ ```javascript
342
+ // tests/test_setup.js
343
+
344
+ // 设置测试环境
345
+ process.env.NODE_ENV = 'test';
346
+ process.env.STIGMERGY_TEST_MODE = 'true';
347
+
348
+ // 创建测试临时目录
349
+ const testTempDir = path.join(os.tmpdir(), 'stigmergy-tests');
350
+ fs.mkdirSync(testTempDir, { recursive: true });
351
+
352
+ // 清理测试环境
353
+ afterAll(async () => {
354
+ await fs.rm(testTempDir, { recursive: true, force: true });
355
+ });
356
+ ```
357
+
358
+ ## 7. 性能测试计划
359
+
360
+ ### 7.1 关键性能指标
361
+ - 路由决策时间:< 100ms
362
+ - 内存读写时间:< 50ms
363
+ - CLI模式分析时间:< 5s
364
+
365
+ ### 7.2 性能测试用例
366
+ ```javascript
367
+ // tests/performance/routing_performance.test.js
368
+
369
+ describe('Routing Performance', () => {
370
+ test('should route decision time be less than 100ms', async () => {
371
+ const router = new SmartRouter();
372
+ const startTime = performance.now();
373
+
374
+ await router.smartRoute('用claude分析项目架构');
375
+
376
+ const endTime = performance.now();
377
+ const executionTime = endTime - startTime;
378
+
379
+ expect(executionTime).toBeLessThan(100);
380
+ });
381
+ });
382
+ ```
383
+
384
+ 通过以上TDD实施计划,我们可以确保Stigmergy CLI系统的质量和可靠性,同时保持开发效率。
@@ -0,0 +1,49 @@
1
+ # Stigmergy CLI - 测试报告
2
+
3
+ ## 概述
4
+ 本次测试验证了Stigmergy CLI系统的核心模块,包括智能路由、CLI帮助分析和内存管理模块。
5
+
6
+ ## 测试结果
7
+
8
+ ### 测试套件执行情况
9
+ - **通过**: 3/3 测试套件
10
+ - **失败**: 0/3 测试套件
11
+ - **总测试数**: 20个测试用例
12
+ - **通过率**: 100%
13
+
14
+ ### 详细测试结果
15
+
16
+ #### 1. SmartRouter 测试套件
17
+ - **总测试数**: 11个测试用例
18
+ - **通过**: 11/11
19
+ - **测试内容**:
20
+ - 构造函数测试
21
+ - 关键字提取功能测试
22
+ - 智能路由决策测试
23
+
24
+ #### 2. CLIHelpAnalyzer 测试套件
25
+ - **总测试数**: 6个测试用例
26
+ - **通过**: 6/6
27
+ - **测试内容**:
28
+ - 构造函数测试
29
+ - 初始化功能测试
30
+ - 缓存过期检查测试
31
+ - 文件存在性检查测试
32
+
33
+ #### 3. MemoryManager 测试套件
34
+ - **总测试数**: 3个测试用例
35
+ - **通过**: 3/3
36
+ - **测试内容**:
37
+ - 构造函数测试
38
+ - 全局内存获取测试
39
+ - 内存文件读写测试
40
+
41
+ ## 代码覆盖率
42
+ 当前测试覆盖率尚未达到预设阈值:
43
+ - **语句覆盖率**: 7.51% (目标: 80%)
44
+ - **分支覆盖率**: 7.84% (目标: 75%)
45
+ - **函数覆盖率**: 12.39% (目标: 85%)
46
+ - **行覆盖率**: 7.6% (目标: 80%)
47
+
48
+ ## 结论
49
+ 所有单元测试均已通过,验证了核心模块的基本功能。下一步需要增加更多测试用例以提高代码覆盖率。
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Example usage of the Calculator class
3
+ */
4
+
5
+ const Calculator = require('../src/calculator');
6
+
7
+ // Create a new calculator instance
8
+ const calc = new Calculator();
9
+
10
+ // Basic operations
11
+ console.log('=== Basic Operations ===');
12
+ console.log(`Addition: 5 + 3 = ${calc.add(5, 3)}`);
13
+ console.log(`Subtraction: 10 - 4 = ${calc.subtract(10, 4)}`);
14
+ console.log(`Multiplication: 6 * 7 = ${calc.multiply(6, 7)}`);
15
+ console.log(`Division: 15 / 3 = ${calc.divide(15, 3)}`);
16
+ console.log(`Power: 2^8 = ${calc.power(2, 8)}`);
17
+ console.log(`Square Root: √64 = ${calc.sqrt(64)}`);
18
+ console.log(`Factorial: 5! = ${calc.factorial(5)}`);
19
+ console.log(`Percentage: 25 is what percent of 200 = ${calc.percentage(25, 200)}%`);
20
+
21
+ // Chained calculations
22
+ console.log('\n=== Chained Calculations ===');
23
+ const result1 = calc.chain(10)
24
+ .add(5)
25
+ .multiply(2)
26
+ .subtract(10)
27
+ .divide(4)
28
+ .equals();
29
+
30
+ console.log(`((10 + 5) * 2 - 10) / 4 = ${result1}`);
31
+
32
+ // More complex chained calculation
33
+ const result2 = calc.chain(2)
34
+ .power(3)
35
+ .add(1)
36
+ .multiply(2)
37
+ .sqrt()
38
+ .equals();
39
+
40
+ console.log(`√(((2^3) + 1) * 2) = ${result2}`);
41
+
42
+ // Getting intermediate values
43
+ console.log('\n=== Intermediate Values ===');
44
+ const chain = calc.chain(100)
45
+ .subtract(20) // 80
46
+ .divide(4) // 20
47
+ .add(5); // 25
48
+
49
+ console.log(`Intermediate result: ${chain.value()}`);
50
+
51
+ const finalResult = chain.multiply(2).equals(); // 50
52
+ console.log(`Final result: ${finalResult}`);
53
+
54
+ // Error handling examples
55
+ console.log('\n=== Error Handling ===');
56
+ try {
57
+ calc.divide(10, 0);
58
+ } catch (error) {
59
+ console.log(`Error caught: ${error.message}`);
60
+ }
61
+
62
+ try {
63
+ calc.sqrt(-1);
64
+ } catch (error) {
65
+ console.log(`Error caught: ${error.message}`);
66
+ }
67
+
68
+ try {
69
+ calc.chain(10).divide(0);
70
+ } catch (error) {
71
+ console.log(`Error caught: ${error.message}`);
72
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Example usage of the encryption functions
3
+ */
4
+
5
+ const { encryptData, decryptData, generateKey } = require('../src/utils');
6
+
7
+ // Generate a secure key (in production, use a proper key management system)
8
+ const secretKey = generateKey();
9
+
10
+ console.log('Data Encryption Example');
11
+ console.log('=====================');
12
+
13
+ // Data to encrypt
14
+ const plaintext = "This is confidential information that needs to be protected.";
15
+
16
+ console.log('Original data:', plaintext);
17
+
18
+ try {
19
+ // Encrypt the data
20
+ const encryptedObj = encryptData(plaintext, secretKey);
21
+ console.log('\nEncrypted data:');
22
+ console.log('Encrypted:', encryptedObj.encryptedData);
23
+ console.log('IV:', encryptedObj.iv);
24
+ console.log('Auth Tag:', encryptedObj.authTag);
25
+
26
+ // Decrypt the data
27
+ const decrypted = decryptData(encryptedObj, secretKey);
28
+ console.log('\nDecrypted data:', decrypted);
29
+
30
+ // Verify data integrity
31
+ console.log('\nData integrity check:', plaintext === decrypted ? 'PASS' : 'FAIL');
32
+
33
+ } catch (error) {
34
+ console.error('Encryption/decryption failed:', error.message);
35
+ }
36
+
37
+ // Example with different data types
38
+ console.log('\n\nExample with different data types:');
39
+ console.log('---------------------------------');
40
+
41
+ // Working with buffers
42
+ const bufferData = Buffer.from('Binary data to encrypt', 'utf8');
43
+ console.log('Buffer data to encrypt:', bufferData.toString('utf8'));
44
+
45
+ try {
46
+ const encryptedBuffer = encryptData(bufferData, secretKey);
47
+ const decryptedBuffer = decryptData(encryptedBuffer, secretKey);
48
+ console.log('Decrypted buffer data:', decryptedBuffer);
49
+ } catch (error) {
50
+ console.error('Buffer encryption failed:', error.message);
51
+ }
52
+
53
+ // Working with Unicode characters
54
+ console.log('\nUnicode example:');
55
+ const unicodeData = "Hello, 世界! 🌍 Welcome to 数据加密!";
56
+ console.log('Unicode data to encrypt:', unicodeData);
57
+
58
+ try {
59
+ const encryptedUnicode = encryptData(unicodeData, secretKey);
60
+ const decryptedUnicode = decryptData(encryptedUnicode, secretKey);
61
+ console.log('Decrypted unicode data:', decryptedUnicode);
62
+ console.log('Unicode integrity check:', unicodeData === decryptedUnicode ? 'PASS' : 'FAIL');
63
+ } catch (error) {
64
+ console.error('Unicode encryption failed:', error.message);
65
+ }
66
+
67
+ console.log('\nExample completed.');
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Example usage of the parseAndValidateJSON function
3
+ */
4
+
5
+ const { parseAndValidateJSON } = require('../src/utils');
6
+
7
+ // Example 1: Simple JSON parsing without validation
8
+ console.log('=== Example 1: Simple JSON parsing ===');
9
+ try {
10
+ const jsonString = '{"name": "Alice", "age": 25, "city": "Boston"}';
11
+ const data = parseAndValidateJSON(jsonString);
12
+ console.log('Parsed data:', data);
13
+ } catch (error) {
14
+ console.error('Error:', error.message);
15
+ }
16
+
17
+ // Example 2: JSON parsing with schema validation
18
+ console.log('\n=== Example 2: JSON parsing with schema validation ===');
19
+ try {
20
+ const jsonString = '{"username": "bob", "email": "bob@example.com", "age": 30}';
21
+
22
+ // Define a schema for validation
23
+ const userSchema = {
24
+ required: ["username", "email"],
25
+ properties: {
26
+ username: {
27
+ type: "string",
28
+ minLength: 3,
29
+ maxLength: 20
30
+ },
31
+ email: {
32
+ type: "string"
33
+ },
34
+ age: {
35
+ type: "number",
36
+ minimum: 0,
37
+ maximum: 120
38
+ }
39
+ }
40
+ };
41
+
42
+ const data = parseAndValidateJSON(jsonString, userSchema);
43
+ console.log('Validated data:', data);
44
+ } catch (error) {
45
+ console.error('Error:', error.message);
46
+ }
47
+
48
+ // Example 3: Handling validation errors
49
+ console.log('\n=== Example 3: Handling validation errors ===');
50
+ try {
51
+ const invalidJsonString = '{"username": "c", "email": "charlie@", "age": -5}';
52
+
53
+ const userSchema = {
54
+ required: ["username", "email", "age"],
55
+ properties: {
56
+ username: {
57
+ type: "string",
58
+ minLength: 3, // This will fail since "c" has length 1
59
+ maxLength: 20
60
+ },
61
+ email: {
62
+ type: "string"
63
+ },
64
+ age: {
65
+ type: "number",
66
+ minimum: 0, // This will fail since -5 < 0
67
+ maximum: 120
68
+ }
69
+ }
70
+ };
71
+
72
+ const data = parseAndValidateJSON(invalidJsonString, userSchema);
73
+ console.log('Validated data:', data);
74
+ } catch (error) {
75
+ console.error('Validation Error:', error.message);
76
+ }
77
+
78
+ // Example 4: Working with arrays and nested objects
79
+ console.log('\n=== Example 4: Arrays and nested objects ===');
80
+ try {
81
+ const jsonString = `{
82
+ "id": 1,
83
+ "name": "Product A",
84
+ "tags": ["electronics", "gadgets"],
85
+ "metadata": {
86
+ "createdBy": "admin",
87
+ "createdAt": "2023-01-01"
88
+ }
89
+ }`;
90
+
91
+ const productSchema = {
92
+ required: ["id", "name"],
93
+ properties: {
94
+ id: {
95
+ type: "number"
96
+ },
97
+ name: {
98
+ type: "string"
99
+ },
100
+ tags: {
101
+ type: "array",
102
+ items: { type: "string" },
103
+ minItems: 1
104
+ },
105
+ metadata: {
106
+ type: "object",
107
+ properties: {
108
+ createdBy: { type: "string" },
109
+ createdAt: { type: "string" }
110
+ },
111
+ required: ["createdBy", "createdAt"]
112
+ }
113
+ }
114
+ };
115
+
116
+ const data = parseAndValidateJSON(jsonString, productSchema);
117
+ console.log('Complex validated data:', data);
118
+ } catch (error) {
119
+ console.error('Error:', error.message);
120
+ }