@sonisoft/now-sdk-ext-core 3.8.0 β†’ 3.9.0

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.
package/README.md CHANGED
@@ -1,732 +1,732 @@
1
- # ServiceNow SDK Extensions Core
2
-
3
- [![npm version](https://img.shields.io/npm/v/@sonisoft/now-sdk-ext-core.svg)](https://www.npmjs.com/package/@sonisoft/now-sdk-ext-core)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
- [![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org)
6
-
7
- A comprehensive TypeScript library that extends the ServiceNow SDK with powerful features for application management, automated testing, log monitoring, and more. Perfect for CI/CD pipelines, development automation, and DevOps workflows.
8
-
9
- ## ✨ Features
10
-
11
- - πŸš€ **Application Management** - Install, upgrade, and manage ServiceNow applications programmatically
12
- - πŸͺ **Store Application Management** - Search, install, and update apps from the ServiceNow Store
13
- - πŸ§ͺ **ATF Test Execution** - Run automated tests and get detailed results
14
- - πŸ“Š **Real-time Log Monitoring** - Tail ServiceNow logs with two efficient methods
15
- - πŸ”„ **AMB (Asynchronous Message Bus)** - WebSocket-based real-time event monitoring
16
- - πŸ“ **Background Script Execution** - Execute server-side scripts programmatically
17
- - πŸ“‹ **Scope Management** - Set/get current application scope programmatically
18
- - πŸ“¦ **Update Set Management** - Create, clone, inspect, and manage update sets
19
- - πŸ” **Code Search** - Search across platform code, apps, and tables
20
- - πŸ—„οΈ **Schema Discovery** - Discover table schemas, explain fields, validate catalogs
21
- - πŸ“Ž **Attachment Management** - Upload, list, and retrieve file attachments
22
- - ⚑ **Batch Operations** - Bulk create/update with variable substitution and query-based bulk operations
23
- - πŸ”§ **Workflow Management** - Create complete workflows programmatically
24
- - πŸ“Œ **Task Operations** - Add comments, assign tasks, resolve/close incidents
25
- - πŸ”— **Script Sync** - Bidirectional sync of scripts between local files and instance
26
- - πŸ“ˆ **Aggregate Queries** - COUNT, AVG, MIN, MAX, SUM with GROUP BY via Stats API
27
- - πŸ₯ **Instance Health** - Version, cluster, stuck jobs, semaphore monitoring
28
- - πŸ—ΊοΈ **CMDB Relationships** - Query and traverse CI relationship graphs
29
- - πŸ”Ž **Instance Discovery** - List tables, scoped apps, store apps, and plugins
30
- - πŸ” **Authentication** - Seamless integration with ServiceNow CLI authentication
31
- - πŸ“‘ **Table API** - Full CRUD operations on ServiceNow tables
32
- - πŸ› οΈ **Type-Safe** - Complete TypeScript definitions for all APIs
33
-
34
- ## πŸ“¦ Installation
35
-
36
- ```bash
37
- npm install @sonisoft/now-sdk-ext-core
38
- ```
39
-
40
- ### Prerequisites
41
-
42
- - Node.js 18.x or higher
43
- - ServiceNow CLI configured with instance credentials
44
- - TypeScript 5.x or higher (optional, for TypeScript projects)
45
-
46
- ### ServiceNow CLI Setup
47
-
48
- ```bash
49
- # Install ServiceNow CLI globally
50
- npm install -g @servicenow/sdk
51
-
52
- # Configure your instance credentials
53
- snc configure profile set
54
- ```
55
-
56
- ## ⚠️ Breaking Change β€” v3.0.0 (ServiceNow SDK 4.3.0)
57
-
58
- > **If you are upgrading from v2.x, read this first.**
59
- >
60
- > This version upgrades the underlying ServiceNow SDK dependencies from **4.2.x to 4.3.0**. ServiceNow 4.3.0 **changed how credential aliases are stored**, replacing the previous `keytar`-based credential store with a new implementation.
61
- >
62
- > **What this means for you:**
63
- > - Credential aliases created with ServiceNow SDK 4.2.x **cannot be read** by SDK 4.3.x
64
- > - You **must re-create all instance aliases** after upgrading
65
- >
66
- > **Migration steps:**
67
- > ```bash
68
- > # 1. Update the global CLI
69
- > npm install -g @servicenow/sdk@4.3.0
70
- >
71
- > # 2. Re-add each instance alias
72
- > snc configure profile set
73
- > # β€” or β€”
74
- > npx @servicenow/sdk auth --add <your-alias>
75
- >
76
- > # 3. Verify your aliases work
77
- > npx @servicenow/sdk auth --list
78
- > ```
79
- >
80
- > All API surfaces in this library remain unchanged β€” only the underlying authentication storage has changed.
81
-
82
- ## πŸš€ Quick Start
83
-
84
- ### Basic Connection
85
-
86
- ```typescript
87
- import { ServiceNowInstance } from '@sonisoft/now-sdk-ext-core';
88
- import { getCredentials } from '@servicenow/sdk-cli/dist/auth/index.js';
89
-
90
- // Get credentials from ServiceNow CLI
91
- const credential = await getCredentials('your-instance-alias');
92
-
93
- // Create instance connection
94
- const instance = new ServiceNowInstance({
95
- alias: 'your-instance-alias',
96
- credential: credential
97
- });
98
- ```
99
-
100
- ### Real-Time Log Monitoring
101
-
102
- ```typescript
103
- import { SyslogReader } from '@sonisoft/now-sdk-ext-core';
104
-
105
- const syslogReader = new SyslogReader(instance);
106
-
107
- // Method 1: Using ChannelAjax (faster, more efficient)
108
- await syslogReader.startTailingWithChannelAjax({
109
- interval: 1000, // Poll every second
110
- onLog: (log) => {
111
- console.log(`[${log.sequence}] ${log.message}`);
112
- },
113
- outputFile: './logs/servicenow.log'
114
- });
115
-
116
- // Method 2: Using Table API (supports filtering)
117
- await syslogReader.startTailing('syslog', {
118
- interval: 5000,
119
- query: 'level=error^ORDERBYDESCsys_created_on',
120
- onLog: (log) => {
121
- console.error(`ERROR: ${log.message}`);
122
- }
123
- });
124
-
125
- // Stop tailing
126
- syslogReader.stopTailing();
127
- ```
128
-
129
- ### Execute Background Scripts
130
-
131
- ```typescript
132
- import { BackgroundScriptExecutor } from '@sonisoft/now-sdk-ext-core';
133
-
134
- const executor = new BackgroundScriptExecutor(instance, 'global');
135
-
136
- const script = `
137
- var gr = new GlideRecord('incident');
138
- gr.addQuery('active', true);
139
- gr.query();
140
- gs.info('Active incidents: ' + gr.getRowCount());
141
- `;
142
-
143
- const result = await executor.executeScript(script);
144
- console.log('Script output:', result.output);
145
- ```
146
-
147
- ### Run ATF Tests
148
-
149
- ```typescript
150
- import { ATFTestExecutor } from '@sonisoft/now-sdk-ext-core';
151
-
152
- const testExecutor = new ATFTestExecutor(instance);
153
-
154
- // Execute a test suite
155
- const result = await testExecutor.executeTestSuite('test_suite_sys_id', {
156
- timeout: 300000,
157
- onProgress: (update) => {
158
- console.log(`Progress: ${update.progress}% - ${update.status}`);
159
- }
160
- });
161
-
162
- console.log(`Tests passed: ${result.testsPassedCount}/${result.totalTests}`);
163
- ```
164
-
165
- ## πŸ“š Core Features
166
-
167
- ### 1. Application Management
168
-
169
- Programmatically manage ServiceNow applications, plugins, and updates.
170
-
171
- ```typescript
172
- import { ApplicationManager, BatchInstallation } from '@sonisoft/now-sdk-ext-core';
173
-
174
- const appManager = new ApplicationManager(instance);
175
-
176
- // Install from batch definition
177
- const success = await appManager.installBatch('./batch-definition.json');
178
-
179
- // Get application details
180
- const appDetails = await appManager.getApplicationDetails('com.example.my_app');
181
-
182
- // Check which apps need updates
183
- const needsAction = await appManager.getApplicationsNeedingAction('./batch-definition.json');
184
- ```
185
-
186
- **Batch Definition Example:**
187
- ```json
188
- {
189
- "packages": [
190
- {
191
- "id": "com.snc.sdlc.agile.multi.2.0",
192
- "type": "plugin",
193
- "load_demo_data": false
194
- },
195
- {
196
- "id": "sn_cicd_spoke",
197
- "type": "application",
198
- "version": "1.2.3",
199
- "load_demo_data": false
200
- }
201
- ]
202
- }
203
- ```
204
-
205
- ### 2. ATF (Automated Test Framework) Testing
206
-
207
- Execute tests and retrieve detailed results programmatically.
208
-
209
- ```typescript
210
- import { ATFTestExecutor } from '@sonisoft/now-sdk-ext-core';
211
-
212
- const testExecutor = new ATFTestExecutor(instance);
213
-
214
- // Execute a single test
215
- const result = await testExecutor.executeTest('test_sys_id', {
216
- timeout: 120000,
217
- onProgress: (update) => {
218
- console.log(`Test: ${update.testName} - ${update.status}`);
219
- }
220
- });
221
-
222
- // Execute test suite
223
- const suiteResult = await testExecutor.executeTestSuite('suite_sys_id', {
224
- timeout: 600000,
225
- pollInterval: 5000
226
- });
227
-
228
- // Get detailed results
229
- console.log(`Pass Rate: ${(suiteResult.testsPassedCount / suiteResult.totalTests * 100).toFixed(2)}%`);
230
- console.log(`Failed Tests:`, suiteResult.testResults.filter(t => t.status === 'failure'));
231
- ```
232
-
233
- ### 3. Syslog Reading & Monitoring
234
-
235
- Two methods for log monitoring, each optimized for different use cases.
236
-
237
- #### ChannelAjax Method (Recommended for Real-Time)
238
-
239
- **Benefits:**
240
- - ⚑ Faster (1s default polling vs 5s)
241
- - 🎯 100% reliable (sequence-based tracking)
242
- - πŸ’ͺ Minimal server load
243
- - βœ… No duplicates or missed logs
244
-
245
- ```typescript
246
- import { SyslogReader } from '@sonisoft/now-sdk-ext-core';
247
-
248
- const syslogReader = new SyslogReader(instance);
249
-
250
- await syslogReader.startTailingWithChannelAjax({
251
- interval: 1000,
252
- onLog: (log) => {
253
- const timestamp = new Date(log.sys_created_on).toLocaleString();
254
- console.log(`[${timestamp}] [Seq:${log.sequence}] ${log.message}`);
255
- },
256
- outputFile: './logs/tail.log'
257
- });
258
- ```
259
-
260
- #### Table API Method (Supports Filtering)
261
-
262
- **Benefits:**
263
- - πŸ” Server-side filtering with encoded queries
264
- - πŸ“‹ Access to syslog_app_scope table
265
- - 🎨 Custom field selection
266
- - πŸ“Š Rich formatting options
267
-
268
- ```typescript
269
- await syslogReader.startTailing('syslog', {
270
- interval: 5000,
271
- query: 'level=error^sys_created_on>javascript:gs.minutesAgoStart(10)',
272
- onLog: (log) => {
273
- if (log.level === 'error') {
274
- sendAlert(log);
275
- }
276
- },
277
- formatOptions: {
278
- fields: ['sys_created_on', 'level', 'source', 'message'],
279
- dateFormat: 'relative',
280
- maxMessageWidth: 100
281
- }
282
- });
283
- ```
284
-
285
- #### Query and Export Logs
286
-
287
- ```typescript
288
- // Query recent errors
289
- const errors = await syslogReader.querySyslog(
290
- 'level=error^ORDERBYDESCsys_created_on',
291
- 50
292
- );
293
-
294
- // Print formatted table
295
- syslogReader.printTable(errors, {
296
- fields: ['sys_created_on', 'level', 'source', 'message'],
297
- maxMessageWidth: 80
298
- });
299
-
300
- // Export to file
301
- await syslogReader.saveToFile(errors, './logs/errors.json', 'json');
302
- await syslogReader.saveToFile(errors, './logs/errors.csv', 'csv');
303
- await syslogReader.saveToFile(errors, './logs/errors.txt', 'table');
304
- ```
305
-
306
- ### 4. AMB (Asynchronous Message Bus)
307
-
308
- Monitor real-time events and record changes via WebSocket.
309
-
310
- ```typescript
311
- import { AMBClient, MessageClientBuilder } from '@sonisoft/now-sdk-ext-core';
312
-
313
- const builder = new MessageClientBuilder();
314
- const subscriptions = builder.buildClientSubscriptions();
315
- const client = new AMBClient(subscriptions, instance);
316
-
317
- // Authenticate and connect
318
- await client.authenticate();
319
- client.connect();
320
-
321
- // Watch for incident changes
322
- const channel = client.getRecordWatcherChannel('incident', 'active=true', null, {
323
- subscriptionCallback: (message) => {
324
- console.log('Incident updated:', message);
325
- }
326
- });
327
-
328
- channel.subscribe((message) => {
329
- console.log('Change detected:', message);
330
- });
331
-
332
- // Disconnect when done
333
- client.disconnect();
334
- ```
335
-
336
- ### 5. Table API Operations
337
-
338
- Full CRUD operations on ServiceNow tables.
339
-
340
- ```typescript
341
- import { TableAPIRequest } from '@sonisoft/now-sdk-ext-core';
342
-
343
- const tableAPI = new TableAPIRequest(instance);
344
-
345
- // Create a record
346
- const createResponse = await tableAPI.post('incident', {}, {
347
- short_description: 'Test incident',
348
- urgency: '2',
349
- impact: '2'
350
- });
351
-
352
- // Read records
353
- const readResponse = await tableAPI.get('incident', {
354
- sysparm_query: 'active=true',
355
- sysparm_limit: 10
356
- });
357
-
358
- // Update a record
359
- const updateResponse = await tableAPI.put('incident', 'sys_id_here', {
360
- state: '6', // Resolved
361
- close_notes: 'Issue resolved'
362
- });
363
-
364
- // Partial update
365
- const patchResponse = await tableAPI.patch('incident', 'sys_id_here', {
366
- work_notes: 'Added update via API'
367
- });
368
- ```
369
-
370
- ### 6. Background Script Execution
371
-
372
- Execute server-side GlideScript with full control.
373
-
374
- ```typescript
375
- import { BackgroundScriptExecutor } from '@sonisoft/now-sdk-ext-core';
376
-
377
- const executor = new BackgroundScriptExecutor(instance, 'global');
378
-
379
- // Execute script
380
- const result = await executor.executeScript(`
381
- var gr = new GlideRecord('sys_user');
382
- gr.addQuery('active', true);
383
- gr.addQuery('last_login', '>', gs.daysAgoStart(30));
384
- gr.query();
385
-
386
- var count = gr.getRowCount();
387
- gs.info('Active users (last 30 days): ' + count);
388
-
389
- return count;
390
- `);
391
-
392
- console.log('Script output:', result.output);
393
- console.log('Return value:', result.result);
394
- ```
395
-
396
- ## πŸ“– API Reference
397
-
398
- ### Core Classes
399
-
400
- - **`ServiceNowInstance`** - Instance connection and configuration
401
- - **`ServiceNowRequest`** - HTTP request handling with authentication
402
- - **`TableAPIRequest`** - ServiceNow Table API wrapper (CRUD)
403
-
404
- ### Application Management
405
-
406
- - **`ApplicationManager`** - Install, upgrade, and validate applications via batch definitions
407
- - **`AppRepoApplication`** - App repository operations
408
- - **`CompanyApplications`** - Store application search, install, update, and progress tracking
409
-
410
- ### Scope & Configuration
411
-
412
- - **`ScopeManager`** - Set/get current application scope, list and retrieve applications
413
- - **`UpdateSetManager`** - Create, clone, inspect, move records, and manage update sets
414
-
415
- ### Testing & Automation
416
-
417
- - **`ATFTestExecutor`** - ATF test execution and monitoring with progress tracking
418
- - **`BackgroundScriptExecutor`** - Server-side GlideScript execution
419
-
420
- ### Code & Schema
421
-
422
- - **`CodeSearch`** - Search across platform code by term, app, or table
423
- - **`SchemaDiscovery`** - Discover table schemas, explain fields, validate catalog items
424
-
425
- ### Data Operations
426
-
427
- - **`AttachmentManager`** - Upload, list, and retrieve file attachments
428
- - **`BatchOperations`** - Sequential bulk create/update with variable substitution
429
- - **`QueryBatchOperations`** - Query-based bulk update/delete with dry-run safety
430
-
431
- ### Workflow & Task
432
-
433
- - **`WorkflowManager`** - Create complete workflows with activities, transitions, and conditions
434
- - **`TaskOperations`** - Add comments, assign tasks, resolve/close incidents, approve changes
435
-
436
- ### Scripting
437
-
438
- - **`ScriptSync`** - Bidirectional sync of Script Includes, Business Rules, and more
439
-
440
- ### Monitoring & Discovery
441
-
442
- - **`AggregateQuery`** - COUNT, AVG, MIN, MAX, SUM with GROUP BY via Stats API
443
- - **`InstanceHealth`** - Version, cluster nodes, stuck jobs, semaphores, operational counts
444
- - **`CMDBRelationships`** - Query direct relationships and traverse CI graphs (BFS)
445
- - **`InstanceDiscovery`** - List tables, scoped apps, store apps, and plugins
446
-
447
- ### Logging & Real-time Events
448
-
449
- - **`SyslogReader`** - Log querying, formatting, export, and real-time tailing
450
- - **`AMBClient`** - WebSocket-based real-time event subscriptions
451
- - **`MessageClientBuilder`** - AMB client configuration
452
-
453
- ### Utilities
454
-
455
- - **`Logger`** - Winston-based logging with file output
456
- - **`NowStringUtil`** - String manipulation utilities
457
- - **`AppUtil`** - Application utility functions
458
-
459
- ## 🎯 Use Cases
460
-
461
- ### CI/CD Pipeline Integration
462
-
463
- ```typescript
464
- // Install required apps before deployment
465
- const appManager = new ApplicationManager(instance);
466
- await appManager.installBatch('./required-apps.json');
467
-
468
- // Run tests
469
- const testExecutor = new ATFTestExecutor(instance);
470
- const testResults = await testExecutor.executeTestSuite('deployment_test_suite');
471
-
472
- if (testResults.testsPassedCount !== testResults.totalTests) {
473
- throw new Error('Tests failed, aborting deployment');
474
- }
475
- ```
476
-
477
- ### Log Analysis & Monitoring
478
-
479
- ```typescript
480
- // Real-time error monitoring with alerts
481
- const syslogReader = new SyslogReader(instance);
482
-
483
- await syslogReader.startTailing('syslog', {
484
- query: 'level=error',
485
- onLog: async (log) => {
486
- if (log.message.includes('OutOfMemory')) {
487
- await sendPageAlert('Critical: OOM detected');
488
- }
489
- await saveToElasticsearch(log);
490
- }
491
- });
492
- ```
493
-
494
- ### Data Migration Scripts
495
-
496
- ```typescript
497
- const executor = new BackgroundScriptExecutor(instance, 'global');
498
- const tableAPI = new TableAPIRequest(instance);
499
-
500
- // Export data
501
- const response = await tableAPI.get('custom_table', {
502
- sysparm_limit: 1000,
503
- sysparm_query: 'sys_created_on>2024-01-01'
504
- });
505
-
506
- // Process and transform
507
- const records = response.bodyObject.result;
508
- // ... transformation logic ...
509
-
510
- // Import to another instance
511
- for (const record of transformedRecords) {
512
- await targetTableAPI.post('target_table', {}, record);
513
- }
514
- ```
515
-
516
- ## πŸ“‹ Command-Line Tools
517
-
518
- The library includes ready-to-use CLI tools:
519
-
520
- ### Log Tailing (ChannelAjax)
521
- ```bash
522
- node docs/examples/syslog-tail-channel.mjs your-instance ./logs/tail.log 1000
523
- ```
524
-
525
- ### Log Tailing (Table API)
526
- ```bash
527
- node docs/examples/syslog-tail.mjs your-instance error ./logs/errors.log
528
- ```
529
-
530
- ## πŸ“š Documentation
531
-
532
- Comprehensive documentation is available in the `/docs` directory:
533
-
534
- **Getting Started:**
535
- - **[Getting Started](./docs/GettingStarted.md)** - Setup and basic usage
536
- - **[API Reference](./docs/APIReference.md)** - Complete API documentation
537
- - **[Examples](./docs/examples/)** - Working code examples
538
-
539
- **Application & Scope Management:**
540
- - **[Application Manager](./docs/ApplicationManager.md)** - Application management guide
541
- - **[Store Applications](./docs/CompanyApplications.md)** - Store app search, install, and update
542
- - **[Scope Manager](./docs/ScopeManager.md)** - Application scope management
543
- - **[Update Set Manager](./docs/UpdateSetManager.md)** - Update set lifecycle management
544
-
545
- **Code, Schema & Search:**
546
- - **[Code Search](./docs/CodeSearch.md)** - Platform code search
547
- - **[Schema Discovery](./docs/SchemaDiscovery.md)** - Table schema and field discovery
548
-
549
- **Data Operations:**
550
- - **[Attachment Manager](./docs/AttachmentManager.md)** - File attachment operations
551
- - **[Batch Operations](./docs/BatchOperations.md)** - Bulk create/update with variable substitution
552
- - **[Query Batch Operations](./docs/QueryBatchOperations.md)** - Query-based bulk update/delete
553
-
554
- **Workflow, Task & Scripting:**
555
- - **[Workflow Manager](./docs/WorkflowManager.md)** - Programmatic workflow creation
556
- - **[Task Operations](./docs/TaskOperations.md)** - ITSM task management
557
- - **[Script Sync](./docs/ScriptSync.md)** - Bidirectional script synchronization
558
-
559
- **Monitoring & Discovery:**
560
- - **[Aggregate Query](./docs/AggregateQuery.md)** - Stats API aggregations
561
- - **[Instance Health](./docs/InstanceHealth.md)** - Health monitoring
562
- - **[CMDB Relationships](./docs/CMDBRelationships.md)** - CI relationship graph traversal
563
- - **[Instance Discovery](./docs/InstanceDiscovery.md)** - Table, app, and plugin discovery
564
-
565
- **Testing & Logging:**
566
- - **[ATF Test Executor](./docs/ATFTestExecutor.md)** - Testing automation
567
- - **[Syslog Reader](./docs/SyslogReader.md)** - Log monitoring guide
568
- - **[ChannelAjax Tailing](./docs/SyslogReaderChannelAjax.md)** - Advanced log tailing
569
-
570
- ## πŸ”§ Advanced Configuration
571
-
572
- ### Custom Request Handlers
573
-
574
- ```typescript
575
- import { RequestHandler, ServiceNowInstance } from '@sonisoft/now-sdk-ext-core';
576
-
577
- const handler = new RequestHandler(instance, {
578
- timeout: 30000,
579
- maxRetries: 3,
580
- retryDelay: 1000
581
- });
582
- ```
583
-
584
- ### Custom Logging
585
-
586
- ```typescript
587
- import { Logger } from '@sonisoft/now-sdk-ext-core';
588
-
589
- const logger = Logger.createLogger('MyApp');
590
- logger.info('Application started');
591
- logger.error('Error occurred', { details: errorObj });
592
- ```
593
-
594
- ### Authentication Handler
595
-
596
- ```typescript
597
- import { NowSDKAuthenticationHandler } from '@sonisoft/now-sdk-ext-core';
598
-
599
- const authHandler = new NowSDKAuthenticationHandler(
600
- 'instance-alias',
601
- credential
602
- );
603
-
604
- const token = await authHandler.getToken();
605
- ```
606
-
607
- ## 🀝 TypeScript Support
608
-
609
- The library is written in TypeScript and includes full type definitions:
610
-
611
- ```typescript
612
- import type {
613
- ServiceNowInstance,
614
- SyslogRecord,
615
- ATFTestResult,
616
- ApplicationDetailModel,
617
- BatchDefinition
618
- } from '@sonisoft/now-sdk-ext-core';
619
- ```
620
-
621
- ## πŸ› Error Handling
622
-
623
- ```typescript
624
- import {
625
- FileException,
626
- InvalidParameterException
627
- } from '@sonisoft/now-sdk-ext-core';
628
-
629
- try {
630
- await appManager.installBatch('./batch.json');
631
- } catch (error) {
632
- if (error instanceof FileException) {
633
- console.error('File not found:', error.message);
634
- } else if (error instanceof InvalidParameterException) {
635
- console.error('Invalid parameter:', error.message);
636
- } else {
637
- console.error('Unexpected error:', error);
638
- }
639
- }
640
- ```
641
-
642
- ## ⚑ Performance Tips
643
-
644
- 1. **Use ChannelAjax for log tailing** - 5x faster than Table API polling
645
- 2. **Batch operations** - Group multiple API calls when possible
646
- 3. **Adjust poll intervals** - Balance responsiveness vs. API load
647
- 4. **Use encoded queries** - Server-side filtering is more efficient
648
- 5. **Implement retry logic** - Handle transient network issues
649
-
650
- ## πŸ”’ Security Best Practices
651
-
652
- 1. **Never hardcode credentials** - Use ServiceNow CLI authentication
653
- 2. **Use environment variables** - For configuration
654
- 3. **Implement role-based access** - Verify user permissions
655
- 4. **Audit API usage** - Log all operations
656
- 5. **Use HTTPS** - Always use secure connections
657
-
658
- ## πŸ“¦ Dependencies
659
-
660
- - `@servicenow/sdk` 4.3.0 / `@servicenow/sdk-cli` 4.3.0 / `@servicenow/sdk-core` 4.3.0 - ServiceNow SDK and CLI tools
661
- - `axios` - HTTP client
662
- - `cometd` / `cometd-nodejs-client` - WebSocket support for AMB
663
- - `winston` - Logging
664
- - `xml2js` / `fast-xml-parser` - XML parsing
665
- - `ws` - WebSocket client
666
- - `zod` - Runtime schema validation
667
- - `lodash` - Utility functions
668
-
669
- ## πŸ§ͺ Testing
670
-
671
- ```bash
672
- # Run all tests
673
- npm test
674
-
675
- # Run specific test suite
676
- npm test -- --testPathPattern=SyslogReader
677
-
678
- # Run with coverage
679
- npm test -- --coverage
680
- ```
681
-
682
- ## πŸ—οΈ Building from Source
683
-
684
- ```bash
685
- # Clone the repository
686
- git clone <repository-url>
687
-
688
- # Install dependencies
689
- npm install
690
-
691
- # Build TypeScript
692
- npm run buildts
693
-
694
- # Run tests
695
- npm test
696
-
697
- # Create package
698
- npm pack
699
- ```
700
-
701
- ## πŸ“ License
702
-
703
- MIT License - see LICENSE file for details
704
-
705
- ## πŸ™ Contributing
706
-
707
- Contributions are welcome! Please:
708
-
709
- 1. Fork the repository
710
- 2. Create a feature branch
711
- 3. Make your changes with tests
712
- 4. Submit a pull request
713
-
714
- ## πŸ“ž Support
715
-
716
- For issues, questions, or contributions:
717
-
718
- - πŸ“§ Create an issue in the repository
719
- - πŸ“– Check the documentation in `/docs`
720
- - πŸ’¬ Review existing examples in `/docs/examples`
721
-
722
- ## πŸ—ΊοΈ Roadmap
723
-
724
- - [ ] GraphQL API support
725
- - [ ] Webhook integration
726
- - [ ] Performance metrics dashboard
727
- - [ ] Standalone CLI tool package
728
- - [ ] Plugin development tools
729
-
730
- ---
731
-
732
- **Made with ❀️ for the ServiceNow Developer Community**
1
+ # ServiceNow SDK Extensions Core
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@sonisoft/now-sdk-ext-core.svg)](https://www.npmjs.com/package/@sonisoft/now-sdk-ext-core)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org)
6
+
7
+ A comprehensive TypeScript library that extends the ServiceNow SDK with powerful features for application management, automated testing, log monitoring, and more. Perfect for CI/CD pipelines, development automation, and DevOps workflows.
8
+
9
+ ## ✨ Features
10
+
11
+ - πŸš€ **Application Management** - Install, upgrade, and manage ServiceNow applications programmatically
12
+ - πŸͺ **Store Application Management** - Search, install, and update apps from the ServiceNow Store
13
+ - πŸ§ͺ **ATF Test Execution** - Run automated tests and get detailed results
14
+ - πŸ“Š **Real-time Log Monitoring** - Tail ServiceNow logs with two efficient methods
15
+ - πŸ”„ **AMB (Asynchronous Message Bus)** - WebSocket-based real-time event monitoring
16
+ - πŸ“ **Background Script Execution** - Execute server-side scripts programmatically
17
+ - πŸ“‹ **Scope Management** - Set/get current application scope programmatically
18
+ - πŸ“¦ **Update Set Management** - Create, clone, inspect, and manage update sets
19
+ - πŸ” **Code Search** - Search across platform code, apps, and tables
20
+ - πŸ—„οΈ **Schema Discovery** - Discover table schemas, explain fields, validate catalogs
21
+ - πŸ“Ž **Attachment Management** - Upload, list, and retrieve file attachments
22
+ - ⚑ **Batch Operations** - Bulk create/update with variable substitution and query-based bulk operations
23
+ - πŸ”§ **Workflow Management** - Create complete workflows programmatically
24
+ - πŸ“Œ **Task Operations** - Add comments, assign tasks, resolve/close incidents
25
+ - πŸ”— **Script Sync** - Bidirectional sync of scripts between local files and instance
26
+ - πŸ“ˆ **Aggregate Queries** - COUNT, AVG, MIN, MAX, SUM with GROUP BY via Stats API
27
+ - πŸ₯ **Instance Health** - Version, cluster, stuck jobs, semaphore monitoring
28
+ - πŸ—ΊοΈ **CMDB Relationships** - Query and traverse CI relationship graphs
29
+ - πŸ”Ž **Instance Discovery** - List tables, scoped apps, store apps, and plugins
30
+ - πŸ” **Authentication** - Seamless integration with ServiceNow CLI authentication
31
+ - πŸ“‘ **Table API** - Full CRUD operations on ServiceNow tables
32
+ - πŸ› οΈ **Type-Safe** - Complete TypeScript definitions for all APIs
33
+
34
+ ## πŸ“¦ Installation
35
+
36
+ ```bash
37
+ npm install @sonisoft/now-sdk-ext-core
38
+ ```
39
+
40
+ ### Prerequisites
41
+
42
+ - Node.js 18.x or higher
43
+ - ServiceNow CLI configured with instance credentials
44
+ - TypeScript 5.x or higher (optional, for TypeScript projects)
45
+
46
+ ### ServiceNow CLI Setup
47
+
48
+ ```bash
49
+ # Install ServiceNow CLI globally
50
+ npm install -g @servicenow/sdk
51
+
52
+ # Configure your instance credentials
53
+ snc configure profile set
54
+ ```
55
+
56
+ ## ⚠️ Breaking Change β€” v3.0.0 (ServiceNow SDK 4.3.0)
57
+
58
+ > **If you are upgrading from v2.x, read this first.**
59
+ >
60
+ > This version upgrades the underlying ServiceNow SDK dependencies from **4.2.x to 4.3.0**. ServiceNow 4.3.0 **changed how credential aliases are stored**, replacing the previous `keytar`-based credential store with a new implementation.
61
+ >
62
+ > **What this means for you:**
63
+ > - Credential aliases created with ServiceNow SDK 4.2.x **cannot be read** by SDK 4.3.x
64
+ > - You **must re-create all instance aliases** after upgrading
65
+ >
66
+ > **Migration steps:**
67
+ > ```bash
68
+ > # 1. Update the global CLI
69
+ > npm install -g @servicenow/sdk@4.3.0
70
+ >
71
+ > # 2. Re-add each instance alias
72
+ > snc configure profile set
73
+ > # β€” or β€”
74
+ > npx @servicenow/sdk auth --add <your-alias>
75
+ >
76
+ > # 3. Verify your aliases work
77
+ > npx @servicenow/sdk auth --list
78
+ > ```
79
+ >
80
+ > All API surfaces in this library remain unchanged β€” only the underlying authentication storage has changed.
81
+
82
+ ## πŸš€ Quick Start
83
+
84
+ ### Basic Connection
85
+
86
+ ```typescript
87
+ import { ServiceNowInstance } from '@sonisoft/now-sdk-ext-core';
88
+ import { getCredentials } from '@servicenow/sdk-cli/dist/auth/index.js';
89
+
90
+ // Get credentials from ServiceNow CLI
91
+ const credential = await getCredentials('your-instance-alias');
92
+
93
+ // Create instance connection
94
+ const instance = new ServiceNowInstance({
95
+ alias: 'your-instance-alias',
96
+ credential: credential
97
+ });
98
+ ```
99
+
100
+ ### Real-Time Log Monitoring
101
+
102
+ ```typescript
103
+ import { SyslogReader } from '@sonisoft/now-sdk-ext-core';
104
+
105
+ const syslogReader = new SyslogReader(instance);
106
+
107
+ // Method 1: Using ChannelAjax (faster, more efficient)
108
+ await syslogReader.startTailingWithChannelAjax({
109
+ interval: 1000, // Poll every second
110
+ onLog: (log) => {
111
+ console.log(`[${log.sequence}] ${log.message}`);
112
+ },
113
+ outputFile: './logs/servicenow.log'
114
+ });
115
+
116
+ // Method 2: Using Table API (supports filtering)
117
+ await syslogReader.startTailing('syslog', {
118
+ interval: 5000,
119
+ query: 'level=error^ORDERBYDESCsys_created_on',
120
+ onLog: (log) => {
121
+ console.error(`ERROR: ${log.message}`);
122
+ }
123
+ });
124
+
125
+ // Stop tailing
126
+ syslogReader.stopTailing();
127
+ ```
128
+
129
+ ### Execute Background Scripts
130
+
131
+ ```typescript
132
+ import { BackgroundScriptExecutor } from '@sonisoft/now-sdk-ext-core';
133
+
134
+ const executor = new BackgroundScriptExecutor(instance, 'global');
135
+
136
+ const script = `
137
+ var gr = new GlideRecord('incident');
138
+ gr.addQuery('active', true);
139
+ gr.query();
140
+ gs.info('Active incidents: ' + gr.getRowCount());
141
+ `;
142
+
143
+ const result = await executor.executeScript(script);
144
+ console.log('Script output:', result.output);
145
+ ```
146
+
147
+ ### Run ATF Tests
148
+
149
+ ```typescript
150
+ import { ATFTestExecutor } from '@sonisoft/now-sdk-ext-core';
151
+
152
+ const testExecutor = new ATFTestExecutor(instance);
153
+
154
+ // Execute a test suite
155
+ const result = await testExecutor.executeTestSuite('test_suite_sys_id', {
156
+ timeout: 300000,
157
+ onProgress: (update) => {
158
+ console.log(`Progress: ${update.progress}% - ${update.status}`);
159
+ }
160
+ });
161
+
162
+ console.log(`Tests passed: ${result.testsPassedCount}/${result.totalTests}`);
163
+ ```
164
+
165
+ ## πŸ“š Core Features
166
+
167
+ ### 1. Application Management
168
+
169
+ Programmatically manage ServiceNow applications, plugins, and updates.
170
+
171
+ ```typescript
172
+ import { ApplicationManager, BatchInstallation } from '@sonisoft/now-sdk-ext-core';
173
+
174
+ const appManager = new ApplicationManager(instance);
175
+
176
+ // Install from batch definition
177
+ const success = await appManager.installBatch('./batch-definition.json');
178
+
179
+ // Get application details
180
+ const appDetails = await appManager.getApplicationDetails('com.example.my_app');
181
+
182
+ // Check which apps need updates
183
+ const needsAction = await appManager.getApplicationsNeedingAction('./batch-definition.json');
184
+ ```
185
+
186
+ **Batch Definition Example:**
187
+ ```json
188
+ {
189
+ "packages": [
190
+ {
191
+ "id": "com.snc.sdlc.agile.multi.2.0",
192
+ "type": "plugin",
193
+ "load_demo_data": false
194
+ },
195
+ {
196
+ "id": "sn_cicd_spoke",
197
+ "type": "application",
198
+ "version": "1.2.3",
199
+ "load_demo_data": false
200
+ }
201
+ ]
202
+ }
203
+ ```
204
+
205
+ ### 2. ATF (Automated Test Framework) Testing
206
+
207
+ Execute tests and retrieve detailed results programmatically.
208
+
209
+ ```typescript
210
+ import { ATFTestExecutor } from '@sonisoft/now-sdk-ext-core';
211
+
212
+ const testExecutor = new ATFTestExecutor(instance);
213
+
214
+ // Execute a single test
215
+ const result = await testExecutor.executeTest('test_sys_id', {
216
+ timeout: 120000,
217
+ onProgress: (update) => {
218
+ console.log(`Test: ${update.testName} - ${update.status}`);
219
+ }
220
+ });
221
+
222
+ // Execute test suite
223
+ const suiteResult = await testExecutor.executeTestSuite('suite_sys_id', {
224
+ timeout: 600000,
225
+ pollInterval: 5000
226
+ });
227
+
228
+ // Get detailed results
229
+ console.log(`Pass Rate: ${(suiteResult.testsPassedCount / suiteResult.totalTests * 100).toFixed(2)}%`);
230
+ console.log(`Failed Tests:`, suiteResult.testResults.filter(t => t.status === 'failure'));
231
+ ```
232
+
233
+ ### 3. Syslog Reading & Monitoring
234
+
235
+ Two methods for log monitoring, each optimized for different use cases.
236
+
237
+ #### ChannelAjax Method (Recommended for Real-Time)
238
+
239
+ **Benefits:**
240
+ - ⚑ Faster (1s default polling vs 5s)
241
+ - 🎯 100% reliable (sequence-based tracking)
242
+ - πŸ’ͺ Minimal server load
243
+ - βœ… No duplicates or missed logs
244
+
245
+ ```typescript
246
+ import { SyslogReader } from '@sonisoft/now-sdk-ext-core';
247
+
248
+ const syslogReader = new SyslogReader(instance);
249
+
250
+ await syslogReader.startTailingWithChannelAjax({
251
+ interval: 1000,
252
+ onLog: (log) => {
253
+ const timestamp = new Date(log.sys_created_on).toLocaleString();
254
+ console.log(`[${timestamp}] [Seq:${log.sequence}] ${log.message}`);
255
+ },
256
+ outputFile: './logs/tail.log'
257
+ });
258
+ ```
259
+
260
+ #### Table API Method (Supports Filtering)
261
+
262
+ **Benefits:**
263
+ - πŸ” Server-side filtering with encoded queries
264
+ - πŸ“‹ Access to syslog_app_scope table
265
+ - 🎨 Custom field selection
266
+ - πŸ“Š Rich formatting options
267
+
268
+ ```typescript
269
+ await syslogReader.startTailing('syslog', {
270
+ interval: 5000,
271
+ query: 'level=error^sys_created_on>javascript:gs.minutesAgoStart(10)',
272
+ onLog: (log) => {
273
+ if (log.level === 'error') {
274
+ sendAlert(log);
275
+ }
276
+ },
277
+ formatOptions: {
278
+ fields: ['sys_created_on', 'level', 'source', 'message'],
279
+ dateFormat: 'relative',
280
+ maxMessageWidth: 100
281
+ }
282
+ });
283
+ ```
284
+
285
+ #### Query and Export Logs
286
+
287
+ ```typescript
288
+ // Query recent errors
289
+ const errors = await syslogReader.querySyslog(
290
+ 'level=error^ORDERBYDESCsys_created_on',
291
+ 50
292
+ );
293
+
294
+ // Print formatted table
295
+ syslogReader.printTable(errors, {
296
+ fields: ['sys_created_on', 'level', 'source', 'message'],
297
+ maxMessageWidth: 80
298
+ });
299
+
300
+ // Export to file
301
+ await syslogReader.saveToFile(errors, './logs/errors.json', 'json');
302
+ await syslogReader.saveToFile(errors, './logs/errors.csv', 'csv');
303
+ await syslogReader.saveToFile(errors, './logs/errors.txt', 'table');
304
+ ```
305
+
306
+ ### 4. AMB (Asynchronous Message Bus)
307
+
308
+ Monitor real-time events and record changes via WebSocket.
309
+
310
+ ```typescript
311
+ import { AMBClient, MessageClientBuilder } from '@sonisoft/now-sdk-ext-core';
312
+
313
+ const builder = new MessageClientBuilder();
314
+ const subscriptions = builder.buildClientSubscriptions();
315
+ const client = new AMBClient(subscriptions, instance);
316
+
317
+ // Authenticate and connect
318
+ await client.authenticate();
319
+ client.connect();
320
+
321
+ // Watch for incident changes
322
+ const channel = client.getRecordWatcherChannel('incident', 'active=true', null, {
323
+ subscriptionCallback: (message) => {
324
+ console.log('Incident updated:', message);
325
+ }
326
+ });
327
+
328
+ channel.subscribe((message) => {
329
+ console.log('Change detected:', message);
330
+ });
331
+
332
+ // Disconnect when done
333
+ client.disconnect();
334
+ ```
335
+
336
+ ### 5. Table API Operations
337
+
338
+ Full CRUD operations on ServiceNow tables.
339
+
340
+ ```typescript
341
+ import { TableAPIRequest } from '@sonisoft/now-sdk-ext-core';
342
+
343
+ const tableAPI = new TableAPIRequest(instance);
344
+
345
+ // Create a record
346
+ const createResponse = await tableAPI.post('incident', {}, {
347
+ short_description: 'Test incident',
348
+ urgency: '2',
349
+ impact: '2'
350
+ });
351
+
352
+ // Read records
353
+ const readResponse = await tableAPI.get('incident', {
354
+ sysparm_query: 'active=true',
355
+ sysparm_limit: 10
356
+ });
357
+
358
+ // Update a record
359
+ const updateResponse = await tableAPI.put('incident', 'sys_id_here', {
360
+ state: '6', // Resolved
361
+ close_notes: 'Issue resolved'
362
+ });
363
+
364
+ // Partial update
365
+ const patchResponse = await tableAPI.patch('incident', 'sys_id_here', {
366
+ work_notes: 'Added update via API'
367
+ });
368
+ ```
369
+
370
+ ### 6. Background Script Execution
371
+
372
+ Execute server-side GlideScript with full control.
373
+
374
+ ```typescript
375
+ import { BackgroundScriptExecutor } from '@sonisoft/now-sdk-ext-core';
376
+
377
+ const executor = new BackgroundScriptExecutor(instance, 'global');
378
+
379
+ // Execute script
380
+ const result = await executor.executeScript(`
381
+ var gr = new GlideRecord('sys_user');
382
+ gr.addQuery('active', true);
383
+ gr.addQuery('last_login', '>', gs.daysAgoStart(30));
384
+ gr.query();
385
+
386
+ var count = gr.getRowCount();
387
+ gs.info('Active users (last 30 days): ' + count);
388
+
389
+ return count;
390
+ `);
391
+
392
+ console.log('Script output:', result.output);
393
+ console.log('Return value:', result.result);
394
+ ```
395
+
396
+ ## πŸ“– API Reference
397
+
398
+ ### Core Classes
399
+
400
+ - **`ServiceNowInstance`** - Instance connection and configuration
401
+ - **`ServiceNowRequest`** - HTTP request handling with authentication
402
+ - **`TableAPIRequest`** - ServiceNow Table API wrapper (CRUD)
403
+
404
+ ### Application Management
405
+
406
+ - **`ApplicationManager`** - Install, upgrade, and validate applications via batch definitions
407
+ - **`AppRepoApplication`** - App repository operations
408
+ - **`CompanyApplications`** - Store application search, install, update, and progress tracking
409
+
410
+ ### Scope & Configuration
411
+
412
+ - **`ScopeManager`** - Set/get current application scope, list and retrieve applications
413
+ - **`UpdateSetManager`** - Create, clone, inspect, move records, and manage update sets
414
+
415
+ ### Testing & Automation
416
+
417
+ - **`ATFTestExecutor`** - ATF test execution and monitoring with progress tracking
418
+ - **`BackgroundScriptExecutor`** - Server-side GlideScript execution
419
+
420
+ ### Code & Schema
421
+
422
+ - **`CodeSearch`** - Search across platform code by term, app, or table
423
+ - **`SchemaDiscovery`** - Discover table schemas, explain fields, validate catalog items
424
+
425
+ ### Data Operations
426
+
427
+ - **`AttachmentManager`** - Upload, list, and retrieve file attachments
428
+ - **`BatchOperations`** - Sequential bulk create/update with variable substitution
429
+ - **`QueryBatchOperations`** - Query-based bulk update/delete with dry-run safety
430
+
431
+ ### Workflow & Task
432
+
433
+ - **`WorkflowManager`** - Create complete workflows with activities, transitions, and conditions
434
+ - **`TaskOperations`** - Add comments, assign tasks, resolve/close incidents, approve changes
435
+
436
+ ### Scripting
437
+
438
+ - **`ScriptSync`** - Bidirectional sync of Script Includes, Business Rules, and more
439
+
440
+ ### Monitoring & Discovery
441
+
442
+ - **`AggregateQuery`** - COUNT, AVG, MIN, MAX, SUM with GROUP BY via Stats API
443
+ - **`InstanceHealth`** - Version, cluster nodes, stuck jobs, semaphores, operational counts
444
+ - **`CMDBRelationships`** - Query direct relationships and traverse CI graphs (BFS)
445
+ - **`InstanceDiscovery`** - List tables, scoped apps, store apps, and plugins
446
+
447
+ ### Logging & Real-time Events
448
+
449
+ - **`SyslogReader`** - Log querying, formatting, export, and real-time tailing
450
+ - **`AMBClient`** - WebSocket-based real-time event subscriptions
451
+ - **`MessageClientBuilder`** - AMB client configuration
452
+
453
+ ### Utilities
454
+
455
+ - **`Logger`** - Winston-based logging with file output
456
+ - **`NowStringUtil`** - String manipulation utilities
457
+ - **`AppUtil`** - Application utility functions
458
+
459
+ ## 🎯 Use Cases
460
+
461
+ ### CI/CD Pipeline Integration
462
+
463
+ ```typescript
464
+ // Install required apps before deployment
465
+ const appManager = new ApplicationManager(instance);
466
+ await appManager.installBatch('./required-apps.json');
467
+
468
+ // Run tests
469
+ const testExecutor = new ATFTestExecutor(instance);
470
+ const testResults = await testExecutor.executeTestSuite('deployment_test_suite');
471
+
472
+ if (testResults.testsPassedCount !== testResults.totalTests) {
473
+ throw new Error('Tests failed, aborting deployment');
474
+ }
475
+ ```
476
+
477
+ ### Log Analysis & Monitoring
478
+
479
+ ```typescript
480
+ // Real-time error monitoring with alerts
481
+ const syslogReader = new SyslogReader(instance);
482
+
483
+ await syslogReader.startTailing('syslog', {
484
+ query: 'level=error',
485
+ onLog: async (log) => {
486
+ if (log.message.includes('OutOfMemory')) {
487
+ await sendPageAlert('Critical: OOM detected');
488
+ }
489
+ await saveToElasticsearch(log);
490
+ }
491
+ });
492
+ ```
493
+
494
+ ### Data Migration Scripts
495
+
496
+ ```typescript
497
+ const executor = new BackgroundScriptExecutor(instance, 'global');
498
+ const tableAPI = new TableAPIRequest(instance);
499
+
500
+ // Export data
501
+ const response = await tableAPI.get('custom_table', {
502
+ sysparm_limit: 1000,
503
+ sysparm_query: 'sys_created_on>2024-01-01'
504
+ });
505
+
506
+ // Process and transform
507
+ const records = response.bodyObject.result;
508
+ // ... transformation logic ...
509
+
510
+ // Import to another instance
511
+ for (const record of transformedRecords) {
512
+ await targetTableAPI.post('target_table', {}, record);
513
+ }
514
+ ```
515
+
516
+ ## πŸ“‹ Command-Line Tools
517
+
518
+ The library includes ready-to-use CLI tools:
519
+
520
+ ### Log Tailing (ChannelAjax)
521
+ ```bash
522
+ node docs/examples/syslog-tail-channel.mjs your-instance ./logs/tail.log 1000
523
+ ```
524
+
525
+ ### Log Tailing (Table API)
526
+ ```bash
527
+ node docs/examples/syslog-tail.mjs your-instance error ./logs/errors.log
528
+ ```
529
+
530
+ ## πŸ“š Documentation
531
+
532
+ Comprehensive documentation is available in the `/docs` directory:
533
+
534
+ **Getting Started:**
535
+ - **[Getting Started](./docs/GettingStarted.md)** - Setup and basic usage
536
+ - **[API Reference](./docs/APIReference.md)** - Complete API documentation
537
+ - **[Examples](./docs/examples/)** - Working code examples
538
+
539
+ **Application & Scope Management:**
540
+ - **[Application Manager](./docs/ApplicationManager.md)** - Application management guide
541
+ - **[Store Applications](./docs/CompanyApplications.md)** - Store app search, install, and update
542
+ - **[Scope Manager](./docs/ScopeManager.md)** - Application scope management
543
+ - **[Update Set Manager](./docs/UpdateSetManager.md)** - Update set lifecycle management
544
+
545
+ **Code, Schema & Search:**
546
+ - **[Code Search](./docs/CodeSearch.md)** - Platform code search
547
+ - **[Schema Discovery](./docs/SchemaDiscovery.md)** - Table schema and field discovery
548
+
549
+ **Data Operations:**
550
+ - **[Attachment Manager](./docs/AttachmentManager.md)** - File attachment operations
551
+ - **[Batch Operations](./docs/BatchOperations.md)** - Bulk create/update with variable substitution
552
+ - **[Query Batch Operations](./docs/QueryBatchOperations.md)** - Query-based bulk update/delete
553
+
554
+ **Workflow, Task & Scripting:**
555
+ - **[Workflow Manager](./docs/WorkflowManager.md)** - Programmatic workflow creation
556
+ - **[Task Operations](./docs/TaskOperations.md)** - ITSM task management
557
+ - **[Script Sync](./docs/ScriptSync.md)** - Bidirectional script synchronization
558
+
559
+ **Monitoring & Discovery:**
560
+ - **[Aggregate Query](./docs/AggregateQuery.md)** - Stats API aggregations
561
+ - **[Instance Health](./docs/InstanceHealth.md)** - Health monitoring
562
+ - **[CMDB Relationships](./docs/CMDBRelationships.md)** - CI relationship graph traversal
563
+ - **[Instance Discovery](./docs/InstanceDiscovery.md)** - Table, app, and plugin discovery
564
+
565
+ **Testing & Logging:**
566
+ - **[ATF Test Executor](./docs/ATFTestExecutor.md)** - Testing automation
567
+ - **[Syslog Reader](./docs/SyslogReader.md)** - Log monitoring guide
568
+ - **[ChannelAjax Tailing](./docs/SyslogReaderChannelAjax.md)** - Advanced log tailing
569
+
570
+ ## πŸ”§ Advanced Configuration
571
+
572
+ ### Custom Request Handlers
573
+
574
+ ```typescript
575
+ import { RequestHandler, ServiceNowInstance } from '@sonisoft/now-sdk-ext-core';
576
+
577
+ const handler = new RequestHandler(instance, {
578
+ timeout: 30000,
579
+ maxRetries: 3,
580
+ retryDelay: 1000
581
+ });
582
+ ```
583
+
584
+ ### Custom Logging
585
+
586
+ ```typescript
587
+ import { Logger } from '@sonisoft/now-sdk-ext-core';
588
+
589
+ const logger = Logger.createLogger('MyApp');
590
+ logger.info('Application started');
591
+ logger.error('Error occurred', { details: errorObj });
592
+ ```
593
+
594
+ ### Authentication Handler
595
+
596
+ ```typescript
597
+ import { NowSDKAuthenticationHandler } from '@sonisoft/now-sdk-ext-core';
598
+
599
+ const authHandler = new NowSDKAuthenticationHandler(
600
+ 'instance-alias',
601
+ credential
602
+ );
603
+
604
+ const token = await authHandler.getToken();
605
+ ```
606
+
607
+ ## 🀝 TypeScript Support
608
+
609
+ The library is written in TypeScript and includes full type definitions:
610
+
611
+ ```typescript
612
+ import type {
613
+ ServiceNowInstance,
614
+ SyslogRecord,
615
+ ATFTestResult,
616
+ ApplicationDetailModel,
617
+ BatchDefinition
618
+ } from '@sonisoft/now-sdk-ext-core';
619
+ ```
620
+
621
+ ## πŸ› Error Handling
622
+
623
+ ```typescript
624
+ import {
625
+ FileException,
626
+ InvalidParameterException
627
+ } from '@sonisoft/now-sdk-ext-core';
628
+
629
+ try {
630
+ await appManager.installBatch('./batch.json');
631
+ } catch (error) {
632
+ if (error instanceof FileException) {
633
+ console.error('File not found:', error.message);
634
+ } else if (error instanceof InvalidParameterException) {
635
+ console.error('Invalid parameter:', error.message);
636
+ } else {
637
+ console.error('Unexpected error:', error);
638
+ }
639
+ }
640
+ ```
641
+
642
+ ## ⚑ Performance Tips
643
+
644
+ 1. **Use ChannelAjax for log tailing** - 5x faster than Table API polling
645
+ 2. **Batch operations** - Group multiple API calls when possible
646
+ 3. **Adjust poll intervals** - Balance responsiveness vs. API load
647
+ 4. **Use encoded queries** - Server-side filtering is more efficient
648
+ 5. **Implement retry logic** - Handle transient network issues
649
+
650
+ ## πŸ”’ Security Best Practices
651
+
652
+ 1. **Never hardcode credentials** - Use ServiceNow CLI authentication
653
+ 2. **Use environment variables** - For configuration
654
+ 3. **Implement role-based access** - Verify user permissions
655
+ 4. **Audit API usage** - Log all operations
656
+ 5. **Use HTTPS** - Always use secure connections
657
+
658
+ ## πŸ“¦ Dependencies
659
+
660
+ - `@servicenow/sdk` 4.3.0 / `@servicenow/sdk-cli` 4.3.0 / `@servicenow/sdk-core` 4.3.0 - ServiceNow SDK and CLI tools
661
+ - `axios` - HTTP client
662
+ - `cometd` / `cometd-nodejs-client` - WebSocket support for AMB
663
+ - `winston` - Logging
664
+ - `xml2js` / `fast-xml-parser` - XML parsing
665
+ - `ws` - WebSocket client
666
+ - `zod` - Runtime schema validation
667
+ - `lodash` - Utility functions
668
+
669
+ ## πŸ§ͺ Testing
670
+
671
+ ```bash
672
+ # Run all tests
673
+ npm test
674
+
675
+ # Run specific test suite
676
+ npm test -- --testPathPattern=SyslogReader
677
+
678
+ # Run with coverage
679
+ npm test -- --coverage
680
+ ```
681
+
682
+ ## πŸ—οΈ Building from Source
683
+
684
+ ```bash
685
+ # Clone the repository
686
+ git clone <repository-url>
687
+
688
+ # Install dependencies
689
+ npm install
690
+
691
+ # Build TypeScript
692
+ npm run buildts
693
+
694
+ # Run tests
695
+ npm test
696
+
697
+ # Create package
698
+ npm pack
699
+ ```
700
+
701
+ ## πŸ“ License
702
+
703
+ MIT License - see LICENSE file for details
704
+
705
+ ## πŸ™ Contributing
706
+
707
+ Contributions are welcome! Please:
708
+
709
+ 1. Fork the repository
710
+ 2. Create a feature branch
711
+ 3. Make your changes with tests
712
+ 4. Submit a pull request
713
+
714
+ ## πŸ“ž Support
715
+
716
+ For issues, questions, or contributions:
717
+
718
+ - πŸ“§ Create an issue in the repository
719
+ - πŸ“– Check the documentation in `/docs`
720
+ - πŸ’¬ Review existing examples in `/docs/examples`
721
+
722
+ ## πŸ—ΊοΈ Roadmap
723
+
724
+ - [ ] GraphQL API support
725
+ - [ ] Webhook integration
726
+ - [ ] Performance metrics dashboard
727
+ - [ ] Standalone CLI tool package
728
+ - [ ] Plugin development tools
729
+
730
+ ---
731
+
732
+ **Made with ❀️ for the ServiceNow Developer Community**