### Install Docker and Run Nightscout on Ubuntu Source: https://github.com/nightscout/cgm-remote-monitor/wiki/Setting-up-Stand-Alone-Nightscout-Server-|-Ubuntu-&-Raspberry-Pi---Docker Commands to install Docker, start the Docker service, clone the nightscout-docker repository, edit the docker-compose.yml file, and launch the Nightscout container on Ubuntu. ```bash apt install docker.io systemctl start docker git clone https://github.com/nightscout/nightscout-docker cd nightscout-docker nano docker-compose.yml docker-compose up -d ``` -------------------------------- ### Vagrant VM Setup for Nightscout Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/README.md Instructions for setting up a virtual machine using Vagrant for Nightscout development. This includes starting the VM, SSHing into it, and running the setup script. ```bash host$ vagrant up host$ vagrant ssh vm$ ./bin/setup.sh ``` -------------------------------- ### Example Profile Store Configuration Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/data-schemas/profiles-schema.md An example of the 'store' object containing a 'Default' profile with various time-based settings. ```json "store": { "Default": { "units": "mg/dL", "dia": 6, "timezone": "ETC/GMT+8", "carbs_hr": "0", "delay": "0", "basal": [ { "time": "00:00", "timeAsSeconds": 0, "value": 1.8 }, { "time": "05:30", "timeAsSeconds": 19800, "value": 1.7 }, { "time": "22:30", "timeAsSeconds": 81000, "value": 1.8 } ], "carbratio": [ { "time": "00:00", "timeAsSeconds": 0, "value": 10 } ], "sens": [ { "time": "00:00", "timeAsSeconds": 0, "value": 40 } ], "target_low": [ { "time": "00:00", "timeAsSeconds": 0, "value": 97 } ], "target_high": [ { "time": "00:00", "timeAsSeconds": 0, "value": 102 } ] } } ``` -------------------------------- ### Import Configuration Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/README.md Example structure for importing settings and extended settings from a URL. This JSON object defines theme colors and alert configurations. ```json {"settings": {"theme": "colors"}, "extendedSettings": {"upbat": {"enableAlerts": true}}} ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/README.md Run this command in the root of the project to install all necessary Node.js dependencies. ```bash $ npm install ``` -------------------------------- ### Shiro Permission Examples Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/requirements/authorization-security-requirements.md Illustrates the Apache Shiro permission format and provides examples for common use cases. ```text api:entries:read - Read entries via API api:treatments:create - Create treatments api:*:* - All API operations * - Full admin access ``` -------------------------------- ### Add Web Manifest for PWA Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Example of a web manifest file for PWA support. This JSON defines application metadata such as name, short name, start URL, and theme color. ```json { "name": "Nightscout", "short_name": "NS", "start_url": "/", "display": "standalone", "theme_color": "#000000" } ``` -------------------------------- ### Complete Client-Side Socket.IO Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/socket.md A full HTML example demonstrating how to connect to the APIv3 Socket.IO endpoint, subscribe to collections, and handle incoming data events. ```html APIv3 Socket.IO sample ``` -------------------------------- ### API v1 Success Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Illustrates the typical JSON structure for a successful GET request to the API v1, such as listing entries. ```json [ { "_id": "5f1234567890abcdef123456", "sgv": 120, "date": 1595000000000, "dateString": "2020-07-17T12:00:00.000Z", "trend": 4, "direction": "Flat", "device": "xDrip-DexcomG6", "type": "sgv" } ] ``` -------------------------------- ### API v3 Search Entries Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of a GET request to search entries in API v3, specifying sorting, limit, and fields. ```http GET /api/v3/entries?sort$desc=date&limit=100&fields=sgv,date,direction ``` -------------------------------- ### Logging Examples Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/messaging-subsystem-audit.md Examples of logging messages at different levels using console methods. Useful for debugging and monitoring application events. ```javascript console.info('EMITTING ALARM:', JSON.stringify(notify)); console.log('Skipping duplicate notification'); console.error('Pushover send failed:', err); ``` -------------------------------- ### Add Service Worker for PWA Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Example of a basic service worker for PWA support. This snippet demonstrates the 'install' event, caching essential application assets. ```javascript // service-worker.js self.addEventListener('install', (event) => { event.waitUntil( caches.open('nightscout-v1').then((cache) => { return cache.addAll([ '/', '/bundle/bundle.js', '/bundle/bundle.css' ]); }) ); }); ``` -------------------------------- ### Example Delegated Token Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/oidc-actor-identity-proposal.md An example of a JWT token demonstrating delegation claims. ```APIDOC ## Example Delegated Token ```json { "iss": "https://nrg.example.com", "sub": "patient-uuid-456", "ns:display_name": "Patient Jane", "ns:actor_type": "human", "act": { "sub": "clinic-staff-uuid", "ns:display_name": "Dr. Smith", "ns:actor_type": "human" }, "ns:permissions": ["api:treatments:create", "api:entries:read"] } ``` ``` -------------------------------- ### Dual Write Data Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/oidc-actor-identity-proposal.md Illustrates the data structure during the dual-write phase of migration, where both `enteredBy` and `actor_ref` are populated for compatibility. ```json { "enteredBy": "Mom", // From actor.display_name "actor_ref": "uuid-123" // From actor.sub } ``` -------------------------------- ### JWT Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of a successful JWT response from the authorization endpoint. ```http GET /api/v2/authorization/request/mytoken-abc123 ``` ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "sub": "mytoken", "permissionGroups": [ ["api:entries:read", "api:treatments:read"] ], "iat": 1595000000, "exp": 1595003600 } ``` -------------------------------- ### Setup Socket.IO Server Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/realtime-systems-audit.md Sets up the Socket.IO server with default configurations for ping timeouts and intervals. It also includes a basic connection handler. ```javascript var io = require('socket.io')(server, { // Default configuration pingTimeout: 60000, pingInterval: 25000 }); io.on('connection', function (socket) { // Handle connection }); ``` -------------------------------- ### v1 API Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/mongodb-modernization-implementation-plan.md Illustrates how the v1 API currently returns an array of created treatment objects. ```javascript // lib/api/treatments/index.js line 142 res.json(created); // where created is array of objects from storage layer ``` -------------------------------- ### Virtual Assistant Intent Handler Callback Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/plugins/add-virtual-assistant-support-to-plugin.md Example of a callback function for an intent handler. It requires `title` for display on cards and `text` for the virtual assistant's spoken response. The `slots` argument contains detected parameters, and `sandbox` provides access to Nightscout functions. ```javascript callback(null, {results: "Hello world", priority: 1}); ``` -------------------------------- ### Announcement Data Structure Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/alarmsockets.md Example JSON structure for an 'announcement' event received from the socket. ```json { "level":0, "title":"Announcement", "message":"test", "plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true}, "group":"Announcement", "isAnnouncement":true, "key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" } ``` -------------------------------- ### API Endpoint Testing Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Example of how to write tests for API endpoints using a testing framework. This snippet demonstrates testing for authorized and unauthorized access to the /api/v3/entries endpoint. ```javascript // Example: API endpoint tests describe('GET /api/v3/entries', () => { it('should return entries for authorized user', async () => { const response = await request(app) .get('/api/v3/entries') .set('Authorization', `Bearer ${validToken}`) .expect(200); expect(response.body.status).toBe(200); expect(response.body.result).toBeInstanceOf(Array); }); it('should reject unauthorized requests', async () => { await request(app) .get('/api/v3/entries') .expect(401); }); }); ``` -------------------------------- ### Legacy WebSocket Connection Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of establishing a connection to the legacy WebSocket endpoint with an authentication token. ```javascript const socket = io('https://example.com/', { query: { token: 'mytoken' } }); ``` -------------------------------- ### Document MongoDB Versions Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/mongodb-modernization-implementation-plan.md Command to list the currently installed versions of the MongoDB drivers. ```bash npm list mongodb mongodb-legacy > mongodb-versions-baseline.txt ``` -------------------------------- ### XML Output Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/formats.md Sample XML output for APIv3 requests. This format can be requested by appending .xml to the URL or setting the Accept header. ```xml sgv 171 2014-07-19T02:44:15.000-07:00 1405763055000 dexcom Flat 5c5a2404e0196f4d3d9a718a 1405763055000 1405763055000 sgv 176 2014-07-19T03:09:15.000-07:00 1405764555000 dexcom Flat 5c5a2404e0196f4d3d9a7187 1405764555000 1405764555000 ``` -------------------------------- ### Authorization Permissions Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/architecture-overview.md Illustrates Apache Shiro-style permissions for API access control. Use specific permissions for fine-grained control, or '*' for admin access. ```plaintext api:entries:read # Read entries collection api:treatments:create # Create treatments * # Admin (all permissions) ``` -------------------------------- ### Implement Socket.IO Redis Adapter Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/realtime-systems-audit.md Configure Socket.IO to use Redis for horizontal scaling. Requires Redis client setup and adapter creation. ```javascript const { createAdapter } = require('@socket.io/redis-adapter'); const { createClient } = require('redis'); const pubClient = createClient({ url: process.env.REDIS_URL }); const subClient = pubClient.duplicate(); io.adapter(createAdapter(pubClient, subClient)); ``` -------------------------------- ### Test Environment Setup Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/test-specs/authorization-tests.md Sets up the test environment by requiring necessary modules, configuring environment variables, and booting the server. It also initializes authentication-related components and retrieves test tokens. ```javascript before(function(done) { var api = require('../lib/api/'); delete process.env.API_SECRET; process.env.API_SECRET = 'this is my long pass phrase'; self.env = require('../lib/server/env')(); self.env.settings.authDefaultRoles = 'denied'; require('../lib/server/bootevent')(self.env, language).boot(async function booted (ctx) { self.app.use('/api/v1', api(self.env, ctx)); self.app.use('/api/v2/authorization', ctx.authorization.endpoints); let authResult = await authSubject(ctx.authorization.storage); self.subject = authResult.subject; self.token = authResult.accessToken; done(); }); }); ``` -------------------------------- ### Complete Client-Side Sample Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/alarmsockets.md A full HTML page demonstrating how to connect to the alarm socket, subscribe, and listen for different alarm events. ```html APIv3 Socket.IO sample for alarms ``` -------------------------------- ### Run Tests with Make Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/TEST-IMPLEMENTATION-SUMMARY.md Use the make command for a streamlined testing process. This is the recommended approach for running all tests. ```bash make test ``` -------------------------------- ### API v3 Success Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of a successful response format for API v3 collection operations. ```json { "status": 200, "result": [ { "identifier": "abc123-def456", "date": 1595000000000, "sgv": 120, "direction": "Flat", "srvCreated": 1595000001000, "srvModified": 1595000001000 } ] } ``` -------------------------------- ### Boot Sequence Flow Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/architecture-overview.md Illustrates the sequential boot process of the application using the bootevent library. ```text startBoot → checkNodeVersion → checkEnv → augmentSettings → checkSettings ↓ setupStorage → setupAuthorization → setupInternals → ensureIndexes ↓ setupListeners → setupConnect → setupBridge → setupMMConnect → finishBoot ``` -------------------------------- ### API v3 Error Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of an error response format for API v3, indicating authentication issues. ```json { "status": 401, "message": "Missing or bad access token or JWT" } ``` -------------------------------- ### Fixture Usage Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/TEST-IMPLEMENTATION-SUMMARY.md Demonstrates how to import and use fixtures for various test scenarios, including Loop, Trio, and edge cases. Fixtures provide pre-defined data for consistent testing. ```javascript const fixtures = require('./fixtures'); // Loop fixtures fixtures.loop.carbsBatch // 2 carb corrections fixtures.loop.doseBatch // 2 doses (temp basal + bolus) fixtures.loop.glucoseBatch // 3 glucose entries fixtures.loop.largeBatch // 100 glucose entries // Trio fixtures fixtures.trio.treatmentPipeline // 2 treatments fixtures.trio.glucosePipeline // 2 glucose entries // Edge cases fixtures.edgeCases.singleItemArray // 1 entry in array fixtures.edgeCases.emptyBatch // [] empty array fixtures.edgeCases.mixedValidity // 2 entries with isValid true/false ``` -------------------------------- ### Configure Query Limits via Environment Variables Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/api-query-normalization.md Demonstrates how to override default query limits and set global multipliers or operational modes using environment variables. This allows for flexible deployment configurations. ```bash # Override default limits QUERY_LIMIT_ENTRIES_MAX=2000 QUERY_LIMIT_DEVICESTATUS_MAX=50 # Global multiplier (for constrained deployments) QUERY_LIMIT_GLOBAL_MULTIPLIER=0.5 # Mode: warn (log only) or enforce (reject/clamp) QUERY_LIMITS_MODE=warn ``` -------------------------------- ### Run Baseline Tests Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/IMPLEMENTATION-QUICKSTART.md Execute existing storage and API tests to establish a baseline. Redirect output to a file for later comparison. ```bash npm test tests/storage.shape-handling.test.js npm test tests/api.shape-handling.test.js npm test tests/api3.shape-handling.test.js npm test tests/api3.aaps-patterns.test.js ``` ```bash npm test > baseline-test-results.txt 2>&1 ``` -------------------------------- ### GitHub Actions: Sequential Testing with Optimizations Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/TEST-OPTIMIZATION-GUIDE.md Recommended GitHub Actions workflow for CI stability, running tests sequentially while benefiting from optimized app initialization. ```yaml jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '16' cache: 'npm' - name: Start MongoDB uses: supercharge/mongodb-github-action@1.10.0 - run: npm ci - run: npm run test-ci ``` -------------------------------- ### API v1 Inconsistent Error Response Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Shows examples of inconsistent error response formats in API v1. Some responses include a status and message, while others may only return an HTTP status code. ```json { "status": 401, "message": "Unauthorized" } // or sometimes just HTTP status without body ``` -------------------------------- ### Configure Pushover API Keys Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/messaging-subsystem-audit.md Sets up Pushover API keys from environment variables, including user keys, alarm keys, and announcement keys. Supports fallback to a default user key. ```javascript var pushoverAPI = { userKeys: env.extendedSettings.pushover.userKey.split(' '), alarmKeys: (env.extendedSettings.pushover.alarmKey || userKey).split(' '), announcementKeys: (env.extendedSettings.pushover.announcementKey || userKey).split(' '), apiToken: env.extendedSettings.pushover.apiToken }; function selectKeys(notify) { if (notify.isAnnouncement) { return pushoverAPI.announcementKeys; } else if (ctx.levels.isAlarm(notify.level)) { return pushoverAPI.alarmKeys; } return pushoverAPI.userKeys; } ``` -------------------------------- ### Basic Deployment Logging Configuration Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/api-query-normalization.md Configuration for basic deployments using console JSON logs, which can be piped to files or analyzed with tools like grep and jq. ```bash # Console JSON logs are sufficient # Can be piped to file: node server.js 2>&1 | tee /var/log/nightscout.log # grep/jq analysis: grep query_violation /var/log/nightscout.log | jq '.violation' ``` -------------------------------- ### Refactor Callback to Async/Await Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Convert callback-based asynchronous operations to use async/await syntax for improved readability and error handling. This example shows the transformation of setupStorage. ```javascript // Before function setupStorage(ctx, next) { require('../storage/mongo-storage')(env, function(err, store) { if (err) { ctx.bootErrors.push({ err }); } ctx.store = store; next(); }); } // After async function setupStorage(ctx) { try { ctx.store = await require('../storage/mongo-storage')(env); } catch (err) { ctx.bootErrors.push({ err }); } } ``` -------------------------------- ### Run Baseline Tests Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/mongodb-modernization-implementation-plan.md Commands to run all existing tests and record the results to establish a baseline before migration. ```bash npm test > baseline-test-results.txt 2>&1 ``` -------------------------------- ### Fallback Deduplication Logic Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/data-layer-audit.md These are fallback deduplication logic examples for entries and treatments in API v3. ```javascript // Fallback dedup for entries { date: doc.date, type: doc.type, app: doc.app } ``` ```javascript // Fallback dedup for treatments { created_at: doc.created_at, eventType: doc.eventType } ``` -------------------------------- ### Feature Flag Implementation Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Shows how to use environment variables to control feature availability. This example demonstrates conditionally applying middleware based on feature flags, enabling gradual rollouts and easy rollback. ```javascript const features = { USE_NEW_AUTH: process.env.FEATURE_NEW_AUTH === 'true', USE_REDIS_CACHE: process.env.FEATURE_REDIS_CACHE === 'true', USE_VUE_COMPONENTS: process.env.FEATURE_VUE === 'true' }; if (features.USE_NEW_AUTH) { app.use('/api', newAuthMiddleware); } else { app.use('/api', legacyAuthMiddleware); } ``` -------------------------------- ### Clear Alarm Data Structure Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/alarmsockets.md Example JSON structure for a 'clear_alarm' event, indicating that an alarm has been resolved. ```json { "clear":true, "title":"All Clear", "message":"default - Urgent was ack\'d", "group":"default" } ``` -------------------------------- ### Test File Structure Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/TEST-IMPLEMENTATION-SUMMARY.md Illustrates the structure of a typical Mocha test file, including describe blocks for different test suites and scenarios. This helps in understanding how tests are organized. ```javascript // tests/api.v1-batch-operations.test.js describe('v1 API Batch Operations - MongoDB Modernization', function() { describe('Batch Insert Semantics (Section 6.1.1)', function() { // 5 tests covering Loop, Trio, edge cases }); describe('Large Batch Operations (Section 2.2)', function() { // 1 test for 100-item batch }); describe('Response Format (Section 6.1.2)', function() { // 1 test validating _id in response }); describe('Trio Pipeline Scenarios (Section 3)', function() { // 2 tests for Trio patterns }); describe('Mixed Valid/Invalid Documents (Section 4.6)', function() { // 1 test (currently skipped) }); }); ``` -------------------------------- ### API v1 Authentication Header Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of authenticating API v1 requests using an 'api-secret' header. ```http GET /api/v1/entries api-secret: your-api-secret ``` -------------------------------- ### Storage Socket Subscription Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of subscribing to collections via the Storage Socket, providing an access token. ```javascript const socket = io('https://example.com/storage'); socket.emit('subscribe', { accessToken: 'mytoken-abc123', collections: ['entries', 'treatments'] }, callback); ``` -------------------------------- ### Bolus Calculation Profile Specification Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/plugins/example-profiles.md Example of how the profile used for bolus calculation is specified via a key. ```json { eventType: "Profile Change" , profile: "2-Weekend" } ``` -------------------------------- ### Source Local Test Environment and Run Tests Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/CONTRIBUTING.md Load environment variables from a local file and then execute the test suite. This is useful for custom local testing configurations. ```bash source my.test.env && npm test ``` -------------------------------- ### Profile Change Treatment Record Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/plugins/example-profiles.md Example of a treatment record used to specify the active profile for basals. ```json { eventType: "Profile Change" , profile: "2-Weekend" } ``` -------------------------------- ### Check Current MongoDB Version Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/IMPLEMENTATION-QUICKSTART.md List installed MongoDB driver versions and save the output to a file. ```bash npm list mongodb mongodb-legacy > mongodb-versions.txt ``` ```bash cat mongodb-versions.txt ``` -------------------------------- ### Replace Moment.js with Day.js Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/meta/modernization-roadmap.md Demonstrates replacing Moment.js with Day.js for date formatting to reduce bundle size. Ensure to extend Day.js with necessary plugins like utc and timezone. ```javascript // Before const moment = require('moment-timezone'); moment(date).format('HH:mm'); // After const dayjs = require('dayjs'); const utc = require('dayjs/plugin/utc'); const timezone = require('dayjs/plugin/timezone'); dayjs.extend(utc); dayjs.extend(timezone); dayjs(date).format('HH:mm'); ``` -------------------------------- ### Alarm Socket Subscription Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/api-layer-audit.md Example of subscribing to alarm notifications via the Alarm Socket, providing an access token. ```javascript const socket = io('https://example.com/alarm'); socket.emit('subscribe', { accessToken: 'mytoken-abc123' }, callback); ``` -------------------------------- ### Client Bundle Entry Point Imports Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/dashboard-ui-audit.md Imports CSS files and JavaScript modules for the client bundle. Includes jQuery, lodash, D3.js, jQuery UI, and js-storage. ```javascript import '../static/css/drawer.css'; import '../static/css/dropdown.css'; import '../static/css/sgv.css'; $ = require("jquery"); require('jquery-ui-bundle'); window._ = require('lodash'); window.d3 = require('d3'); require('jquery.tooltips'); window.Storage = require('js-storage'); require('flot'); require('../node_modules/flot/jquery.flot.time'); ``` -------------------------------- ### Get API Version Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/tutorial.md Retrieves basic information about the software packages versions. This operation is public and does not require authorization. ```APIDOC ## GET /version ### Description Gets basic information about software packages versions. ### Method GET ### Endpoint /api/v3/version ### Response #### Success Response (200) - **version** (string) - The software version. - **apiVersion** (string) - The API version. - **srvDate** (number) - Server date as a timestamp. - **storage** (object) - Storage information. - **storage** (string) - Storage type. - **version** (string) - Storage version. ### Request Example ```javascript const axios = require('axios'); axios.get(`https://nsapiv3.herokuapp.com/api/v3/version`) .then(res => { console.log(res.data); }); ``` ### Response Example ```json { "status": 200, "result": { "version": "14.2.0", "apiVersion": "3.0.4-alpha", "srvDate": 1613056980085, "storage": { "storage": "mongodb", "version": "4.4.3" } } } ``` ``` -------------------------------- ### Register Server Default Plugins Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/plugin-architecture-audit.md This code registers default server plugins during the application's boot process. It requires the context object containing settings, language, levels, and moment.js. ```javascript ctx.plugins = require('../plugins')({ settings: env.settings, language: ctx.language, levels: ctx.levels, moment: ctx.moment }).registerServerDefaults(); ``` -------------------------------- ### Readable Permissions Default Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/requirements/api-v1-compatibility-requirements.md Details authentication requirements for GET, POST, PUT, and DELETE endpoints based on 'authDefaultRoles'. ```APIDOC ### COMPAT-010: Readable Permissions Default When `authDefaultRoles` includes `readable`: - GET endpoints should be accessible without authentication - POST/PUT/DELETE require valid authentication ``` -------------------------------- ### Event Bus Communication Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/audits/security-audit.md Demonstrates basic event emission and listening on the Node.js Stream-based event bus. Note the lack of authentication, authorization, encryption, and rate limiting. ```javascript var stream = new Stream; stream.emit('notification', notify); ctx.bus.on('data-update', handler); ``` -------------------------------- ### Virtual Assistant Configuration for Plugin Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/plugins/add-virtual-assistant-support-to-plugin.md Configure virtual assistant support by returning an object with a `virtAsst` key from the plugin's `init` method. This object should contain `intentHandlers` and `rollupHandlers` arrays. ```javascript iob.virtAsst = { intentHandlers: [{ intent: "MetricNow" , metrics: ["iob"] , intentHandler: virtAsstIOBIntentHandler }] , rollupHandlers: [{ rollupGroup: "Status" , rollupName: "current iob" , rollupHandler: virtAsstIOBRollupHandler }] }; ``` -------------------------------- ### Example Delegated Token Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/docs/proposals/oidc-actor-identity-proposal.md Demonstrates a JSON Web Token (JWT) with standard and Nightscout-specific claims, including delegation information. ```json { "iss": "https://nrg.example.com", "sub": "patient-uuid-456", "ns:display_name": "Patient Jane", "ns:actor_type": "human", "act": { "sub": "clinic-staff-uuid", "ns:display_name": "Dr. Smith", "ns:actor_type": "human" }, "ns:permissions": ["api:treatments:create", "api:entries:read"] } ``` -------------------------------- ### JSON Output Example Source: https://github.com/nightscout/cgm-remote-monitor/blob/master/lib/api3/doc/formats.md Default JSON output for APIv3 requests. This format is used when no specific content type is requested. ```json { "status": 200, "result": [ { "type": "sgv", "sgv": "171", "dateString": "2014-07-19T02:44:15.000-07:00", "date": 1405763055000, "device": "dexcom", "direction": "Flat", "identifier": "5c5a2404e0196f4d3d9a718a", "srvModified": 1405763055000, "srvCreated": 1405763055000 }, { "type": "sgv", "sgv": "176", "dateString": "2014-07-19T03:09:15.000-07:00", "date": 1405764555000, "device": "dexcom", "direction": "Flat", "identifier": "5c5a2404e0196f4d3d9a7187", "srvModified": 1405764555000, "srvCreated": 1405764555000 } ] } ```