@adminide-stack/yantra-mobile 12.0.103-alpha.0 → 12.0.103-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/lib/components/CustomDrawer.js +4 -2
  2. package/lib/components/CustomDrawer.js.map +1 -1
  3. package/lib/features/expenses/ExpensesExperience.js +11 -1
  4. package/lib/features/expenses/ExpensesExperience.js.map +1 -1
  5. package/lib/features/expenses/components/ClaimForm.js +144 -23
  6. package/lib/features/expenses/components/ClaimForm.js.map +1 -1
  7. package/lib/features/expenses/receiptScan.js +36 -5
  8. package/lib/features/expenses/receiptScan.js.map +1 -1
  9. package/lib/features/expenses/starterCategories.js +7 -0
  10. package/lib/features/expenses/starterCategories.js.map +1 -0
  11. package/lib/features/health/HealthSyncRunner.js +13 -13
  12. package/lib/features/health/HealthSyncRunner.js.map +1 -1
  13. package/lib/features/health/buildDays.js +188 -113
  14. package/lib/features/health/buildDays.js.map +1 -1
  15. package/lib/features/health/fitnessClient.js +5 -5
  16. package/lib/features/health/fitnessClient.js.map +1 -1
  17. package/lib/features/health/healthConnectMapping.js +57 -29
  18. package/lib/features/health/healthConnectMapping.js.map +1 -1
  19. package/lib/features/health/healthConnectReader.js +23 -5
  20. package/lib/features/health/healthConnectReader.js.map +1 -1
  21. package/lib/features/health/healthSyncStore.js +5 -1
  22. package/lib/features/health/healthSyncStore.js.map +1 -1
  23. package/lib/features/health/healthkitMapping.js +115 -25
  24. package/lib/features/health/healthkitMapping.js.map +1 -1
  25. package/lib/features/health/healthkitReader.js +49 -39
  26. package/lib/features/health/healthkitReader.js.map +1 -1
  27. package/lib/features/health/healthkitWriter.js +3 -6
  28. package/lib/features/health/healthkitWriter.js.map +1 -1
  29. package/lib/features/health/hostHealth.js +3 -1
  30. package/lib/features/health/hostHealth.js.map +1 -1
  31. package/lib/features/health/intraday.js +115 -0
  32. package/lib/features/health/intraday.js.map +1 -0
  33. package/lib/features/health/model.js +3 -0
  34. package/lib/features/health/model.js.map +1 -1
  35. package/lib/features/health/reader.js +15 -0
  36. package/lib/features/health/reader.js.map +1 -1
  37. package/lib/features/health/sleep.js +59 -3
  38. package/lib/features/health/sleep.js.map +1 -1
  39. package/lib/features/health/syncEngine.js +35 -31
  40. package/lib/features/health/syncEngine.js.map +1 -1
  41. package/lib/features/health/syncState.js.map +1 -1
  42. package/lib/features/health/time.js +52 -52
  43. package/lib/features/health/time.js.map +1 -1
  44. package/lib/features/health/types.js +21 -4
  45. package/lib/features/health/types.js.map +1 -1
  46. package/lib/features/health/writeMapping.js +12 -12
  47. package/lib/features/health/writeMapping.js.map +1 -1
  48. package/lib/features/health/zones.js +1 -2
  49. package/lib/features/health/zones.js.map +1 -1
  50. package/lib/features/messaging/ActionSheet.js +104 -0
  51. package/lib/features/messaging/ActionSheet.js.map +1 -0
  52. package/lib/features/messaging/ChatAttachments.js +2 -6
  53. package/lib/features/messaging/ChatAttachments.js.map +1 -1
  54. package/lib/features/messaging/ChatComponents.js +512 -244
  55. package/lib/features/messaging/ChatComponents.js.map +1 -1
  56. package/lib/features/messaging/ChatInfoScreen.js +314 -0
  57. package/lib/features/messaging/ChatInfoScreen.js.map +1 -0
  58. package/lib/features/messaging/ContactsScreen.js +28 -11
  59. package/lib/features/messaging/ContactsScreen.js.map +1 -1
  60. package/lib/features/messaging/ConversationListScreen.js +274 -14
  61. package/lib/features/messaging/ConversationListScreen.js.map +1 -1
  62. package/lib/features/messaging/ForwardScreen.js +203 -0
  63. package/lib/features/messaging/ForwardScreen.js.map +1 -0
  64. package/lib/features/messaging/InviteSheet.js +43 -39
  65. package/lib/features/messaging/InviteSheet.js.map +1 -1
  66. package/lib/features/messaging/LinkPreviewCard.js +52 -24
  67. package/lib/features/messaging/LinkPreviewCard.js.map +1 -1
  68. package/lib/features/messaging/MessageActions.js +11 -15
  69. package/lib/features/messaging/MessageActions.js.map +1 -1
  70. package/lib/features/messaging/MessageInfoScreen.js +218 -0
  71. package/lib/features/messaging/MessageInfoScreen.js.map +1 -0
  72. package/lib/features/messaging/NativeChatExperience.js +248 -28
  73. package/lib/features/messaging/NativeChatExperience.js.map +1 -1
  74. package/lib/features/messaging/NotificationSettingsScreen.js +288 -0
  75. package/lib/features/messaging/NotificationSettingsScreen.js.map +1 -0
  76. package/lib/features/messaging/StarredMessagesScreen.js +161 -0
  77. package/lib/features/messaging/StarredMessagesScreen.js.map +1 -0
  78. package/lib/features/messaging/TapRow.js +46 -0
  79. package/lib/features/messaging/TapRow.js.map +1 -0
  80. package/lib/features/messaging/ThreadScreen.js +704 -81
  81. package/lib/features/messaging/ThreadScreen.js.map +1 -1
  82. package/lib/features/messaging/chatModel.js +217 -11
  83. package/lib/features/messaging/chatModel.js.map +1 -1
  84. package/lib/features/messaging/chatNotificationPrefs.js +47 -0
  85. package/lib/features/messaging/chatNotificationPrefs.js.map +1 -0
  86. package/lib/features/messaging/chatOperations.js +102 -2
  87. package/lib/features/messaging/chatOperations.js.map +1 -1
  88. package/lib/features/messaging/chatPushToken.js +25 -0
  89. package/lib/features/messaging/chatPushToken.js.map +1 -0
  90. package/lib/features/messaging/nativeChatChannelQuery.js.map +1 -1
  91. package/lib/features/messaging/useChatData.js +364 -15
  92. package/lib/features/messaging/useChatData.js.map +1 -1
  93. package/lib/features/messaging/usePressed.js +8 -0
  94. package/lib/features/messaging/usePressed.js.map +1 -0
  95. package/lib/index.js +1 -1
  96. package/lib/index.js.map +1 -1
  97. package/lib/screens/ChatNative/index.js +2 -1
  98. package/lib/screens/ChatNative/index.js.map +1 -1
  99. package/lib/screens/Health/index.js +20 -5
  100. package/lib/screens/Health/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -14,6 +14,48 @@ var __spreadValues = (a, b) => {
14
14
  }
15
15
  return a;
16
16
  };
17
+ const HK_READ_TYPES = {
18
+ steps: ["HKQuantityTypeIdentifierStepCount"],
19
+ distance: ["HKQuantityTypeIdentifierDistanceWalkingRunning"],
20
+ activeCalories: ["HKQuantityTypeIdentifierActiveEnergyBurned"],
21
+ restingCalories: ["HKQuantityTypeIdentifierBasalEnergyBurned"],
22
+ exercise: ["HKQuantityTypeIdentifierAppleExerciseTime"],
23
+ heartRate: ["HKQuantityTypeIdentifierHeartRate"],
24
+ restingHr: ["HKQuantityTypeIdentifierRestingHeartRate"],
25
+ hrv: ["HKQuantityTypeIdentifierHeartRateVariabilitySDNN"],
26
+ sleep: ["HKCategoryTypeIdentifierSleepAnalysis"],
27
+ wristTemp: ["HKQuantityTypeIdentifierAppleSleepingWristTemperature"],
28
+ workouts: ["HKWorkoutTypeIdentifier"],
29
+ daylight: ["HKQuantityTypeIdentifierTimeInDaylight"],
30
+ mindful: ["HKCategoryTypeIdentifierMindfulSession"],
31
+ weight: ["HKQuantityTypeIdentifierBodyMass"],
32
+ vo2Max: ["HKQuantityTypeIdentifierVO2Max"],
33
+ spo2: ["HKQuantityTypeIdentifierOxygenSaturation"],
34
+ respiratoryRate: ["HKQuantityTypeIdentifierRespiratoryRate"],
35
+ bodyFat: ["HKQuantityTypeIdentifierBodyFatPercentage"],
36
+ leanMass: ["HKQuantityTypeIdentifierLeanBodyMass"],
37
+ bmi: ["HKQuantityTypeIdentifierBodyMassIndex"],
38
+ waist: ["HKQuantityTypeIdentifierWaistCircumference"],
39
+ bodyTemp: ["HKQuantityTypeIdentifierBodyTemperature"],
40
+ bloodPressure: ["HKQuantityTypeIdentifierBloodPressureSystolic", "HKQuantityTypeIdentifierBloodPressureDiastolic"],
41
+ bloodGlucose: ["HKQuantityTypeIdentifierBloodGlucose"]
42
+ };
43
+ const HK_MIN_IOS = {
44
+ wristTemp: 16,
45
+ daylight: 17
46
+ };
47
+ function hkReadTypes(iosMajor) {
48
+ return Object.keys(HK_READ_TYPES).filter((t) => {
49
+ var _a;
50
+ return iosMajor >= ((_a = HK_MIN_IOS[t]) != null ? _a : 0);
51
+ });
52
+ }
53
+ function hkIdentifiers(types) {
54
+ return [...new Set(types.flatMap((t) => {
55
+ var _a;
56
+ return (_a = HK_READ_TYPES[t]) != null ? _a : [];
57
+ }))];
58
+ }
17
59
  const HK_SLEEP_STAGE = {
18
60
  0: "inBed",
19
61
  1: "asleep",
@@ -27,13 +69,14 @@ function hkSleepSegments(samples) {
27
69
  const out = [];
28
70
  for (const s of samples) {
29
71
  const stage = HK_SLEEP_STAGE[s.value];
30
- if (!stage) continue;
31
- out.push({
32
- start: s.startDate.getTime(),
33
- end: s.endDate.getTime(),
34
- stage,
35
- sourceKey: ((_b = (_a = s.sourceRevision) == null ? void 0 : _a.source) == null ? void 0 : _b.bundleIdentifier) || ((_d = (_c = s.sourceRevision) == null ? void 0 : _c.source) == null ? void 0 : _d.name) || "unknown"
36
- });
72
+ if (stage) {
73
+ out.push({
74
+ start: s.startDate.getTime(),
75
+ end: s.endDate.getTime(),
76
+ stage,
77
+ sourceKey: ((_b = (_a = s.sourceRevision) == null ? void 0 : _a.source) == null ? void 0 : _b.bundleIdentifier) || ((_d = (_c = s.sourceRevision) == null ? void 0 : _c.source) == null ? void 0 : _d.name) || "unknown"
78
+ });
79
+ }
37
80
  }
38
81
  return out;
39
82
  }
@@ -43,6 +86,18 @@ function hkValues(samples, transform = (v) => v) {
43
86
  value: transform(s.quantity)
44
87
  }));
45
88
  }
89
+ function hkValuesAtEnd(samples) {
90
+ return samples.filter((s) => Number.isFinite(s.quantity)).map((s) => ({
91
+ t: s.endDate.getTime(),
92
+ value: s.quantity
93
+ }));
94
+ }
95
+ function hkSpans(samples) {
96
+ return samples.map((s) => ({
97
+ start: s.startDate.getTime(),
98
+ end: s.endDate.getTime()
99
+ })).filter((s) => s.end > s.start);
100
+ }
46
101
  const hkSpo2Values = (samples) => hkValues(samples, fractionToPercent);
