sugarsense-glucose-units 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sugar Sense (https://sugarsense.io)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # sugarsense-glucose-units
2
+
3
+ Blood glucose unit conversion (mg/dL to mmol/L and back), CGM trend arrows, glucose zone classification, time in range and GMI helpers. Zero dependencies, works in Node and every bundler, ships CommonJS, ESM and TypeScript types.
4
+
5
+ Extracted from [Sugar Sense](https://sugarsense.io), a CGM monitoring app for iOS, Apple Watch and Android that connects to FreeStyle Libre, Dexcom and [Nightscout](https://nightscout.github.io/) and shares glucose with family in real time. These are the exact conventions the app uses in production, published so other diabetes tools can reuse them instead of re-deriving the math.
6
+
7
+ > This library is informational only. It contains no insulin dosing logic and gives no medical advice.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install sugarsense-glucose-units
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```js
18
+ import {
19
+ mgdlToMmol,
20
+ formatGlucose,
21
+ trendArrow,
22
+ classifyZone,
23
+ timeInRange,
24
+ gmi,
25
+ isStale,
26
+ } from 'sugarsense-glucose-units';
27
+
28
+ mgdlToMmol(100); // 5.55
29
+ formatGlucose(120, 'mmol'); // '6.7' (display form, 1 decimal)
30
+ trendArrow(2); // '↘'
31
+ classifyZone(65); // 'low'
32
+ gmi(154); // 6.99 (approximates lab A1C, %)
33
+ isStale(readingMs); // true when older than 15 minutes
34
+
35
+ timeInRange([50, 60, 100, 150, 200, 300]);
36
+ // {
37
+ // total: 6,
38
+ // counts: { veryLow: 1, low: 1, inRange: 2, high: 1, veryHigh: 1 },
39
+ // percent: { veryLow: 16.7, low: 16.7, inRange: 33.3, high: 16.7, veryHigh: 16.7 }
40
+ // }
41
+ ```
42
+
43
+ CommonJS works the same way: `const units = require('sugarsense-glucose-units')`.
44
+
45
+ ## Conventions
46
+
47
+ These match the Sugar Sense production apps and backend:
48
+
49
+ - All math is done in **mg/dL**; mmol/L is a display conversion (factor `0.0555`, shown with 1 decimal).
50
+ - **Trend codes** are integers 1 to 5: `1 ↓ falling fast, 2 ↘ falling, 3 → steady, 4 ↗ rising, 5 ↑ rising fast` (the same scheme Dexcom, Libre and Nightscout data can be normalized to).
51
+ - **Zones**: `veryLow | low | inRange | high | veryHigh`, with boundaries inclusive on the out-of-range side (a value exactly at the low limit is `low`, exactly at the high limit is `high`).
52
+ - **Default thresholds** are `55 / 70 / 180 / 250` mg/dL (`DEFAULT_THRESHOLDS`), aligned with ADA guidance. Every function accepts custom thresholds.
53
+ - **Stale rule**: a reading older than 15 minutes should be treated as "no current data".
54
+
55
+ ## API
56
+
57
+ | Function | Description |
58
+ |---|---|
59
+ | `mgdlToMmol(mgdl)` | mg/dL to mmol/L, unrounded number |
60
+ | `mmolToMgdl(mmol)` | mmol/L to mg/dL, rounded to a whole number |
61
+ | `formatGlucose(mgdl, unit?)` | display string: `'mgdl'` whole number, `'mmol'` 1 decimal |
62
+ | `trendArrow(code)` / `trendName(code)` | arrow symbol / name for trend codes 1 to 5 |
63
+ | `classifyZone(mgdl, thresholds?)` | `'veryLow' \| 'low' \| 'inRange' \| 'high' \| 'veryHigh'` |
64
+ | `timeInRange(readings, thresholds?)` | five-band counts + percentages over an array of readings |
65
+ | `inRangePercent(readings, thresholds?)` | percent strictly inside the target band, `null` when empty |
66
+ | `gmi(meanMgdl)` | Glucose Management Indicator (Bergenstal et al., 2018) |
67
+ | `isStale(timeMs, nowMs?, staleMinutes?)` | staleness check, 15 min default |
68
+ | `MMOL_PER_MGDL`, `DEFAULT_THRESHOLDS`, `TREND_ARROWS`, `TREND_NAMES` | constants |
69
+
70
+ ## About Sugar Sense
71
+
72
+ [Sugar Sense](https://sugarsense.io) turns CGM data into real-time monitoring for the whole family: glucose on the lock screen and Apple Watch, low and high alerts, an automated emergency call on urgent lows, and a Care Circle so loved ones can follow along. There is also a [web dashboard](https://app.sugarsense.io) and a free [download page](https://sugarsense.io/download).
73
+
74
+ ## License
75
+
76
+ MIT
package/index.cjs ADDED
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ // Glucose unit and zone helpers, extracted from Sugar Sense (https://sugarsense.io).
4
+ // All internal math is mg/dL; mmol/L exists only as a display conversion.
5
+ // This library is informational only and contains no dosing logic.
6
+
7
+ const MMOL_PER_MGDL = 0.0555;
8
+
9
+ // ADA-aligned defaults used by Sugar Sense for new accounts (mg/dL).
10
+ const DEFAULT_THRESHOLDS = Object.freeze({
11
+ veryLow: 55,
12
+ low: 70,
13
+ high: 180,
14
+ veryHigh: 250,
15
+ });
16
+
17
+ // CGM trend codes: 1 falling fast, 2 falling, 3 steady, 4 rising, 5 rising fast.
18
+ const TREND_ARROWS = Object.freeze({ 1: '↓', 2: '↘', 3: '→', 4: '↗', 5: '↑' });
19
+ const TREND_NAMES = Object.freeze({
20
+ 1: 'fallingFast',
21
+ 2: 'falling',
22
+ 3: 'steady',
23
+ 4: 'rising',
24
+ 5: 'risingFast',
25
+ });
26
+
27
+ function assertFinite(value, name) {
28
+ const n = Number(value);
29
+ if (!Number.isFinite(n)) throw new TypeError(`${name} must be a finite number`);
30
+ return n;
31
+ }
32
+
33
+ function assertThresholds(t) {
34
+ const veryLow = assertFinite(t.veryLow, 'thresholds.veryLow');
35
+ const low = assertFinite(t.low, 'thresholds.low');
36
+ const high = assertFinite(t.high, 'thresholds.high');
37
+ const veryHigh = assertFinite(t.veryHigh, 'thresholds.veryHigh');
38
+ if (!(veryLow < low && low < high && high < veryHigh)) {
39
+ throw new RangeError('thresholds must satisfy veryLow < low < high < veryHigh');
40
+ }
41
+ return { veryLow, low, high, veryHigh };
42
+ }
43
+
44
+ // mg/dL -> mmol/L (unrounded). Use formatGlucose for the 1-decimal display form.
45
+ function mgdlToMmol(mgdl) {
46
+ return assertFinite(mgdl, 'mgdl') * MMOL_PER_MGDL;
47
+ }
48
+
49
+ // mmol/L -> mg/dL, rounded to the nearest whole number.
50
+ function mmolToMgdl(mmol) {
51
+ return Math.round(assertFinite(mmol, 'mmol') / MMOL_PER_MGDL);
52
+ }
53
+
54
+ // Display formatting identical to the Sugar Sense apps:
55
+ // mmol/L is shown with exactly 1 decimal, mg/dL as a whole number.
56
+ function formatGlucose(mgdl, unit = 'mgdl') {
57
+ const v = assertFinite(mgdl, 'mgdl');
58
+ if (unit === 'mmol') return (v * MMOL_PER_MGDL).toFixed(1);
59
+ if (unit === 'mgdl') return String(Math.round(v));
60
+ throw new RangeError("unit must be 'mgdl' or 'mmol'");
61
+ }
62
+
63
+ function trendArrow(code) {
64
+ return TREND_ARROWS[code] || '';
65
+ }
66
+
67
+ function trendName(code) {
68
+ return TREND_NAMES[code] || '';
69
+ }
70
+
71
+ // Zone boundaries are inclusive on the out-of-range side:
72
+ // veryLow : value <= veryLow
73
+ // low : veryLow < value <= low
74
+ // inRange : low < value < high
75
+ // high : high <= value < veryHigh
76
+ // veryHigh: value >= veryHigh
77
+ function classifyZone(mgdl, thresholds = DEFAULT_THRESHOLDS) {
78
+ const v = assertFinite(mgdl, 'mgdl');
79
+ const t = assertThresholds(thresholds);
80
+ if (v >= t.veryHigh) return 'veryHigh';
81
+ if (v <= t.veryLow) return 'veryLow';
82
+ if (v >= t.high) return 'high';
83
+ if (v <= t.low) return 'low';
84
+ return 'inRange';
85
+ }
86
+
87
+ // Five-band distribution over an array of mg/dL values (numbers or {value}).
88
+ // Percentages sum to ~100; empty input returns zero counts and percentages.
89
+ function timeInRange(readings, thresholds = DEFAULT_THRESHOLDS) {
90
+ const t = assertThresholds(thresholds);
91
+ const counts = { veryLow: 0, low: 0, inRange: 0, high: 0, veryHigh: 0 };
92
+ for (const r of readings) {
93
+ const v = typeof r === 'object' && r !== null ? r.value : r;
94
+ counts[classifyZone(v, t)]++;
95
+ }
96
+ const total = readings.length;
97
+ const pct = (c) => (total === 0 ? 0 : (c / total) * 100);
98
+ return {
99
+ total,
100
+ counts,
101
+ percent: {
102
+ veryLow: pct(counts.veryLow),
103
+ low: pct(counts.low),
104
+ inRange: pct(counts.inRange),
105
+ high: pct(counts.high),
106
+ veryHigh: pct(counts.veryHigh),
107
+ },
108
+ };
109
+ }
110
+
111
+ // Percent of readings strictly inside the target band (edges are out of range).
112
+ // Returns null for empty input.
113
+ function inRangePercent(readings, thresholds = DEFAULT_THRESHOLDS) {
114
+ const t = assertThresholds(thresholds);
115
+ if (readings.length === 0) return null;
116
+ let inRange = 0;
117
+ for (const r of readings) {
118
+ const v = assertFinite(typeof r === 'object' && r !== null ? r.value : r, 'reading');
119
+ if (v > t.low && v < t.high) inRange++;
120
+ }
121
+ return (inRange / readings.length) * 100;
122
+ }
123
+
124
+ // Glucose Management Indicator (approximates lab A1C, %) from mean mg/dL.
125
+ // International consensus formula (Bergenstal et al., 2018).
126
+ function gmi(meanMgdl) {
127
+ return 3.31 + 0.02392 * assertFinite(meanMgdl, 'meanMgdl');
128
+ }
129
+
130
+ // A reading older than staleMinutes (default 15, the Sugar Sense rule) is stale
131
+ // and should be presented as "no current data". Timestamps in epoch ms.
132
+ function isStale(readingTimeMs, nowMs = Date.now(), staleMinutes = 15) {
133
+ const ts = assertFinite(readingTimeMs, 'readingTimeMs');
134
+ const now = assertFinite(nowMs, 'nowMs');
135
+ return now - ts > staleMinutes * 60 * 1000;
136
+ }
137
+
138
+ module.exports = {
139
+ MMOL_PER_MGDL,
140
+ DEFAULT_THRESHOLDS,
141
+ TREND_ARROWS,
142
+ TREND_NAMES,
143
+ mgdlToMmol,
144
+ mmolToMgdl,
145
+ formatGlucose,
146
+ trendArrow,
147
+ trendName,
148
+ classifyZone,
149
+ timeInRange,
150
+ inRangePercent,
151
+ gmi,
152
+ isStale,
153
+ };
package/index.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ export declare const MMOL_PER_MGDL: number;
2
+
3
+ export interface Thresholds {
4
+ veryLow: number;
5
+ low: number;
6
+ high: number;
7
+ veryHigh: number;
8
+ }
9
+
10
+ export declare const DEFAULT_THRESHOLDS: Readonly<Thresholds>;
11
+
12
+ export type TrendCode = 1 | 2 | 3 | 4 | 5;
13
+ export declare const TREND_ARROWS: Readonly<Record<TrendCode, string>>;
14
+ export declare const TREND_NAMES: Readonly<Record<TrendCode, string>>;
15
+
16
+ export type Zone = 'veryLow' | 'low' | 'inRange' | 'high' | 'veryHigh';
17
+
18
+ export type Reading = number | { value: number };
19
+
20
+ export interface TimeInRangeResult {
21
+ total: number;
22
+ counts: Record<Zone, number>;
23
+ percent: Record<Zone, number>;
24
+ }
25
+
26
+ export declare function mgdlToMmol(mgdl: number): number;
27
+ export declare function mmolToMgdl(mmol: number): number;
28
+ export declare function formatGlucose(mgdl: number, unit?: 'mgdl' | 'mmol'): string;
29
+ export declare function trendArrow(code: number): string;
30
+ export declare function trendName(code: number): string;
31
+ export declare function classifyZone(mgdl: number, thresholds?: Thresholds): Zone;
32
+ export declare function timeInRange(readings: Reading[], thresholds?: Thresholds): TimeInRangeResult;
33
+ export declare function inRangePercent(readings: Reading[], thresholds?: Thresholds): number | null;
34
+ export declare function gmi(meanMgdl: number): number;
35
+ export declare function isStale(readingTimeMs: number, nowMs?: number, staleMinutes?: number): boolean;
package/index.mjs ADDED
@@ -0,0 +1,20 @@
1
+ import m from './index.cjs';
2
+
3
+ export const {
4
+ MMOL_PER_MGDL,
5
+ DEFAULT_THRESHOLDS,
6
+ TREND_ARROWS,
7
+ TREND_NAMES,
8
+ mgdlToMmol,
9
+ mmolToMgdl,
10
+ formatGlucose,
11
+ trendArrow,
12
+ trendName,
13
+ classifyZone,
14
+ timeInRange,
15
+ inRangePercent,
16
+ gmi,
17
+ isStale,
18
+ } = m;
19
+
20
+ export default m;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "sugarsense-glucose-units",
3
+ "version": "0.1.0",
4
+ "description": "Blood glucose unit conversion (mg/dL to mmol/L), CGM trend arrows, glucose zone classification, time in range and GMI helpers. Zero dependencies. Extracted from the Sugar Sense CGM monitoring app.",
5
+ "keywords": [
6
+ "glucose",
7
+ "blood-glucose",
8
+ "diabetes",
9
+ "cgm",
10
+ "mmol",
11
+ "mgdl",
12
+ "time-in-range",
13
+ "gmi",
14
+ "dexcom",
15
+ "freestyle-libre",
16
+ "nightscout"
17
+ ],
18
+ "homepage": "https://sugarsense.io",
19
+ "bugs": {
20
+ "email": "info@sugarsense.io"
21
+ },
22
+ "license": "MIT",
23
+ "author": "Sugar Sense (https://sugarsense.io)",
24
+ "type": "commonjs",
25
+ "main": "./index.cjs",
26
+ "types": "./index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./index.d.ts",
30
+ "import": "./index.mjs",
31
+ "require": "./index.cjs"
32
+ }
33
+ },
34
+ "files": [
35
+ "index.cjs",
36
+ "index.mjs",
37
+ "index.d.ts",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "scripts": {
42
+ "test": "node --test"
43
+ },
44
+ "engines": {
45
+ "node": ">=18"
46
+ }
47
+ }