47
102
  const hkPercentValues = (samples) => hkValues(samples, fractionToPercent);
48
103
  function hkNotOwn(samples, ownBundleId) {
@@ -60,21 +115,25 @@ function hkBloodPressure(correlations) {
60
115
  const part = (type) => c.objects.find((o) => o.quantityType === type);
61
116
  const sys = part("HKQuantityTypeIdentifierBloodPressureSystolic");
62
117
  const dia = part("HKQuantityTypeIdentifierBloodPressureDiastolic");
63
- if (typeof (sys == null ? void 0 : sys.quantity) !== "number" || typeof (dia == null ? void 0 : dia.quantity) !== "number") continue;
64
- out.push({
65
- id: c.uuid,
66
- t: c.startDate.getTime(),
67
- systolic: toMmHg(sys.quantity, sys.unit),
68
- diastolic: toMmHg(dia.quantity, dia.unit)
69
- });
118
+ if (typeof (sys == null ? void 0 : sys.quantity) === "number" && typeof (dia == null ? void 0 : dia.quantity) === "number") {
119
+ out.push({
120
+ id: c.uuid,
121
+ t: c.startDate.getTime(),
122
+ systolic: toMmHg(sys.quantity, sys.unit),
123
+ diastolic: toMmHg(dia.quantity, dia.unit)
124
+ });
125
+ }
70
126
  }
71
127
  return out;
72
128
  }
129
+ const HK_MEAL = {
130
+ 1: "before-meal",
131
+ 2: "after-meal"
132
+ };
73
133
  function hkGlucose(samples) {
74
134
  return samples.filter((s) => Number.isFinite(s.quantity)).map((s) => {
75
135
  var _a, _b;
76
- const mealTime = Number((_a = s.metadata) == null ? void 0 : _a.HKMetadataKeyBloodGlucoseMealTime);
77
- const meal = mealTime === 1 ? "before-meal" : mealTime === 2 ? "after-meal" : void 0;
136
+ const meal = HK_MEAL[Number((_a = s.metadata) == null ? void 0 : _a.HKMetadataKeyBloodGlucoseMealTime)];
78
137
  return __spreadValues({
79
138
  id: (_b = s.uuid) != null ? _b : `hk-glucose-${s.startDate.getTime()}`,
80
139
  t: s.startDate.getTime(),
@@ -90,23 +149,52 @@ function hkDailyTotals(stats, clock) {
90
149
  var _a, _b;
91
150
  for (const b of buckets != null ? buckets : []) {
92
151
  const value = (_a = b.sumQuantity) == null ? void 0 : _a.quantity;
93
- if (!b.startDate || value === void 0 || !Number.isFinite(value)) continue;
94
- const date = clock.dateOf(b.startDate.getTime() + 6e4);
95
- const row = (_b = byDate.get(date)) != null ? _b : {
96
- date
97
- };
98
- row[field] = value;
99
- byDate.set(date, row);
152
+ if (b.startDate && value !== void 0 && Number.isFinite(value)) {
153
+ const date = clock.dateOf(b.startDate.getTime() + 6e4);
154
+ const row = (_b = byDate.get(date)) != null ? _b : {
155
+ date
156
+ };
157
+ row[field] = value;
158
+ byDate.set(date, row);
159
+ }
100
160
  }
101
161
  };
102
162
  put("steps", stats.steps);
103
163
  put("activeCalories", stats.activeCalories);
104
164
  put("distanceMeters", stats.distanceMeters);
105
165
  put("activeMinutes", stats.activeMinutes);
166
+ put("daylightMinutes", stats.daylightMinutes);
167
+ put("restingCalories", stats.restingCalories);
106
168
  return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));
107
169
  }
170
+ function hkStepSpans(buckets) {
171
+ var _a;
172
+ const out = [];
173
+ for (const b of buckets) {
174
+ const value = (_a = b.sumQuantity) == null ? void 0 : _a.quantity;
175
+ if (b.startDate && b.endDate && value !== void 0 && Number.isFinite(value)) {
176
+ out.push({
177
+ start: b.startDate.getTime(),
178
+ end: b.endDate.getTime(),
179
+ value
180
+ });
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+ function asQuantity(v) {
186
+ if (!v || typeof v !== "object") return void 0;
187
+ const {
188
+ quantity,
189
+ unit
190
+ } = v;
191
+ return typeof quantity === "number" && typeof unit === "string" ? {
192
+ quantity,
193
+ unit
194
+ } : void 0;
195
+ }
108
196
  function hkWorkout(w, stats = {}) {
109
- var _a, _b;
197
+ var _a, _b, _c;
110
198
  const out = {
111
199
  id: w.uuid,
112
200
  start: w.startDate.getTime(),
@@ -121,5 +209,7 @@ function hkWorkout(w, stats = {}) {
121
209
  if (distance !== void 0 && distance > 0) out.distanceMeters = distance;
122
210
  if (stats.avgHr !== void 0) out.avgHr = stats.avgHr;
123
211
  if (stats.maxHr !== void 0) out.maxHr = stats.maxHr;
212
+ const elevation = toMeters(asQuantity((_c = w.metadata) == null ? void 0 : _c.HKElevationAscended));
213
+ if (elevation !== void 0 && elevation >= 0) out.elevationMeters = elevation;
124
214
  return out;
125
- }export{hkBloodPressure,hkDailyTotals,hkGlucose,hkNotOwn,hkPercentValues,hkSleepSegments,hkSpo2Values,hkValues,hkWorkout};//# sourceMappingURL=healthkitMapping.js.map
215
+ }export{HK_READ_TYPES,hkBloodPressure,hkDailyTotals,hkGlucose,hkIdentifiers,hkNotOwn,hkPercentValues,hkReadTypes,hkSleepSegments,hkSpans,hkSpo2Values,hkStepSpans,hkValues,hkValuesAtEnd,hkWorkout};//# sourceMappingURL=healthkitMapping.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"healthkitMapping.js","sources":["../../../src/features/health/healthkitMapping.ts"],"sourcesContent":["/**\n * @kingstinct/react-native-healthkit records -> RawHealthData pieces.\n *\n * The input interfaces are the subset of the library's types this reads\n * (QuantitySample, CategorySample, QueryStatisticsResponse, WorkoutSample),\n * declared structurally so the mapping runs under jest without the native\n * module. Values are queried in fixed units (healthkitReader.ts), so only\n * the workout totals need unit conversion.\n */\nimport type {\n DailyTotals,\n RawBloodPressure,\n RawGlucose,\n RawWorkout,\n SleepSegment,\n SleepStage,\n TimedValue,\n} from './model';\nimport type { ZoneClock } from './time';\nimport { fractionToPercent, toKcal, toMeters, toMinutes, type UnitQuantity } from './units';\nimport { healthKitWorkoutType } from './workoutTypes';\n\nexport interface HKSourceLike {\n readonly source?: { readonly bundleIdentifier?: string; readonly name?: string };\n}\n\nexport interface HKQuantitySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly quantity: number;\n readonly unit?: string;\n readonly sourceRevision?: HKSourceLike;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport interface HKCorrelationLike {\n readonly uuid: string;\n readonly startDate: Date;\n readonly objects: ReadonlyArray<{\n readonly quantityType?: string;\n readonly quantity?: number;\n readonly unit?: string;\n }>;\n readonly sourceRevision?: HKSourceLike;\n}\n\nexport interface HKCategorySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly value: number;\n readonly sourceRevision?: HKSourceLike;\n}\n\nexport interface HKStatisticsLike {\n readonly startDate?: Date;\n readonly sumQuantity?: UnitQuantity;\n}\n\nexport interface HKWorkoutLike {\n readonly uuid: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly workoutActivityType: number;\n readonly duration?: UnitQuantity;\n readonly totalEnergyBurned?: UnitQuantity;\n readonly totalDistance?: UnitQuantity;\n}\n\n/** Per-workout statistics the reader asked HealthKit for in fixed units. */\nexport interface HKWorkoutStats {\n calories?: number;\n distanceMeters?: number;\n avgHr?: number;\n maxHr?: number;\n}\n\n/** HKCategoryValueSleepAnalysis raw values. */\nconst HK_SLEEP_STAGE: Record<number, SleepStage> = {\n 0: 'inBed',\n 1: 'asleep',\n 2: 'awake',\n 3: 'light',\n 4: 'deep',\n 5: 'rem',\n};\n\nexport function hkSleepSegments(samples: readonly HKCategorySampleLike[]): SleepSegment[] {\n const out: SleepSegment[] = [];\n for (const s of samples) {\n const stage = HK_SLEEP_STAGE[s.value];\n if (!stage) continue;\n out.push({\n start: s.startDate.getTime(),\n end: s.endDate.getTime(),\n stage,\n sourceKey: s.sourceRevision?.source?.bundleIdentifier || s.sourceRevision?.source?.name || 'unknown',\n });\n }\n return out;\n}\n\n/** Point-in-time values; an interval sample counts at its start. */\nexport function hkValues(\n samples: readonly HKQuantitySampleLike[],\n transform: (v: number) => number = (v) => v,\n): TimedValue[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => ({ t: s.startDate.getTime(), value: transform(s.quantity) }));\n}\n\nexport const hkSpo2Values = (samples: readonly HKQuantitySampleLike[]) => hkValues(samples, fractionToPercent);\n\n/** Body fat is a HealthKit percent, which is a fraction (0.231 for 23.1 %). */\nexport const hkPercentValues = (samples: readonly HKQuantitySampleLike[]) => hkValues(samples, fractionToPercent);\n\n/**\n * Everything not written by this app. Yantra's own samples are readings from a\n * paired device that the backend already has as source `device`.\n */\nexport function hkNotOwn<T extends { readonly sourceRevision?: HKSourceLike }>(\n samples: readonly T[],\n ownBundleId: string | undefined,\n): T[] {\n if (!ownBundleId) return [...samples];\n return samples.filter((s) => s.sourceRevision?.source?.bundleIdentifier !== ownBundleId);\n}\n\nconst KPA_TO_MMHG = 7.500617;\nconst toMmHg = (v: number, unit?: string) => (unit && /kpa/i.test(unit) ? v * KPA_TO_MMHG : v);\n\nexport function hkBloodPressure(correlations: readonly HKCorrelationLike[]): RawBloodPressure[] {\n const out: RawBloodPressure[] = [];\n for (const c of correlations) {\n const part = (type: string) => c.objects.find((o) => o.quantityType === type);\n const sys = part('HKQuantityTypeIdentifierBloodPressureSystolic');\n const dia = part('HKQuantityTypeIdentifierBloodPressureDiastolic');\n if (typeof sys?.quantity !== 'number' || typeof dia?.quantity !== 'number') continue;\n out.push({\n id: c.uuid,\n t: c.startDate.getTime(),\n systolic: toMmHg(sys.quantity, sys.unit),\n diastolic: toMmHg(dia.quantity, dia.unit),\n });\n }\n return out;\n}\n\n/** HKMetadataKeyBloodGlucoseMealTime: 1 before a meal, 2 after. */\nexport function hkGlucose(samples: readonly HKQuantitySampleLike[]): RawGlucose[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => {\n const mealTime = Number(s.metadata?.HKMetadataKeyBloodGlucoseMealTime);\n const meal = mealTime === 1 ? 'before-meal' : mealTime === 2 ? 'after-meal' : undefined;\n return {\n id: s.uuid ?? `hk-glucose-${s.startDate.getTime()}`,\n t: s.startDate.getTime(),\n mgdl: s.quantity,\n ...(meal ? { meal } : {}),\n } as RawGlucose;\n });\n}\n\nexport interface HKDailyStatistics {\n steps?: readonly HKStatisticsLike[];\n activeCalories?: readonly HKStatisticsLike[];\n distanceMeters?: readonly HKStatisticsLike[];\n activeMinutes?: readonly HKStatisticsLike[];\n}\n\n/**\n * Daily statistics-collection buckets (anchored at local midnight, one day\n * each) -> DailyTotals. HealthKit's statistics already merge phone + watch\n * without double counting, which summing raw samples would not.\n */\nexport function hkDailyTotals(stats: HKDailyStatistics, clock: ZoneClock): DailyTotals[] {\n const byDate = new Map<string, DailyTotals>();\n const put = (field: Exclude<keyof DailyTotals, 'date'>, buckets: readonly HKStatisticsLike[] | undefined) => {\n for (const b of buckets ?? []) {\n const value = b.sumQuantity?.quantity;\n if (!b.startDate || value === undefined || !Number.isFinite(value)) continue;\n // +1 min: a bucket starts AT local midnight; never let float/DST\n // rounding push it onto the previous date.\n const date = clock.dateOf(b.startDate.getTime() + 60_000);\n const row = byDate.get(date) ?? { date };\n row[field] = value;\n byDate.set(date, row);\n }\n };\n put('steps', stats.steps);\n put('activeCalories', stats.activeCalories);\n put('distanceMeters', stats.distanceMeters);\n put('activeMinutes', stats.activeMinutes);\n return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));\n}\n\nexport function hkWorkout(w: HKWorkoutLike, stats: HKWorkoutStats = {}): RawWorkout {\n const out: RawWorkout = {\n id: w.uuid,\n start: w.startDate.getTime(),\n end: w.endDate.getTime(),\n type: healthKitWorkoutType(w.workoutActivityType),\n };\n const duration = toMinutes(w.duration);\n if (duration !== undefined) out.durationMin = duration;\n const calories = stats.calories ?? toKcal(w.totalEnergyBurned);\n if (calories !== undefined) out.calories = calories;\n const distance = stats.distanceMeters ?? toMeters(w.totalDistance);\n if (distance !== undefined && distance > 0) out.distanceMeters = distance;\n if (stats.avgHr !== undefined) out.avgHr = stats.avgHr;\n if (stats.maxHr !== undefined) out.maxHr = stats.maxHr;\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAoEA,MAAM,cAA6C,GAAA;AAAA,EACjD,CAAG,EAAA,OAAA;AAAA,EACH,CAAG,EAAA,QAAA;AAAA,EACH,CAAG,EAAA,OAAA;AAAA,EACH,CAAG,EAAA,OAAA;AAAA,EACH,CAAG,EAAA,MAAA;AAAA,EACH,CAAG,EAAA;AACL,CAAA;AACO,SAAS,gBAAgB,OAA0D,EAAA;AA5E1F,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA;AA6EE,EAAA,MAAM,MAAsB,EAAC;AAC7B,EAAA,KAAA,MAAW,K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OAAA,CAAQ,OAAQ,EAAA;AAAA,IACvB,IAAA,EAAM,oBAAqB,CAAA,CAAA,CAAE,mBAAmB;AAAA,GAClD;AACA,EAAM,MAAA,QAAA,GAAW,SAAU,CAAA,CAAA,CAAE,QAAQ,CAAA;AACrC,EAAI,IAAA,QAAA,KAAa,MAAW,EAAA,GAAA,CAAI,WAAc,GAAA,QAAA;AAC9C,EAAA,MAAM,YAAW,EAAM,GAAA,KAAA,CAAA,QAAA,KAAN,IAAkB,GAAA,EAAA,GAAA,MAAA,CAAO,EAAE,iBAAiB,CAAA;AAC7D,EAAI,IAAA,QAAA,KAAa,MAAW,EAAA,GAAA,CAAI,QAAW,GAAA,QAAA;AAC3C,EAAA,MAAM,YAAW,EAAM,GAAA,KAAA,CAAA,cAAA,KAAN,IAAwB,GAAA,EAAA,GAAA,QAAA,CAAS,EAAE,aAAa,CAAA;AACjE,EAAA,IAAI,QAAa,KAAA,MAAA,IAAa,QAAW,GAAA,CAAA,MAAO,cAAiB,GAAA,QAAA;AACjE,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAO,OAAA,GAAA;AACT"}
1
+ {"version":3,"file":"healthkitMapping.js","sources":["../../../src/features/health/healthkitMapping.ts"],"sourcesContent":["/**\n * @kingstinct/react-native-healthkit records -> RawHealthData pieces, and the\n * HealthKit types each data type is read from.\n *\n * The input interfaces are the subset of the library's types this reads\n * (QuantitySample, CategorySample, QueryStatisticsResponse, WorkoutSample),\n * declared structurally so the mapping runs under jest without the native\n * module. Values are queried in fixed units (healthkitReader.ts), so only\n * the workout totals and metadata need unit conversion.\n */\nimport type { ObjectTypeIdentifier } from '@kingstinct/react-native-healthkit';\nimport type {\n DailyTotals,\n RawBloodPressure,\n RawGlucose,\n RawWorkout,\n SleepSegment,\n SleepStage,\n SpanValue,\n TimedValue,\n TimeSpan,\n} from './model';\nimport type { HealthDataType } from './reader';\nimport type { ZoneClock } from './time';\nimport type { MealRelation } from './types';\nimport { fractionToPercent, toKcal, toMeters, toMinutes, type UnitQuantity } from './units';\nimport { healthKitWorkoutType } from './workoutTypes';\n\n/**\n * The HealthKit types each data type is read from. Read access to a\n * correlation (blood pressure) is asked through its quantity types. Workout\n * elevation comes with the workout (its metadata), so it needs nothing more.\n */\nexport const HK_READ_TYPES: Partial<Record<HealthDataType, readonly ObjectTypeIdentifier[]>> = {\n steps: ['HKQuantityTypeIdentifierStepCount'],\n distance: ['HKQuantityTypeIdentifierDistanceWalkingRunning'],\n activeCalories: ['HKQuantityTypeIdentifierActiveEnergyBurned'],\n restingCalories: ['HKQuantityTypeIdentifierBasalEnergyBurned'],\n exercise: ['HKQuantityTypeIdentifierAppleExerciseTime'],\n heartRate: ['HKQuantityTypeIdentifierHeartRate'],\n restingHr: ['HKQuantityTypeIdentifierRestingHeartRate'],\n hrv: ['HKQuantityTypeIdentifierHeartRateVariabilitySDNN'],\n sleep: ['HKCategoryTypeIdentifierSleepAnalysis'],\n wristTemp: ['HKQuantityTypeIdentifierAppleSleepingWristTemperature'],\n workouts: ['HKWorkoutTypeIdentifier'],\n daylight: ['HKQuantityTypeIdentifierTimeInDaylight'],\n mindful: ['HKCategoryTypeIdentifierMindfulSession'],\n weight: ['HKQuantityTypeIdentifierBodyMass'],\n vo2Max: ['HKQuantityTypeIdentifierVO2Max'],\n spo2: ['HKQuantityTypeIdentifierOxygenSaturation'],\n respiratoryRate: ['HKQuantityTypeIdentifierRespiratoryRate'],\n bodyFat: ['HKQuantityTypeIdentifierBodyFatPercentage'],\n leanMass: ['HKQuantityTypeIdentifierLeanBodyMass'],\n bmi: ['HKQuantityTypeIdentifierBodyMassIndex'],\n waist: ['HKQuantityTypeIdentifierWaistCircumference'],\n bodyTemp: ['HKQuantityTypeIdentifierBodyTemperature'],\n bloodPressure: ['HKQuantityTypeIdentifierBloodPressureSystolic', 'HKQuantityTypeIdentifierBloodPressureDiastolic'],\n bloodGlucose: ['HKQuantityTypeIdentifierBloodGlucose'],\n};\n\n/** The first iOS version that has the type; an older one never asks for it or reads it. */\nconst HK_MIN_IOS: Partial<Record<HealthDataType, number>> = {\n wristTemp: 16,\n daylight: 17,\n};\n\n/** The data types read from Apple Health on this iOS major version. */\nexport function hkReadTypes(iosMajor: number): HealthDataType[] {\n return (Object.keys(HK_READ_TYPES) as HealthDataType[]).filter((t) => iosMajor >= (HK_MIN_IOS[t] ?? 0));\n}\n\n/** The HealthKit types to ask for, for some data types. */\nexport function hkIdentifiers(types: readonly HealthDataType[]): ObjectTypeIdentifier[] {\n return [...new Set(types.flatMap((t) => HK_READ_TYPES[t] ?? []))];\n}\n\nexport interface HKSourceLike {\n readonly source?: { readonly bundleIdentifier?: string; readonly name?: string };\n}\n\nexport interface HKQuantitySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly quantity: number;\n readonly unit?: string;\n readonly sourceRevision?: HKSourceLike;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\nexport interface HKCorrelationLike {\n readonly uuid: string;\n readonly startDate: Date;\n readonly objects: ReadonlyArray<{\n // Every object has one; it keeps a category object (no quantity) assignable.\n readonly uuid?: string;\n readonly quantityType?: string;\n readonly quantity?: number;\n readonly unit?: string;\n }>;\n readonly sourceRevision?: HKSourceLike;\n}\n\nexport interface HKCategorySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly value: number;\n readonly sourceRevision?: HKSourceLike;\n}\n\nexport interface HKStatisticsLike {\n readonly startDate?: Date;\n readonly endDate?: Date;\n readonly sumQuantity?: UnitQuantity;\n}\n\nexport interface HKWorkoutLike {\n readonly uuid: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly workoutActivityType: number;\n readonly duration?: UnitQuantity;\n readonly totalEnergyBurned?: UnitQuantity;\n readonly totalDistance?: UnitQuantity;\n /** HKElevationAscended (HKMetadataKeyElevationAscended) arrives here as { quantity, unit }. */\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Per-workout statistics the reader asked HealthKit for in fixed units. */\nexport interface HKWorkoutStats {\n calories?: number;\n distanceMeters?: number;\n avgHr?: number;\n maxHr?: number;\n}\n\n/** HKCategoryValueSleepAnalysis raw values. */\nconst HK_SLEEP_STAGE: Record<number, SleepStage> = {\n 0: 'inBed',\n 1: 'asleep',\n 2: 'awake',\n 3: 'light',\n 4: 'deep',\n 5: 'rem',\n};\n\nexport function hkSleepSegments(samples: readonly HKCategorySampleLike[]): SleepSegment[] {\n const out: SleepSegment[] = [];\n for (const s of samples) {\n const stage = HK_SLEEP_STAGE[s.value];\n if (stage) {\n out.push({\n start: s.startDate.getTime(),\n end: s.endDate.getTime(),\n stage,\n sourceKey: s.sourceRevision?.source?.bundleIdentifier || s.sourceRevision?.source?.name || 'unknown',\n });\n }\n }\n return out;\n}\n\n/** Point-in-time values; an interval sample counts at its start. */\nexport function hkValues(\n samples: readonly HKQuantitySampleLike[],\n transform: (v: number) => number = (v) => v,\n): TimedValue[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => ({ t: s.startDate.getTime(), value: transform(s.quantity) }));\n}\n\n/**\n * Values that describe the stretch they were measured over, at its END: the\n * sleeping wrist temperature covers a night and belongs to the date it ended.\n */\nexport function hkValuesAtEnd(samples: readonly HKQuantitySampleLike[]): TimedValue[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => ({ t: s.endDate.getTime(), value: s.quantity }));\n}\n\n/** Category samples whose length is the measurement (mindful sessions). */\nexport function hkSpans(samples: readonly HKCategorySampleLike[]): TimeSpan[] {\n return samples\n .map((s) => ({ start: s.startDate.getTime(), end: s.endDate.getTime() }))\n .filter((s) => s.end > s.start);\n}\n\nexport const hkSpo2Values = (samples: readonly HKQuantitySampleLike[]) => hkValues(samples, fractionToPercent);\n\n/** Body fat is a HealthKit percent, which is a fraction (0.231 for 23.1 %). */\nexport const hkPercentValues = (samples: readonly HKQuantitySampleLike[]) => hkValues(samples, fractionToPercent);\n\n/**\n * Everything not written by this app. Yantra's own samples are readings from a\n * paired device that the backend already has as source `device`.\n */\nexport function hkNotOwn<T extends { readonly sourceRevision?: HKSourceLike }>(\n samples: readonly T[],\n ownBundleId: string | undefined,\n): T[] {\n if (!ownBundleId) return [...samples];\n return samples.filter((s) => s.sourceRevision?.source?.bundleIdentifier !== ownBundleId);\n}\n\nconst KPA_TO_MMHG = 7.500617;\nconst toMmHg = (v: number, unit?: string) => (unit && /kpa/i.test(unit) ? v * KPA_TO_MMHG : v);\n\nexport function hkBloodPressure(correlations: readonly HKCorrelationLike[]): RawBloodPressure[] {\n const out: RawBloodPressure[] = [];\n for (const c of correlations) {\n const part = (type: string) => c.objects.find((o) => o.quantityType === type);\n const sys = part('HKQuantityTypeIdentifierBloodPressureSystolic');\n const dia = part('HKQuantityTypeIdentifierBloodPressureDiastolic');\n if (typeof sys?.quantity === 'number' && typeof dia?.quantity === 'number') {\n out.push({\n id: c.uuid,\n t: c.startDate.getTime(),\n systolic: toMmHg(sys.quantity, sys.unit),\n diastolic: toMmHg(dia.quantity, dia.unit),\n });\n }\n }\n return out;\n}\n\n/** HKMetadataKeyBloodGlucoseMealTime: 1 before a meal, 2 after. */\nconst HK_MEAL: Record<number, MealRelation | undefined> = { 1: 'before-meal', 2: 'after-meal' };\n\nexport function hkGlucose(samples: readonly HKQuantitySampleLike[]): RawGlucose[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => {\n const meal = HK_MEAL[Number(s.metadata?.HKMetadataKeyBloodGlucoseMealTime)];\n return {\n id: s.uuid ?? `hk-glucose-${s.startDate.getTime()}`,\n t: s.startDate.getTime(),\n mgdl: s.quantity,\n ...(meal ? { meal } : {}),\n } as RawGlucose;\n });\n}\n\nexport interface HKDailyStatistics {\n steps?: readonly HKStatisticsLike[];\n activeCalories?: readonly HKStatisticsLike[];\n distanceMeters?: readonly HKStatisticsLike[];\n activeMinutes?: readonly HKStatisticsLike[];\n daylightMinutes?: readonly HKStatisticsLike[];\n restingCalories?: readonly HKStatisticsLike[];\n}\n\n/**\n * Daily statistics-collection buckets (anchored at local midnight, one day\n * each) -> DailyTotals. HealthKit's statistics already merge phone + watch\n * without double counting, which summing raw samples would not.\n */\nexport function hkDailyTotals(stats: HKDailyStatistics, clock: ZoneClock): DailyTotals[] {\n const byDate = new Map<string, DailyTotals>();\n const put = (field: Exclude<keyof DailyTotals, 'date'>, buckets: readonly HKStatisticsLike[] | undefined) => {\n for (const b of buckets ?? []) {\n const value = b.sumQuantity?.quantity;\n if (b.startDate && value !== undefined && Number.isFinite(value)) {\n // +1 min: a bucket starts AT local midnight; never let float/DST\n // rounding push it onto the previous date.\n const date = clock.dateOf(b.startDate.getTime() + 60_000);\n const row = byDate.get(date) ?? { date };\n row[field] = value;\n byDate.set(date, row);\n }\n }\n };\n put('steps', stats.steps);\n put('activeCalories', stats.activeCalories);\n put('distanceMeters', stats.distanceMeters);\n put('activeMinutes', stats.activeMinutes);\n put('daylightMinutes', stats.daylightMinutes);\n put('restingCalories', stats.restingCalories);\n return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));\n}\n\n/**\n * Statistics-collection buckets (steps per quarter-hour) -> counts over each\n * bucket's span. HealthKit leaves out a bucket nothing was recorded in.\n */\nexport function hkStepSpans(buckets: readonly HKStatisticsLike[]): SpanValue[] {\n const out: SpanValue[] = [];\n for (const b of buckets) {\n const value = b.sumQuantity?.quantity;\n if (b.startDate && b.endDate && value !== undefined && Number.isFinite(value)) {\n out.push({ start: b.startDate.getTime(), end: b.endDate.getTime(), value });\n }\n }\n return out;\n}\n\nfunction asQuantity(v: unknown): UnitQuantity | undefined {\n if (!v || typeof v !== 'object') return undefined;\n const { quantity, unit } = v as { quantity?: unknown; unit?: unknown };\n return typeof quantity === 'number' && typeof unit === 'string' ? { quantity, unit } : undefined;\n}\n\nexport function hkWorkout(w: HKWorkoutLike, stats: HKWorkoutStats = {}): RawWorkout {\n const out: RawWorkout = {\n id: w.uuid,\n start: w.startDate.getTime(),\n end: w.endDate.getTime(),\n type: healthKitWorkoutType(w.workoutActivityType),\n };\n const duration = toMinutes(w.duration);\n if (duration !== undefined) out.durationMin = duration;\n const calories = stats.calories ?? toKcal(w.totalEnergyBurned);\n if (calories !== undefined) out.calories = calories;\n const distance = stats.distanceMeters ?? toMeters(w.totalDistance);\n if (distance !== undefined && distance > 0) out.distanceMeters = distance;\n if (stats.avgHr !== undefined) out.avgHr = stats.avgHr;\n if (stats.maxHr !== undefined) out.maxHr = stats.maxHr;\n const elevation = toMeters(asQuantity(w.metadata?.HKElevationAscended));\n if (elevation !== undefined && elevation >= 0) out.elevationMeters = elevation;\n return out;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAuBO,MAAM,aAAkF,GAAA;AAAA,EAC7F,KAAA,EAAO,CAAC,mCAAmC,CAAA;AAAA,EAC3C,QAAA,EAAU,CAAC,gDAAgD,CAAA;AAAA,EAC3D,cAAA,EAAgB,CAAC,4CAA4C,CAAA;AAAA,EAC7D,eAAA,EAAiB,CAAC,2CAA2C,CAAA;AAAA,EAC7D,QAAA,EAAU,CAAC,2CAA2C,CAAA;AAAA,EACtD,SAAA,EAAW,CAAC,mCAAmC,CAAA;AAAA,EAC/C,SAAA,EAAW,CAAC,0CAA0C,CAAA;AAAA,EACtD,GAAA,EAAK,CAAC,kDAAkD,CAAA;AAAA,EACxD,KAAA,EAAO,CAAC,uCAAuC,CAAA;AAAA,EAC/C,SAAA,EAAW,CAAC,uDAAuD,CAAA;AAAA,EACnE,QAAA,EAAU,CAAC,yBAAyB,CAAA;AAAA,EACpC,QAAA,EAAU,CAAC,wCAAwC,CAAA;AAAA,EACnD,OAAA,EAAS,CAAC,wCAAwC,CAAA;AAAA,EAClD,MAAA,EAAQ,CAAC,kCAAkC,CAAA;AAAA,EAC3C,MAAA,EAA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AAA,CAAA,MAAO,cAAiB,GAAA,QAAA;AACjE,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAA,MAAM,YAAY,QAAS,CAAA,UAAA,CAAA,CAAW,OAAE,QAAF,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAY,mBAAmB,CAAC,CAAA;AACtE,EAAA,IAAI,SAAc,KAAA,MAAA,IAAa,SAAa,IAAA,CAAA,MAAO,eAAkB,GAAA,SAAA;AACrE,EAAO,OAAA,GAAA;AACT"}
@@ -1,33 +1,26 @@
1
- import {getRequestStatusForAuthorization,AuthorizationRequestStatus,requestAuthorization,isHealthDataAvailableAsync,queryQuantitySamples,queryCorrelationSamples,queryCategorySamples,queryWorkoutSamples,queryStatisticsCollectionForQuantity}from'@kingstinct/react-native-healthkit';import {hkDailyTotals,hkValues,hkNotOwn,hkSpo2Values,hkPercentValues,hkGlucose,hkBloodPressure,hkSleepSegments,hkWorkout}from'./healthkitMapping.js';import {ownAppId}from'./ownSource.js';import {emptyRawHealthData}from'./model.js';class HealthAccessNeededError extends Error {
1
+ import {Platform}from'react-native';import {requestAuthorization,isHealthDataAvailableAsync,getRequestStatusForAuthorization,AuthorizationRequestStatus,queryQuantitySamples,queryStatisticsCollectionForQuantity,queryCorrelationSamples,queryCategorySamples,queryWorkoutSamples}from'@kingstinct/react-native-healthkit';import {hkReadTypes,hkIdentifiers,hkDailyTotals,hkStepSpans,hkValues,hkNotOwn,hkSpo2Values,hkPercentValues,hkValuesAtEnd,hkGlucose,hkBloodPressure,hkSleepSegments,hkSpans,hkWorkout}from'./healthkitMapping.js';import {ownAppId}from'./ownSource.js';import {emptyRawHealthData}from'./model.js';import {INTRADAY_BUCKET_MINUTES}from'./types.js';class HealthAccessNeededError extends Error {
2
2
  constructor() {
3
3
  super("Yantra needs to ask for access to Apple Health again.");
4
4
  this.name = "HealthAccessNeededError";
5
5
  }
6
6
  }
7
- const READ_TYPES = {
8
- steps: "HKQuantityTypeIdentifierStepCount",
9
- distance: "HKQuantityTypeIdentifierDistanceWalkingRunning",
10
- activeCalories: "HKQuantityTypeIdentifierActiveEnergyBurned",
11
- exercise: "HKQuantityTypeIdentifierAppleExerciseTime",
12
- heartRate: "HKQuantityTypeIdentifierHeartRate",
13
- restingHr: "HKQuantityTypeIdentifierRestingHeartRate",
14
- hrv: "HKQuantityTypeIdentifierHeartRateVariabilitySDNN",
15
- sleep: "HKCategoryTypeIdentifierSleepAnalysis",
16
- workouts: "HKWorkoutTypeIdentifier",
17
- weight: "HKQuantityTypeIdentifierBodyMass",
18
- vo2Max: "HKQuantityTypeIdentifierVO2Max",
19
- spo2: "HKQuantityTypeIdentifierOxygenSaturation",
20
- respiratoryRate: "HKQuantityTypeIdentifierRespiratoryRate",
21
- bodyFat: "HKQuantityTypeIdentifierBodyFatPercentage",
22
- leanMass: "HKQuantityTypeIdentifierLeanBodyMass",
23
- bmi: "HKQuantityTypeIdentifierBodyMassIndex",
24
- waist: "HKQuantityTypeIdentifierWaistCircumference",
25
- bodyTemp: "HKQuantityTypeIdentifierBodyTemperature",
26
- // Read access to a correlation is asked through its two quantity types.
27
- bloodPressure: "HKQuantityTypeIdentifierBloodPressureSystolic",
28
- bloodGlucose: "HKQuantityTypeIdentifierBloodGlucose"
29
- };
30
- const TO_READ = [...Object.values(READ_TYPES), "HKQuantityTypeIdentifierBloodPressureDiastolic"];
7
+ function iosMajor() {
8
+ const major = Number.parseInt(String(Platform.Version), 10);
9
+ return Number.isFinite(major) ? major : 0;
10
+ }
11
+ async function notAskedYet(types) {
12
+ const all = await getRequestStatusForAuthorization({
13
+ toRead: hkIdentifiers(types)
14
+ });
15
+ if (all !== AuthorizationRequestStatus.shouldRequest) return [];
16
+ const each = await Promise.all(types.map(async (type) => ({
17
+ type,
18
+ status: await getRequestStatusForAuthorization({
19
+ toRead: hkIdentifiers([type])
20
+ })
21
+ })));
22
+ return each.filter((x) => x.status === AuthorizationRequestStatus.shouldRequest).map((x) => x.type);
23
+ }
31
24
  const HR_CHUNK_MS = 864e5;
32
25
  async function attempt(type, unreadable, run) {
33
26
  try {
@@ -38,9 +31,12 @@ async function attempt(type, unreadable, run) {
38
31
  }
39
32
  }
40
33
  function createHealthKitReader() {
34
+ const types = hkReadTypes(iosMajor());
35
+ const toRead = hkIdentifiers(types);
41
36
  return {
42
37
  source: "apple-health",
43
38
  storeName: "Apple Health",
39
+ types,
44
40
  async availability() {
45
41
  try {
46
42
  return await isHealthDataAvailableAsync() ? {
@@ -58,7 +54,7 @@ function createHealthKitReader() {
58
54
  },
59
55
  async requestAccess() {
60
56
  await requestAuthorization({
61
- toRead: TO_READ
57
+ toRead
62
58
  });
63
59
  return null;
64
60
  },
@@ -67,11 +63,11 @@ function createHealthKitReader() {
67
63
  },
68
64
  async read(range, clock) {
69
65
  var _a;
70
- const status = await getRequestStatusForAuthorization({
71
- toRead: TO_READ
72
- });
73
- if (status === AuthorizationRequestStatus.shouldRequest) throw new HealthAccessNeededError();
66
+ const needsAccess = await notAskedYet(types);
67
+ if (needsAccess.length === types.length) throw new HealthAccessNeededError();
68
+ const skip = new Set(needsAccess);
74
69
  const unreadable = /* @__PURE__ */ new Set();
70
+ const tryRead = (type, run) => skip.has(type) || !types.includes(type) ? Promise.resolve(void 0) : attempt(type, unreadable, run);
75
71
  const raw = emptyRawHealthData("sdnn");
76
72
  const own = ownAppId("ios");
77
73
  const startDate = new Date(range.start);
@@ -80,7 +76,7 @@ function createHealthKitReader() {
80
76
  startDate,
81
77
  endDate
82
78
  };
83
- const samples = (type, id, unit, from = startDate, to = endDate) => attempt(type, unreadable, () => queryQuantitySamples(id, {
79
+ const samples = (type, id, unit, from = startDate, to = endDate) => tryRead(type, () => queryQuantitySamples(id, {
84
80
  limit: 0,
85
81
  ascending: true,
86
82
  unit,
@@ -99,30 +95,41 @@ function createHealthKitReader() {
99
95
  endDate
100
96
  }
101
97
  };
102
- const daily = (type, id, unit) => attempt(type, unreadable, () => queryStatisticsCollectionForQuantity(id, ["cumulativeSum"], anchor, {
98
+ const sums = (type, id, unit, interval = {
103
99
  day: 1
104
- }, {
100
+ }) => tryRead(type, () => queryStatisticsCollectionForQuantity(id, ["cumulativeSum"], anchor, interval, {
105
101
  unit,
106
102
  filter: statsRange
107
103
  }));
108
- const [steps, activeCalories, distance, exercise] = await Promise.all([daily("steps", "HKQuantityTypeIdentifierStepCount", "count"), daily("activeCalories", "HKQuantityTypeIdentifierActiveEnergyBurned", "kcal"), daily("distance", "HKQuantityTypeIdentifierDistanceWalkingRunning", "m"), daily("exercise", "HKQuantityTypeIdentifierAppleExerciseTime", "min")]);
104
+ const [steps, activeCalories, distance, exercise, daylight, restingCalories, quarterSteps] = await Promise.all([sums("steps", "HKQuantityTypeIdentifierStepCount", "count"), sums("activeCalories", "HKQuantityTypeIdentifierActiveEnergyBurned", "kcal"), sums("distance", "HKQuantityTypeIdentifierDistanceWalkingRunning", "m"), sums("exercise", "HKQuantityTypeIdentifierAppleExerciseTime", "min"), sums("daylight", "HKQuantityTypeIdentifierTimeInDaylight", "min"), sums("restingCalories", "HKQuantityTypeIdentifierBasalEnergyBurned", "kcal"), sums("steps", "HKQuantityTypeIdentifierStepCount", "count", {
105
+ minute: INTRADAY_BUCKET_MINUTES
106
+ })]);
109
107
  raw.dailyTotals = hkDailyTotals({
110
108
  steps,
111
109
  activeCalories,
112
110
  distanceMeters: distance,
113
- activeMinutes: exercise
111
+ activeMinutes: exercise,
112
+ daylightMinutes: daylight,
113
+ restingCalories
114
114
  }, clock);
115
+ raw.stepSpans = hkStepSpans(quarterSteps != null ? quarterSteps : []);
115
116
  for (let t = range.start; t < range.end; t += HR_CHUNK_MS) {
116
117
  const chunk = await samples("heartRate", "HKQuantityTypeIdentifierHeartRate", "count/min", new Date(t), new Date(Math.min(range.end, t + HR_CHUNK_MS)));
117
118
  if (chunk) raw.heartRate.push(...hkValues(hkNotOwn(chunk, own)));
118
119
  }
119
- const [rhr, hrv, weight, vo2, spo2, resp, fat, lean, bmi, waist, temp, glucose, pressure, sleep] = await Promise.all([samples("restingHr", "HKQuantityTypeIdentifierRestingHeartRate", "count/min"), samples("hrv", "HKQuantityTypeIdentifierHeartRateVariabilitySDNN", "ms"), samples("weight", "HKQuantityTypeIdentifierBodyMass", "kg"), samples("vo2Max", "HKQuantityTypeIdentifierVO2Max", "ml/(kg*min)"), samples("spo2", "HKQuantityTypeIdentifierOxygenSaturation", "%"), samples("respiratoryRate", "HKQuantityTypeIdentifierRespiratoryRate", "count/min"), samples("bodyFat", "HKQuantityTypeIdentifierBodyFatPercentage", "%"), samples("leanMass", "HKQuantityTypeIdentifierLeanBodyMass", "kg"), samples("bmi", "HKQuantityTypeIdentifierBodyMassIndex", "count"), samples("waist", "HKQuantityTypeIdentifierWaistCircumference", "cm"), samples("bodyTemp", "HKQuantityTypeIdentifierBodyTemperature", "degC"), samples("bloodGlucose", "HKQuantityTypeIdentifierBloodGlucose", "mg/dL"), attempt("bloodPressure", unreadable, () => queryCorrelationSamples("HKCorrelationTypeIdentifierBloodPressure", {
120
+ const [rhr, hrv, weight, vo2, spo2, resp, fat, lean, bmi, waist, temp, wristTemp, glucose, pressure, sleep, mindful] = await Promise.all([samples("restingHr", "HKQuantityTypeIdentifierRestingHeartRate", "count/min"), samples("hrv", "HKQuantityTypeIdentifierHeartRateVariabilitySDNN", "ms"), samples("weight", "HKQuantityTypeIdentifierBodyMass", "kg"), samples("vo2Max", "HKQuantityTypeIdentifierVO2Max", "ml/(kg*min)"), samples("spo2", "HKQuantityTypeIdentifierOxygenSaturation", "%"), samples("respiratoryRate", "HKQuantityTypeIdentifierRespiratoryRate", "count/min"), samples("bodyFat", "HKQuantityTypeIdentifierBodyFatPercentage", "%"), samples("leanMass", "HKQuantityTypeIdentifierLeanBodyMass", "kg"), samples("bmi", "HKQuantityTypeIdentifierBodyMassIndex", "count"), samples("waist", "HKQuantityTypeIdentifierWaistCircumference", "cm"), samples("bodyTemp", "HKQuantityTypeIdentifierBodyTemperature", "degC"), samples("wristTemp", "HKQuantityTypeIdentifierAppleSleepingWristTemperature", "degC"), samples("bloodGlucose", "HKQuantityTypeIdentifierBloodGlucose", "mg/dL"), tryRead("bloodPressure", () => queryCorrelationSamples("HKCorrelationTypeIdentifierBloodPressure", {
121
+ limit: 0,
122
+ ascending: true,
123
+ filter: {
124
+ date
125
+ }
126
+ })), tryRead("sleep", () => queryCategorySamples("HKCategoryTypeIdentifierSleepAnalysis", {
120
127
  limit: 0,
121
128
  ascending: true,
122
129
  filter: {
123
130
  date
124
131
  }
125
- })), attempt("sleep", unreadable, () => queryCategorySamples("HKCategoryTypeIdentifierSleepAnalysis", {
132
+ })), tryRead("mindful", () => queryCategorySamples("HKCategoryTypeIdentifierMindfulSession", {
126
133
  limit: 0,
127
134
  ascending: true,
128
135
  filter: {
@@ -140,10 +147,12 @@ function createHealthKitReader() {
140
147
  raw.bmi = hkValues(hkNotOwn(bmi != null ? bmi : [], own));
141
148
  raw.waistCm = hkValues(waist != null ? waist : []);
142
149
  raw.bodyTempC = hkValues(hkNotOwn(temp != null ? temp : [], own));
150
+ raw.wristTempC = hkValuesAtEnd(wristTemp != null ? wristTemp : []);
143
151
  raw.glucose = hkGlucose(hkNotOwn(glucose != null ? glucose : [], own));
144
152
  raw.bloodPressure = hkBloodPressure(hkNotOwn(pressure != null ? pressure : [], own));
145
153
  raw.sleep = hkSleepSegments(sleep != null ? sleep : []);
146
- const workouts = await attempt("workouts", unreadable, () => queryWorkoutSamples({
154
+ raw.mindful = hkSpans(mindful != null ? mindful : []);
155
+ const workouts = await tryRead("workouts", () => queryWorkoutSamples({
147
156
  limit: 0,
148
157
  ascending: true,
149
158
  filter: {
@@ -164,7 +173,8 @@ function createHealthKitReader() {
164
173
  }
165
174
  return {
166
175
  raw,
167
- unreadable: [...unreadable]
176
+ unreadable: [...unreadable],
177
+ needsAccess
168
178
  };
169
179
  },
170
180
  async revoke() {
@@ -1 +1 @@
1
- {"version":3,"file":"healthkitReader.js","sources":["../../../src/features/health/healthkitReader.ts"],"sourcesContent":["/**\n * Apple Health (HealthKit) reader, iOS only. Yantra writes only readings from\n * devices paired in the app (healthkitWriter.ts); those are skipped here, the\n * backend already has them as source `device`.\n *\n * - Daily totals use HealthKit's statistics collection (one bucket per local\n * day), which merges iPhone + Apple Watch without double counting.\n * - Heart rate, HRV, sleep and the body measurements are read as samples.\n * - HealthKit never tells an app which read types were allowed, and a denied\n * type simply returns no samples; the screen says so instead of guessing.\n * - HealthKit must have been asked before anything is queried (the library\n * crashes otherwise), so a read first checks the request status and stops\n * with HealthAccessNeededError when the sheet still has to be shown.\n */\nimport {\n getRequestStatusForAuthorization,\n isHealthDataAvailableAsync,\n queryCategorySamples,\n queryCorrelationSamples,\n queryQuantitySamples,\n queryStatisticsCollectionForQuantity,\n queryWorkoutSamples,\n requestAuthorization,\n AuthorizationRequestStatus,\n type ObjectTypeIdentifier,\n type QuantityTypeIdentifier,\n type UnitForIdentifier,\n} from '@kingstinct/react-native-healthkit';\nimport {\n hkBloodPressure,\n hkDailyTotals,\n hkGlucose,\n hkNotOwn,\n hkPercentValues,\n hkSleepSegments,\n hkSpo2Values,\n hkValues,\n hkWorkout,\n type HKWorkoutStats,\n} from './healthkitMapping';\nimport { ownAppId } from './ownSource';\nimport { emptyRawHealthData } from './model';\nimport type { HealthDataType, HealthReader, ReadResult } from './reader';\nimport type { ZoneClock } from './time';\n\nexport class HealthAccessNeededError extends Error {\n constructor() {\n super('Yantra needs to ask for access to Apple Health again.');\n this.name = 'HealthAccessNeededError';\n }\n}\n\nconst READ_TYPES: Record<HealthDataType, ObjectTypeIdentifier> = {\n steps: 'HKQuantityTypeIdentifierStepCount',\n distance: 'HKQuantityTypeIdentifierDistanceWalkingRunning',\n activeCalories: 'HKQuantityTypeIdentifierActiveEnergyBurned',\n exercise: 'HKQuantityTypeIdentifierAppleExerciseTime',\n heartRate: 'HKQuantityTypeIdentifierHeartRate',\n restingHr: 'HKQuantityTypeIdentifierRestingHeartRate',\n hrv: 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN',\n sleep: 'HKCategoryTypeIdentifierSleepAnalysis',\n workouts: 'HKWorkoutTypeIdentifier',\n weight: 'HKQuantityTypeIdentifierBodyMass',\n vo2Max: 'HKQuantityTypeIdentifierVO2Max',\n spo2: 'HKQuantityTypeIdentifierOxygenSaturation',\n respiratoryRate: 'HKQuantityTypeIdentifierRespiratoryRate',\n bodyFat: 'HKQuantityTypeIdentifierBodyFatPercentage',\n leanMass: 'HKQuantityTypeIdentifierLeanBodyMass',\n bmi: 'HKQuantityTypeIdentifierBodyMassIndex',\n waist: 'HKQuantityTypeIdentifierWaistCircumference',\n bodyTemp: 'HKQuantityTypeIdentifierBodyTemperature',\n // Read access to a correlation is asked through its two quantity types.\n bloodPressure: 'HKQuantityTypeIdentifierBloodPressureSystolic',\n bloodGlucose: 'HKQuantityTypeIdentifierBloodGlucose',\n};\n\nconst TO_READ: ObjectTypeIdentifier[] = [\n ...Object.values(READ_TYPES),\n 'HKQuantityTypeIdentifierBloodPressureDiastolic',\n];\n\n/** Heart rate is read one day at a time: a workout day is thousands of samples. */\nconst HR_CHUNK_MS = 86_400_000;\n\nasync function attempt<T>(\n type: HealthDataType,\n unreadable: Set<HealthDataType>,\n run: () => Promise<T>,\n): Promise<T | undefined> {\n try {\n return await run();\n } catch {\n unreadable.add(type);\n return undefined;\n }\n}\n\nexport function createHealthKitReader(): HealthReader {\n return {\n source: 'apple-health',\n storeName: 'Apple Health',\n\n async availability() {\n try {\n return (await isHealthDataAvailableAsync())\n ? { status: 'available' }\n : { status: 'unsupported', reason: 'Apple Health is not available on this device.' };\n } catch {\n return { status: 'unsupported', reason: 'Apple Health is not available in this build of the app.' };\n }\n },\n\n async requestAccess() {\n await requestAuthorization({ toRead: TO_READ });\n return null;\n },\n\n async grantedTypes() {\n return null;\n },\n\n async read(range, clock: ZoneClock): Promise<ReadResult> {\n const status = await getRequestStatusForAuthorization({ toRead: TO_READ });\n if (status === AuthorizationRequestStatus.shouldRequest) throw new HealthAccessNeededError();\n\n const unreadable = new Set<HealthDataType>();\n const raw = emptyRawHealthData('sdnn');\n const own = ownAppId('ios');\n const startDate = new Date(range.start);\n const endDate = new Date(range.end);\n const date = { startDate, endDate };\n\n const samples = <T extends QuantityTypeIdentifier>(\n type: HealthDataType,\n id: T,\n unit: UnitForIdentifier<T>,\n from = startDate,\n to = endDate,\n ) =>\n attempt(type, unreadable, () =>\n queryQuantitySamples(id, {\n limit: 0,\n ascending: true,\n unit,\n filter: { date: { startDate: from, endDate: to } },\n }),\n );\n\n // Daily totals: buckets start at the local midnight of the first full day.\n const firstDay = clock.dateOf(range.start + 12 * 3_600_000);\n const anchor = new Date(clock.startOfDay(firstDay));\n const statsRange = { date: { startDate: anchor, endDate } };\n const daily = <T extends QuantityTypeIdentifier>(type: HealthDataType, id: T, unit: UnitForIdentifier<T>) =>\n attempt(type, unreadable, () =>\n queryStatisticsCollectionForQuantity(\n id,\n ['cumulativeSum'],\n anchor,\n { day: 1 },\n { unit, filter: statsRange },\n ),\n );\n const [steps, activeCalories, distance, exercise] = await Promise.all([\n daily('steps', 'HKQuantityTypeIdentifierStepCount', 'count'),\n daily('activeCalories', 'HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal'),\n daily('distance', 'HKQuantityTypeIdentifierDistanceWalkingRunning', 'm'),\n daily('exercise', 'HKQuantityTypeIdentifierAppleExerciseTime', 'min'),\n ]);\n raw.dailyTotals = hkDailyTotals(\n { steps, activeCalories, distanceMeters: distance, activeMinutes: exercise },\n clock,\n );\n\n for (let t = range.start; t < range.end; t += HR_CHUNK_MS) {\n const chunk = await samples(\n 'heartRate',\n 'HKQuantityTypeIdentifierHeartRate',\n 'count/min',\n new Date(t),\n new Date(Math.min(range.end, t + HR_CHUNK_MS)),\n );\n if (chunk) raw.heartRate.push(...hkValues(hkNotOwn(chunk, own)));\n }\n\n const [rhr, hrv, weight, vo2, spo2, resp, fat, lean, bmi, waist, temp, glucose, pressure, sleep] =\n await Promise.all([\n samples('restingHr', 'HKQuantityTypeIdentifierRestingHeartRate', 'count/min'),\n samples('hrv', 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN', 'ms'),\n samples('weight', 'HKQuantityTypeIdentifierBodyMass', 'kg'),\n samples('vo2Max', 'HKQuantityTypeIdentifierVO2Max', 'ml/(kg*min)'),\n samples('spo2', 'HKQuantityTypeIdentifierOxygenSaturation', '%'),\n samples('respiratoryRate', 'HKQuantityTypeIdentifierRespiratoryRate', 'count/min'),\n samples('bodyFat', 'HKQuantityTypeIdentifierBodyFatPercentage', '%'),\n samples('leanMass', 'HKQuantityTypeIdentifierLeanBodyMass', 'kg'),\n samples('bmi', 'HKQuantityTypeIdentifierBodyMassIndex', 'count'),\n samples('waist', 'HKQuantityTypeIdentifierWaistCircumference', 'cm'),\n samples('bodyTemp', 'HKQuantityTypeIdentifierBodyTemperature', 'degC'),\n samples('bloodGlucose', 'HKQuantityTypeIdentifierBloodGlucose', 'mg/dL'),\n attempt('bloodPressure', unreadable, () =>\n queryCorrelationSamples('HKCorrelationTypeIdentifierBloodPressure', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n attempt('sleep', unreadable, () =>\n queryCategorySamples('HKCategoryTypeIdentifierSleepAnalysis', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n ]);\n raw.restingHr = hkValues(rhr ?? []);\n raw.hrv = hkValues(hrv ?? []);\n raw.weightKg = hkValues(hkNotOwn(weight ?? [], own));\n raw.vo2Max = hkValues(vo2 ?? []);\n raw.spo2 = hkSpo2Values(hkNotOwn(spo2 ?? [], own));\n raw.respiratoryRate = hkValues(resp ?? []);\n raw.bodyFatPct = hkPercentValues(hkNotOwn(fat ?? [], own));\n raw.leanMassKg = hkValues(hkNotOwn(lean ?? [], own));\n raw.bmi = hkValues(hkNotOwn(bmi ?? [], own));\n raw.waistCm = hkValues(waist ?? []);\n raw.bodyTempC = hkValues(hkNotOwn(temp ?? [], own));\n raw.glucose = hkGlucose(hkNotOwn(glucose ?? [], own));\n raw.bloodPressure = hkBloodPressure(hkNotOwn(pressure ?? [], own));\n raw.sleep = hkSleepSegments(sleep ?? []);\n\n const workouts = await attempt('workouts', unreadable, () =>\n queryWorkoutSamples({ limit: 0, ascending: true, filter: { date } }),\n );\n for (const w of workouts ?? []) {\n try {\n const stats: HKWorkoutStats = {};\n const [energy, hr] = await Promise.all([\n w.getStatistic('HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal').catch(() => undefined),\n w.getStatistic('HKQuantityTypeIdentifierHeartRate', 'count/min').catch(() => undefined),\n ]);\n if (energy?.sumQuantity) stats.calories = energy.sumQuantity.quantity;\n if (hr?.averageQuantity) stats.avgHr = hr.averageQuantity.quantity;\n if (hr?.maximumQuantity) stats.maxHr = hr.maximumQuantity.quantity;\n raw.workouts.push(hkWorkout(w, stats));\n } finally {\n w.dispose?.();\n }\n }\n\n return { raw, unreadable: [...unreadable] };\n },\n\n async revoke() {\n // iOS has no API to give read access back; the person turns it\n // off in the Health app. Stopping sync is handled by the caller.\n },\n };\n}\n"],"names":[],"mappings":"+fAoBO,MAAM,gCAAgC,KAAM,CAAA;AAAA,EACjD,WAAc,GAAA;AACZ,IAAA,KAAA,CAAM,uDAAuD,CAAA;AAC7D,IAAA,IAAA,CAAK,IAAO,GAAA,yBAAA;AAAA;AAEhB;AACA,MAAM,UAA2D,GAAA;AAAA,EAC/D,KAAO,EAAA,mCAAA;AAAA,EACP,QAAU,EAAA,gDAAA;AAAA,EACV,cAAgB,EAAA,4CAAA;AAAA,EAChB,QAAU,EAAA,2CAAA;AAAA,EACV,SAAW,EAAA,mCAAA;AAAA,EACX,SAAW,EAAA,0CAAA;AAAA,EACX,GAAK,EAAA,kDAAA;AAAA,EACL,KAAO,EAAA,uCAAA;AAAA,EACP,QAAU,EAAA,yB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eAAgB,CAAA,QAAA;AAC1D,UAAA,GAAA,CAAI,QAAS,CAAA,IAAA,CAAK,SAAU,CAAA,CAAA,EAAG,KAAK,CAAC,CAAA;AAAA,SACrC,SAAA;AACA,UAAA,CAAA,EAAA,GAAA,CAAA,CAAE,OAAF,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,CAAA,CAAA,CAAA;AAAA;AACF;AAEF,MAAO,OAAA;AAAA,QACL,GAAA;AAAA,QACA,UAAA,EAAY,CAAC,GAAG,UAAU;AAAA,OAC5B;AAAA,KACF;AAAA,IACA,MAAM,MAAS,GAAA;AAAA;AAGf,GACF;AACF"}
1
+ {"version":3,"file":"healthkitReader.js","sources":["../../../src/features/health/healthkitReader.ts"],"sourcesContent":["/**\n * Apple Health (HealthKit) reader, iOS only. Yantra writes only readings from\n * devices paired in the app (healthkitWriter.ts); those are skipped here, the\n * backend already has them as source `device`.\n *\n * - Daily totals use HealthKit's statistics collection (one bucket per local\n * day), which merges iPhone + Apple Watch without double counting. Steps\n * per quarter-hour, for the 15-minute buckets, come from the same query\n * with a 15-minute interval.\n * - Heart rate, HRV, sleep and the body measurements are read as samples.\n * - HealthKit never tells an app which read types were allowed, and a denied\n * type simply returns no samples; the screen says so instead of guessing.\n * - HealthKit must have been asked before anything is queried (the library\n * crashes otherwise), so a read first checks the request status and stops\n * with HealthAccessNeededError when the sheet was never shown. A type added\n * since (an app update, a newer iOS) is left out and reported as needing\n * access instead: the rest keeps syncing until \"Sync now\" asks for it.\n * - Types a version of iOS does not have (wrist temperature before 16, time\n * in daylight before 17) are never asked for nor read there.\n * - Workout effort (iOS 18's HKQuantityTypeIdentifierWorkoutEffortScore) is\n * not read: Apple ties it to a workout through HKWorkoutEffortRelationship,\n * which this library version (16.1.0) has no query for, and matching effort\n * samples by time would be a guess.\n */\nimport { Platform } from 'react-native';\nimport {\n getRequestStatusForAuthorization,\n isHealthDataAvailableAsync,\n queryCategorySamples,\n queryCorrelationSamples,\n queryQuantitySamples,\n queryStatisticsCollectionForQuantity,\n queryWorkoutSamples,\n requestAuthorization,\n AuthorizationRequestStatus,\n type IntervalComponents,\n type QuantityTypeIdentifier,\n type UnitForIdentifier,\n} from '@kingstinct/react-native-healthkit';\nimport {\n hkBloodPressure,\n hkDailyTotals,\n hkGlucose,\n hkIdentifiers,\n hkNotOwn,\n hkPercentValues,\n hkReadTypes,\n hkSleepSegments,\n hkSpans,\n hkSpo2Values,\n hkStepSpans,\n hkValues,\n hkValuesAtEnd,\n hkWorkout,\n type HKWorkoutStats,\n} from './healthkitMapping';\nimport { ownAppId } from './ownSource';\nimport { emptyRawHealthData } from './model';\nimport type { HealthDataType, HealthReader, ReadResult } from './reader';\nimport type { ZoneClock } from './time';\nimport { INTRADAY_BUCKET_MINUTES } from './types';\n\nexport class HealthAccessNeededError extends Error {\n constructor() {\n super('Yantra needs to ask for access to Apple Health again.');\n this.name = 'HealthAccessNeededError';\n }\n}\n\n/** iOS major version, e.g. 17 for \"17.4\"; 0 when the runtime does not say. */\nfunction iosMajor(): number {\n const major = Number.parseInt(String(Platform.Version), 10);\n return Number.isFinite(major) ? major : 0;\n}\n\n/**\n * The types never asked about yet. One status call for all of them first: the\n * usual answer is \"asked\", and only then is each type checked on its own.\n */\nasync function notAskedYet(types: readonly HealthDataType[]): Promise<HealthDataType[]> {\n const all = await getRequestStatusForAuthorization({ toRead: hkIdentifiers(types) });\n if (all !== AuthorizationRequestStatus.shouldRequest) return [];\n const each = await Promise.all(\n types.map(async (type) => ({\n type,\n status: await getRequestStatusForAuthorization({ toRead: hkIdentifiers([type]) }),\n })),\n );\n return each.filter((x) => x.status === AuthorizationRequestStatus.shouldRequest).map((x) => x.type);\n}\n\n/** Heart rate is read one day at a time: a workout day is thousands of samples. */\nconst HR_CHUNK_MS = 86_400_000;\n\nasync function attempt<T>(\n type: HealthDataType,\n unreadable: Set<HealthDataType>,\n run: () => Promise<T>,\n): Promise<T | undefined> {\n try {\n return await run();\n } catch {\n unreadable.add(type);\n return undefined;\n }\n}\n\nexport function createHealthKitReader(): HealthReader {\n const types = hkReadTypes(iosMajor());\n const toRead = hkIdentifiers(types);\n return {\n source: 'apple-health',\n storeName: 'Apple Health',\n types,\n\n async availability() {\n try {\n return (await isHealthDataAvailableAsync())\n ? { status: 'available' }\n : { status: 'unsupported', reason: 'Apple Health is not available on this device.' };\n } catch {\n return { status: 'unsupported', reason: 'Apple Health is not available in this build of the app.' };\n }\n },\n\n async requestAccess() {\n await requestAuthorization({ toRead });\n return null;\n },\n\n async grantedTypes() {\n return null;\n },\n\n async read(range, clock: ZoneClock): Promise<ReadResult> {\n const needsAccess = await notAskedYet(types);\n if (needsAccess.length === types.length) throw new HealthAccessNeededError();\n const skip = new Set(needsAccess);\n\n const unreadable = new Set<HealthDataType>();\n /** Reads a type that was asked for; one never asked about is left out (needsAccess). */\n const tryRead = <T>(type: HealthDataType, run: () => Promise<T>): Promise<T | undefined> =>\n skip.has(type) || !types.includes(type) ? Promise.resolve(undefined) : attempt(type, unreadable, run);\n const raw = emptyRawHealthData('sdnn');\n const own = ownAppId('ios');\n const startDate = new Date(range.start);\n const endDate = new Date(range.end);\n const date = { startDate, endDate };\n\n const samples = <T extends QuantityTypeIdentifier>(\n type: HealthDataType,\n id: T,\n unit: UnitForIdentifier<T>,\n from = startDate,\n to = endDate,\n ) =>\n tryRead(type, () =>\n queryQuantitySamples(id, {\n limit: 0,\n ascending: true,\n unit,\n filter: { date: { startDate: from, endDate: to } },\n }),\n );\n\n // Statistics buckets start at the local midnight of the first full day.\n const firstDay = clock.dateOf(range.start + 12 * 3_600_000);\n const anchor = new Date(clock.startOfDay(firstDay));\n const statsRange = { date: { startDate: anchor, endDate } };\n const sums = <T extends QuantityTypeIdentifier>(\n type: HealthDataType,\n id: T,\n unit: UnitForIdentifier<T>,\n interval: IntervalComponents = { day: 1 },\n ) =>\n tryRead(type, () =>\n queryStatisticsCollectionForQuantity(id, ['cumulativeSum'], anchor, interval, {\n unit,\n filter: statsRange,\n }),\n );\n const [steps, activeCalories, distance, exercise, daylight, restingCalories, quarterSteps] =\n await Promise.all([\n sums('steps', 'HKQuantityTypeIdentifierStepCount', 'count'),\n sums('activeCalories', 'HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal'),\n sums('distance', 'HKQuantityTypeIdentifierDistanceWalkingRunning', 'm'),\n sums('exercise', 'HKQuantityTypeIdentifierAppleExerciseTime', 'min'),\n sums('daylight', 'HKQuantityTypeIdentifierTimeInDaylight', 'min'),\n sums('restingCalories', 'HKQuantityTypeIdentifierBasalEnergyBurned', 'kcal'),\n sums('steps', 'HKQuantityTypeIdentifierStepCount', 'count', { minute: INTRADAY_BUCKET_MINUTES }),\n ]);\n raw.dailyTotals = hkDailyTotals(\n {\n steps,\n activeCalories,\n distanceMeters: distance,\n activeMinutes: exercise,\n daylightMinutes: daylight,\n restingCalories,\n },\n clock,\n );\n raw.stepSpans = hkStepSpans(quarterSteps ?? []);\n\n for (let t = range.start; t < range.end; t += HR_CHUNK_MS) {\n const chunk = await samples(\n 'heartRate',\n 'HKQuantityTypeIdentifierHeartRate',\n 'count/min',\n new Date(t),\n new Date(Math.min(range.end, t + HR_CHUNK_MS)),\n );\n if (chunk) raw.heartRate.push(...hkValues(hkNotOwn(chunk, own)));\n }\n\n const [\n rhr,\n hrv,\n weight,\n vo2,\n spo2,\n resp,\n fat,\n lean,\n bmi,\n waist,\n temp,\n wristTemp,\n glucose,\n pressure,\n sleep,\n mindful,\n ] = await Promise.all([\n samples('restingHr', 'HKQuantityTypeIdentifierRestingHeartRate', 'count/min'),\n samples('hrv', 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN', 'ms'),\n samples('weight', 'HKQuantityTypeIdentifierBodyMass', 'kg'),\n samples('vo2Max', 'HKQuantityTypeIdentifierVO2Max', 'ml/(kg*min)'),\n samples('spo2', 'HKQuantityTypeIdentifierOxygenSaturation', '%'),\n samples('respiratoryRate', 'HKQuantityTypeIdentifierRespiratoryRate', 'count/min'),\n samples('bodyFat', 'HKQuantityTypeIdentifierBodyFatPercentage', '%'),\n samples('leanMass', 'HKQuantityTypeIdentifierLeanBodyMass', 'kg'),\n samples('bmi', 'HKQuantityTypeIdentifierBodyMassIndex', 'count'),\n samples('waist', 'HKQuantityTypeIdentifierWaistCircumference', 'cm'),\n samples('bodyTemp', 'HKQuantityTypeIdentifierBodyTemperature', 'degC'),\n samples('wristTemp', 'HKQuantityTypeIdentifierAppleSleepingWristTemperature', 'degC'),\n samples('bloodGlucose', 'HKQuantityTypeIdentifierBloodGlucose', 'mg/dL'),\n tryRead('bloodPressure', () =>\n queryCorrelationSamples('HKCorrelationTypeIdentifierBloodPressure', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n tryRead('sleep', () =>\n queryCategorySamples('HKCategoryTypeIdentifierSleepAnalysis', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n tryRead('mindful', () =>\n queryCategorySamples('HKCategoryTypeIdentifierMindfulSession', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n ]);\n raw.restingHr = hkValues(rhr ?? []);\n raw.hrv = hkValues(hrv ?? []);\n raw.weightKg = hkValues(hkNotOwn(weight ?? [], own));\n raw.vo2Max = hkValues(vo2 ?? []);\n raw.spo2 = hkSpo2Values(hkNotOwn(spo2 ?? [], own));\n raw.respiratoryRate = hkValues(resp ?? []);\n raw.bodyFatPct = hkPercentValues(hkNotOwn(fat ?? [], own));\n raw.leanMassKg = hkValues(hkNotOwn(lean ?? [], own));\n raw.bmi = hkValues(hkNotOwn(bmi ?? [], own));\n raw.waistCm = hkValues(waist ?? []);\n raw.bodyTempC = hkValues(hkNotOwn(temp ?? [], own));\n raw.wristTempC = hkValuesAtEnd(wristTemp ?? []);\n raw.glucose = hkGlucose(hkNotOwn(glucose ?? [], own));\n raw.bloodPressure = hkBloodPressure(hkNotOwn(pressure ?? [], own));\n raw.sleep = hkSleepSegments(sleep ?? []);\n raw.mindful = hkSpans(mindful ?? []);\n\n const workouts = await tryRead('workouts', () =>\n queryWorkoutSamples({ limit: 0, ascending: true, filter: { date } }),\n );\n for (const w of workouts ?? []) {\n try {\n const stats: HKWorkoutStats = {};\n const [energy, hr] = await Promise.all([\n w.getStatistic('HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal').catch(() => undefined),\n w.getStatistic('HKQuantityTypeIdentifierHeartRate', 'count/min').catch(() => undefined),\n ]);\n if (energy?.sumQuantity) stats.calories = energy.sumQuantity.quantity;\n if (hr?.averageQuantity) stats.avgHr = hr.averageQuantity.quantity;\n if (hr?.maximumQuantity) stats.maxHr = hr.maximumQuantity.quantity;\n raw.workouts.push(hkWorkout(w, stats));\n } finally {\n w.dispose?.();\n }\n }\n\n return { raw, unreadable: [...unreadable], needsAccess };\n },\n\n async revoke() {\n // iOS has no API to give read access back; the person turns it\n // off in the Health app. Stopping sync is handled by the caller.\n },\n };\n}\n"],"names":[],"mappings":"gpBAgCO,MAAM,gCAAgC,KAAM,CAAA;AAAA,EACjD,WAAc,GAAA;AACZ,IAAA,KAAA,CAAM,uDAAuD,CAAA;AAC7D,IAAA,IAAA,CAAK,IAAO,GAAA,yBAAA;AAAA;AAEhB;AAGA,SAAS,QAAmB,GAAA;AAC1B,EAAA,MAAM,QAAQ,MAAO,CAAA,QAAA,CAAS,OAAO,QAAS,CAAA,OAAO,GAAG,EAAE,CAAA;AAC1D,EAAA,OAAO,MAAO,CAAA,QAAA,CAAS,KAAK,CAAA,GAAI,KAAQ,GAAA,CAAA;AAC1C;AAMA,eAAe,YAAY,KAA6D,EAAA;AACtF,EAAM,MAAA,GAAA,GAAM,MAAM,gCAAiC,CAAA;AAAA,IACjD,MAAA,EAAQ,cAAc,KAAK;AAAA,GAC5B,CAAA;AACD,EAAA,IAAI,GAAQ,KAAA,0BAAA,CAA2B,aAAe,EAAA,OAAO,EAAC;AAC9D,EAAA,MAAM,OAAO,MAAM,OAAA,CAAQ,IAAI,KAAM,CAAA,GAAA,CAAI,OAAM,IAAS,MAAA;AAAA,I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AAA,CAAA;AAAA;AACF;AAEF,MAAO,OAAA;AAAA,QACL,GAAA;AAAA,QACA,UAAA,EAAY,CAAC,GAAG,UAAU,CAAA;AAAA,QAC1B;AAAA,OACF;AAAA,KACF;AAAA,IACA,MAAM,MAAS,GAAA;AAAA;AAGf,GACF;AACF"}
@@ -35,12 +35,9 @@ function createHealthKitWriter() {
35
35
  const writes = healthKitWritesFor(reading);
36
36
  if (!writes.length) return "nothing";
37
37
  let saved = 0;
38
- let denied = 0;
39
- for (const w of writes) {
40
- if (typesOf(w).some((t) => authorizationStatusFor(t) !== AuthorizationStatus.sharingAuthorized)) {
41
- denied++;
42
- continue;
43
- }
38
+ const allowed = writes.filter((w) => typesOf(w).every((t) => authorizationStatusFor(t) === AuthorizationStatus.sharingAuthorized));
39
+ const denied = writes.length - allowed.length;
40
+ for (const w of allowed) {
44
41
  try {
45
42
  await write(w);
46
43
  saved++;
@@ -1 +1 @@
1
- {"version":3,"file":"healthkitWriter.js","sources":["../../../src/features/health/healthkitWriter.ts"],"sourcesContent":["/**\n * Apple Health writer, iOS only: saves the readings Yantra took from a paired\n * Bluetooth device (see writeMapping.ts for what each becomes). HealthKit says\n * per type whether saving is allowed, so a type the person turned off is\n * skipped, never retried into an error.\n */\nimport {\n AuthorizationStatus,\n authorizationStatusFor,\n requestAuthorization,\n saveCorrelationSample,\n saveQuantitySample,\n} from '@kingstinct/react-native-healthkit';\nimport { HK_WRITE_TYPES, healthKitWritesFor, type HKWrite, type HKWriteType } from './writeMapping';\nimport type { HealthWriter, SaveOutcome } from './writer';\n\nconst SYSTOLIC: HKWriteType = 'HKQuantityTypeIdentifierBloodPressureSystolic';\nconst DIASTOLIC: HKWriteType = 'HKQuantityTypeIdentifierBloodPressureDiastolic';\n\nconst typesOf = (w: HKWrite): HKWriteType[] => (w.kind === 'quantity' ? [w.type] : [SYSTOLIC, DIASTOLIC]);\n\nasync function write(w: HKWrite): Promise<void> {\n if (w.kind === 'quantity') {\n await saveQuantitySample(w.type, w.unit as never, w.value, w.at, w.at, w.metadata as never);\n return;\n }\n await saveCorrelationSample(\n 'HKCorrelationTypeIdentifierBloodPressure',\n [\n { quantityType: SYSTOLIC, quantity: w.systolic, unit: 'mmHg', startDate: w.at, endDate: w.at },\n { quantityType: DIASTOLIC, quantity: w.diastolic, unit: 'mmHg', startDate: w.at, endDate: w.at },\n ],\n w.at,\n w.at,\n w.metadata as never,\n );\n}\n\nexport function createHealthKitWriter(): HealthWriter {\n return {\n storeName: 'Apple Health',\n\n async requestAccess() {\n await requestAuthorization({ toShare: HK_WRITE_TYPES });\n },\n\n async asked() {\n return HK_WRITE_TYPES.some((t) => authorizationStatusFor(t) !== AuthorizationStatus.notDetermined);\n },\n\n async save(reading): Promise<SaveOutcome> {\n const writes = healthKitWritesFor(reading);\n if (!writes.length) return 'nothing';\n let saved = 0;\n let denied = 0;\n for (const w of writes) {\n if (typesOf(w).some((t) => authorizationStatusFor(t) !== AuthorizationStatus.sharingAuthorized)) {\n denied++;\n continue;\n }\n try {\n await write(w);\n saved++;\n } catch {\n return saved ? 'saved' : 'failed';\n }\n }\n if (saved) return 'saved';\n return denied ? 'not-allowed' : 'failed';\n },\n };\n}\n"],"names":[],"mappings":"4NASA,MAAM,QAAwB,GAAA,+CAAA;AAC9B,MAAM,SAAyB,GAAA,gDAAA;AAC/B,MAAM,OAAU,GAAA,CAAC,CAA8B,KAAA,CAAA,CAAE,IAAS,KAAA,UAAA,GAAa,CAAC,CAAA,CAAE,IAAI,CAAA,GAAI,CAAC,QAAA,EAAU,SAAS,CAAA;AACtG,eAAe,MAAM,CAA2B,EAAA;AAC9C,EAAI,IAAA,CAAA,CAAE,SAAS,UAAY,EAAA;AACzB,IAAA,MAAM,kBAAmB,CAAA,CAAA,CAAE,IAAM,EAAA,CAAA,CAAE,IAAe,EAAA,CAAA,CAAE,KAAO,EAAA,CAAA,CAAE,EAAI,EAAA,CAAA,CAAE,EAAI,EAAA,CAAA,CAAE,QAAiB,CAAA;AAC1F,IAA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,EAAA;AACA,UAAA;AAAA;AAEF,QAAI,IAAA;AACF,UAAA,MAAM,MAAM,CAAC,CAAA;AACb,UAAA,KAAA,EAAA;AAAA,SACM,CAAA,OAAA,CAAA,EAAA;AACN,UAAA,OAAO,QAAQ,OAAU,GAAA,QAAA;AAAA;AAC3B;AAEF,MAAA,IAAI,OAAc,OAAA,OAAA;AAClB,MAAA,OAAO,SAAS,aAAgB,GAAA,QAAA;AAAA;AAClC,GACF;AACF"}
1
+ {"version":3,"file":"healthkitWriter.js","sources":["../../../src/features/health/healthkitWriter.ts"],"sourcesContent":["/**\n * Apple Health writer, iOS only: saves the readings Yantra took from a paired\n * Bluetooth device (see writeMapping.ts for what each becomes). HealthKit says\n * per type whether saving is allowed, so a type the person turned off is\n * skipped, never retried into an error.\n */\nimport {\n AuthorizationStatus,\n authorizationStatusFor,\n requestAuthorization,\n saveCorrelationSample,\n saveQuantitySample,\n} from '@kingstinct/react-native-healthkit';\nimport { HK_WRITE_TYPES, healthKitWritesFor, type HKWrite, type HKWriteType } from './writeMapping';\nimport type { HealthWriter, SaveOutcome } from './writer';\n\nconst SYSTOLIC: HKWriteType = 'HKQuantityTypeIdentifierBloodPressureSystolic';\nconst DIASTOLIC: HKWriteType = 'HKQuantityTypeIdentifierBloodPressureDiastolic';\n\nconst typesOf = (w: HKWrite): HKWriteType[] => (w.kind === 'quantity' ? [w.type] : [SYSTOLIC, DIASTOLIC]);\n\nasync function write(w: HKWrite): Promise<void> {\n if (w.kind === 'quantity') {\n await saveQuantitySample(w.type, w.unit as never, w.value, w.at, w.at, w.metadata as never);\n return;\n }\n await saveCorrelationSample(\n 'HKCorrelationTypeIdentifierBloodPressure',\n [\n { quantityType: SYSTOLIC, quantity: w.systolic, unit: 'mmHg', startDate: w.at, endDate: w.at },\n { quantityType: DIASTOLIC, quantity: w.diastolic, unit: 'mmHg', startDate: w.at, endDate: w.at },\n ],\n w.at,\n w.at,\n w.metadata as never,\n );\n}\n\nexport function createHealthKitWriter(): HealthWriter {\n return {\n storeName: 'Apple Health',\n\n async requestAccess() {\n await requestAuthorization({ toShare: HK_WRITE_TYPES });\n },\n\n async asked() {\n return HK_WRITE_TYPES.some((t) => authorizationStatusFor(t) !== AuthorizationStatus.notDetermined);\n },\n\n async save(reading): Promise<SaveOutcome> {\n const writes = healthKitWritesFor(reading);\n if (!writes.length) return 'nothing';\n let saved = 0;\n const allowed = writes.filter((w) =>\n typesOf(w).every((t) => authorizationStatusFor(t) === AuthorizationStatus.sharingAuthorized),\n );\n const denied = writes.length - allowed.length;\n for (const w of allowed) {\n try {\n await write(w);\n saved++;\n } catch {\n return saved ? 'saved' : 'failed';\n }\n }\n if (saved) return 'saved';\n return denied ? 'not-allowed' : 'failed';\n },\n };\n}\n"],"names":[],"mappings":"4NASA,MAAM,QAAwB,GAAA,+CAAA;AAC9B,MAAM,SAAyB,GAAA,gDAAA;AAC/B,MAAM,OAAU,GAAA,CAAC,CAA8B,KAAA,CAAA,CAAE,IAAS,KAAA,UAAA,GAAa,CAAC,CAAA,CAAE,IAAI,CAAA,GAAI,CAAC,QAAA,EAAU,SAAS,CAAA;AACtG,eAAe,MAAM,CAA2B,EAAA;AAC9C,EAAI,IAAA,CAAA,CAAE,SAAS,UAAY,EAAA;AACzB,IAAA,MAAM,kBAAmB,CAAA,CAAA,CAAE,IAAM,EAAA,CAAA,CAAE,IAAe,EAAA,CAAA,CAAE,KAAO,EAAA,CAAA,CAAE,EAAI,EAAA,CAAA,CAAE,EAAI,EAAA,CAAA,CAAE,QAAiB,CAAA;AAC1F,IAAA;AAAA;AAEF,EAAM,MAAA,qBAAA,CAAsB,4CAA4C,CAAC;AAAA,IACvE,YAAc,EAAA,QAAA;AAAA,IACd,UAAU,CAAE,CAAA,QAAA;AAAA,IACZ,IAAM,EAAA,MAAA;AAAA,IACN,WAAW,CAAE,CAAA,EAAA;AAAA,IACb,SAAS,CAAE,CAAA;AAAA,GACV,EAAA;AAAA,IACD,YAAc,EAAA,SAAA;AAAA,IACd,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OAAA;AAClB,MAAA,OAAO,SAAS,aAAgB,GAAA,QAAA;AAAA;AAClC,GACF;AACF"}
@@ -3,7 +3,9 @@ function storeNameFor(platform) {
3
3
  }
4
4
  function hostHealthStatus(snapshot, platform) {
5
5
  var _a;
6
- const availability = snapshot.availability;
6
+ const {
7
+ availability
8
+ } = snapshot;
7
9
  return {
8
10
  status: (_a = availability == null ? void 0 : availability.status) != null ? _a : "unknown",
9
11
  reason: (availability == null ? void 0 : availability.status) === "unsupported" ? availability.reason : void 0,