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

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 +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"hostHealth.js","sources":["../../../src/features/health/hostHealth.ts"],"sourcesContent":["/**\n * The health hand-off a web surface can ask for (bridge `health.status` /\n * `health.connect`, see bridge/handlers/SurfaceHostBridgeHandler): the same\n * HealthSyncStore the Health screen uses, so connecting from the Fitness page\n * runs the very same permission sheet, backfill and error wording.\n */\n\nimport type { HostHealthStatus } from '../../bridge/handlers/SurfaceHostBridgeHandler';\nimport type { HealthSyncSnapshot } from './healthSyncStore';\n\ninterface StoreLike {\n refreshStatus: () => Promise<void>;\n connect: () => Promise<boolean>;\n getSnapshot: () => HealthSyncSnapshot;\n}\n\nexport function storeNameFor(platform: string): string {\n return platform === 'android' ? 'Health Connect' : 'Apple Health';\n}\n\nexport function hostHealthStatus(snapshot: HealthSyncSnapshot, platform: string): HostHealthStatus {\n const availability = snapshot.availability;\n return {\n status: availability?.status ?? 'unknown',\n reason: availability?.status === 'unsupported' ? availability.reason : undefined,\n connected: Boolean(snapshot.sync.connected),\n source: snapshot.sync.source,\n storeName: storeNameFor(platform),\n lastSyncAt: snapshot.sync.lastSyncAt,\n lastError: snapshot.sync.lastError,\n busy: snapshot.busy,\n };\n}\n\nexport function createHostHealth(store: StoreLike, platform: string) {\n return {\n async status(): Promise<HostHealthStatus> {\n await store.refreshStatus();\n return hostHealthStatus(store.getSnapshot(), platform);\n },\n async connect(): Promise<HostHealthStatus> {\n await store.connect();\n return hostHealthStatus(store.getSnapshot(), platform);\n },\n };\n}\n"],"names":[],"mappings":"AAcO,SAAS,aAAa,QAA0B,EAAA;AACrD,EAAO,OAAA,QAAA,KAAa,YAAY,gBAAmB,GAAA,cAAA;AACrD;AACgB,SAAA,gBAAA,CAAiB,UAA8B,QAAoC,EAAA;AAjBnG,EAAA,IAAA,EAAA;AAkBE,EAAA,MAAM,eAAe,QAAS,CAAA,YAAA;AAC9B,EAAO,OAAA;AAAA,IACL,MAAA,EAAA,CAAQ,EAAc,GAAA,YAAA,IAAA,IAAA,GAAA,MAAA,GAAA,YAAA,CAAA,MAAA,KAAd,IAAwB,GAAA,EAAA,GAAA,SAAA;AAAA,IAChC,MAAQ,EAAA,CAAA,YAAA,IAAA,IAAA,GAAA,MAAA,GAAA,YAAA,CAAc,MAAW,MAAA,aAAA,GAAgB,aAAa,MAAS,GAAA,MAAA;AAAA,IACvE,SAAW,EAAA,OAAA,CAAQ,QAAS,CAAA,IAAA,CAAK,SAAS,CAAA;AAAA,IAC1C,MAAA,EAAQ,SAAS,IAAK,CAAA,MAAA;AAAA,IACtB,SAAA,EAAW,aAAa,QAAQ,CAAA;AAAA,IAChC,UAAA,EAAY,SAAS,IAAK,CAAA,UAAA;AAAA,IAC1B,SAAA,EAAW,SAAS,IAAK,CAAA,SAAA;AAAA,IACzB,MAAM,QAAS,CAAA;AAAA,GACjB;AACF;AACgB,SAAA,gBAAA,CAAiB,OAAkB,QAAkB,EAAA;AACnE,EAAO,OAAA;AAAA,IACL,MAAM,MAAoC,GAAA;AACxC,MAAA,MAAM,MAAM,aAAc,EAAA;AAC1B,MAAA,OAAO,gBAAiB,CAAA,KAAA,CAAM,WAAY,EAAA,EAAG,QAAQ,CAAA;AAAA,KACvD;AAAA,IACA,MAAM,OAAqC,GAAA;AACzC,MAAA,MAAM,MAAM,OAAQ,EAAA;AACpB,MAAA,OAAO,gBAAiB,CAAA,KAAA,CAAM,WAAY,EAAA,EAAG,QAAQ,CAAA;AAAA;AACvD,GACF;AACF"}
1
+ {"version":3,"file":"hostHealth.js","sources":["../../../src/features/health/hostHealth.ts"],"sourcesContent":["/**\n * The health hand-off a web surface can ask for (bridge `health.status` /\n * `health.connect`, see bridge/handlers/SurfaceHostBridgeHandler): the same\n * HealthSyncStore the Health screen uses, so connecting from the Fitness page\n * runs the very same permission sheet, backfill and error wording.\n */\n\nimport type { HostHealthStatus } from '../../bridge/handlers/SurfaceHostBridgeHandler';\nimport type { HealthSyncSnapshot } from './healthSyncStore';\n\ninterface StoreLike {\n refreshStatus: () => Promise<void>;\n connect: () => Promise<boolean>;\n getSnapshot: () => HealthSyncSnapshot;\n}\n\nexport function storeNameFor(platform: string): string {\n return platform === 'android' ? 'Health Connect' : 'Apple Health';\n}\n\nexport function hostHealthStatus(snapshot: HealthSyncSnapshot, platform: string): HostHealthStatus {\n const { availability } = snapshot;\n return {\n status: availability?.status ?? 'unknown',\n reason: availability?.status === 'unsupported' ? availability.reason : undefined,\n connected: Boolean(snapshot.sync.connected),\n source: snapshot.sync.source,\n storeName: storeNameFor(platform),\n lastSyncAt: snapshot.sync.lastSyncAt,\n lastError: snapshot.sync.lastError,\n busy: snapshot.busy,\n };\n}\n\nexport function createHostHealth(store: StoreLike, platform: string) {\n return {\n async status(): Promise<HostHealthStatus> {\n await store.refreshStatus();\n return hostHealthStatus(store.getSnapshot(), platform);\n },\n async connect(): Promise<HostHealthStatus> {\n await store.connect();\n return hostHealthStatus(store.getSnapshot(), platform);\n },\n };\n}\n"],"names":[],"mappings":"AAcO,SAAS,aAAa,QAA0B,EAAA;AACrD,EAAO,OAAA,QAAA,KAAa,YAAY,gBAAmB,GAAA,cAAA;AACrD;AACgB,SAAA,gBAAA,CAAiB,UAA8B,QAAoC,EAAA;AAjBnG,EAAA,IAAA,EAAA;AAkBE,EAAM,MAAA;AAAA,IACJ;AAAA,GACE,GAAA,QAAA;AACJ,EAAO,OAAA;AAAA,IACL,MAAA,EAAA,CAAQ,EAAc,GAAA,YAAA,IAAA,IAAA,GAAA,MAAA,GAAA,YAAA,CAAA,MAAA,KAAd,IAAwB,GAAA,EAAA,GAAA,SAAA;AAAA,IAChC,MAAQ,EAAA,CAAA,YAAA,IAAA,IAAA,GAAA,MAAA,GAAA,YAAA,CAAc,MAAW,MAAA,aAAA,GAAgB,aAAa,MAAS,GAAA,MAAA;AAAA,IACvE,SAAW,EAAA,OAAA,CAAQ,QAAS,CAAA,IAAA,CAAK,SAAS,CAAA;AAAA,IAC1C,MAAA,EAAQ,SAAS,IAAK,CAAA,MAAA;AAAA,IACtB,SAAA,EAAW,aAAa,QAAQ,CAAA;AAAA,IAChC,UAAA,EAAY,SAAS,IAAK,CAAA,UAAA;AAAA,IAC1B,SAAA,EAAW,SAAS,IAAK,CAAA,SAAA;AAAA,IACzB,MAAM,QAAS,CAAA;AAAA,GACjB;AACF;AACgB,SAAA,gBAAA,CAAiB,OAAkB,QAAkB,EAAA;AACnE,EAAO,OAAA;AAAA,IACL,MAAM,MAAoC,GAAA;AACxC,MAAA,MAAM,MAAM,aAAc,EAAA;AAC1B,MAAA,OAAO,gBAAiB,CAAA,KAAA,CAAM,WAAY,EAAA,EAAG,QAAQ,CAAA;AAAA,KACvD;AAAA,IACA,MAAM,OAAqC,GAAA;AACzC,MAAA,MAAM,MAAM,OAAQ,EAAA;AACpB,MAAA,OAAO,gBAAiB,CAAA,KAAA,CAAM,WAAY,EAAA,EAAG,QAAQ,CAAA;AAAA;AACvD,GACF;AACF"}
@@ -0,0 +1,115 @@
1
+ import {unionIntervals}from'./sleep.js';import {addDays,isoDate}from'./time.js';import {MAX_INTRADAY_BUCKETS,INTRADAY_BUCKET_MINUTES,INTRADAY_RANGES}from'./types.js';const BUCKET_MS = INTRADAY_BUCKET_MINUTES * 6e4;
2
+ const DAY_MS = 864e5;
3
+ const pad2 = (n) => String(n).padStart(2, "0");
4
+ const floorToBucket = (t) => t - (t % BUCKET_MS + BUCKET_MS) % BUCKET_MS;
5
+ function nameOf(start, clock) {
6
+ const wall = start + clock.offsetMs(start);
7
+ const minute = Math.floor((wall % DAY_MS + DAY_MS) % DAY_MS / 6e4);
8
+ const quarter = minute - minute % INTRADAY_BUCKET_MINUTES;
9
+ return {
10
+ date: isoDate(wall),
11
+ t: `${pad2(Math.floor(quarter / 60))}:${pad2(quarter % 60)}`
12
+ };
13
+ }
14
+ const inRange = (v, [lo, hi]) => Number.isFinite(v) && v >= lo && v <= hi;
15
+ function toBucket(slot) {
16
+ const bucket = {
17
+ t: slot.t
18
+ };
19
+ if (slot.hrCount) bucket.hr = Math.round(slot.hrSum / slot.hrCount);
20
+ if (slot.hrvCount) bucket.hrv = Math.round(slot.hrvSum / slot.hrvCount);
21
+ const steps = Math.round(slot.steps);
22
+ if (steps > 0 && inRange(steps, INTRADAY_RANGES.steps)) bucket.steps = steps;
23
+ if (slot.asleepMs > 0 && slot.asleepMs * 2 >= slot.spanMs) bucket.sleep = true;
24
+ if (slot.workout) bucket.workout = true;
25
+ return Object.keys(bucket).length > 1 ? bucket : void 0;
26
+ }
27
+ function buildIntraday(input, opts) {
28
+ var _a, _b;
29
+ const {
30
+ clock,
31
+ from,
32
+ to
33
+ } = opts;
34
+ const windowStart = clock.startOfDay(from);
35
+ const windowEnd = Math.min(clock.startOfDay(addDays(to, 1)), (_a = opts.until) != null ? _a : Infinity);
36
+ const slots = /* @__PURE__ */ new Map();
37
+ const byName = /* @__PURE__ */ new Map();
38
+ for (let start = floorToBucket(windowStart); start < windowEnd; start += BUCKET_MS) {
39
+ const {
40
+ date,
41
+ t
42
+ } = nameOf(start, clock);
43
+ if (date >= from && date <= to) {
44
+ const key = `${date} ${t}`;
45
+ const slot = (_b = byName.get(key)) != null ? _b : {
46
+ date,
47
+ t,
48
+ spanMs: 0,
49
+ hrSum: 0,
50
+ hrCount: 0,
51
+ hrvSum: 0,
52
+ hrvCount: 0,
53
+ steps: 0,
54
+ asleepMs: 0,
55
+ workout: false
56
+ };
57
+ slot.spanMs += BUCKET_MS;
58
+ byName.set(key, slot);
59
+ slots.set(start, slot);
60
+ }
61
+ }
62
+ const overlapping = (start, end) => {
63
+ const a = Math.max(start, windowStart);
64
+ const b = Math.min(end, windowEnd);
65
+ const out2 = [];
66
+ for (let bucket = floorToBucket(a); bucket < b; bucket += BUCKET_MS) {
67
+ const slot = slots.get(bucket);
68
+ if (slot) out2.push([slot, Math.min(b, bucket + BUCKET_MS) - Math.max(a, bucket)]);
69
+ }
70
+ return out2;
71
+ };
72
+ const at = (t) => t >= windowStart && t < windowEnd ? slots.get(floorToBucket(t)) : void 0;
73
+ for (const s of input.heartRate) {
74
+ const slot = at(s.t);
75
+ if (slot && inRange(s.value, INTRADAY_RANGES.hr)) {
76
+ slot.hrSum += s.value;
77
+ slot.hrCount += 1;
78
+ }
79
+ }
80
+ for (const s of input.hrv) {
81
+ const slot = at(s.t);
82
+ if (slot && inRange(s.value, INTRADAY_RANGES.hrv)) {
83
+ slot.hrvSum += s.value;
84
+ slot.hrvCount += 1;
85
+ }
86
+ }
87
+ for (const s of input.steps) {
88
+ if (Number.isFinite(s.value) && s.value > 0) {
89
+ if (s.end > s.start) {
90
+ for (const [slot, ms] of overlapping(s.start, s.end)) slot.steps += s.value * ms / (s.end - s.start);
91
+ } else {
92
+ const slot = at(s.start);
93
+ if (slot) slot.steps += s.value;
94
+ }
95
+ }
96
+ }
97
+ for (const [a, b] of unionIntervals(input.asleep)) {
98
+ for (const [slot, ms] of overlapping(a, b)) slot.asleepMs += ms;
99
+ }
100
+ for (const [a, b] of input.workouts) {
101
+ for (const [slot] of overlapping(a, b)) slot.workout = true;
102
+ }
103
+ const out = {};
104
+ for (const slot of byName.values()) {
105
+ const bucket = toBucket(slot);
106
+ if (bucket) {
107
+ if (!out[slot.date]) out[slot.date] = [];
108
+ out[slot.date].push(bucket);
109
+ }
110
+ }
111
+ for (const date of Object.keys(out)) {
112
+ out[date] = out[date].sort((a, b) => a.t.localeCompare(b.t)).slice(0, MAX_INTRADAY_BUCKETS);
113
+ }
114
+ return out;
115
+ }export{buildIntraday};//# sourceMappingURL=intraday.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intraday.js","sources":["../../../src/features/health/intraday.ts"],"sourcesContent":["/**\n * The day in 15-minute buckets, for Stress and the Energy Bank. No platform\n * code: the readers hand over samples, this cuts them.\n *\n * - A bucket is a local quarter-hour (00:00, 00:15 ... 23:45) in `clock`'s\n * zone and belongs to the local date it starts on: the sleep that ends this\n * morning fills today's 00:00-07:00, the 23:15 bucket last night is\n * yesterday's.\n * - Every zone in use is a whole number of quarter-hours from UTC, so the\n * buckets are the UTC quarter-hours, each named by its local start. The\n * hour a fall-back change repeats has the same names twice: both 01:00\n * stretches are one bucket, so a day never has more than 96. The hour a\n * spring-forward change skips has none.\n * - hr, hrv: the mean of the samples taken in the bucket. A sample outside\n * the plausible range is left out, never averaged in.\n * - steps: a count over a stretch (a statistics bucket, a sample) is shared\n * between the buckets it spans in proportion to the time in each.\n * - sleep: asleep for at least half the bucket (sleep.ts asleepIntervals).\n * - workout: any part of the bucket inside a workout.\n * - Nothing from `until` on (the end of the data read: now, for today), and\n * a bucket with nothing in it is not sent.\n */\nimport type { SpanValue, TimedValue } from './model';\nimport { unionIntervals, type Interval } from './sleep';\nimport { addDays, isoDate, type ZoneClock } from './time';\nimport { INTRADAY_BUCKET_MINUTES, INTRADAY_RANGES, MAX_INTRADAY_BUCKETS, type IntradayBucket } from './types';\n\nconst BUCKET_MS = INTRADAY_BUCKET_MINUTES * 60_000;\nconst DAY_MS = 86_400_000;\n\nexport interface IntradayInput {\n heartRate: readonly TimedValue[];\n /** HRV readings in the day's own method (SDNN on iOS, RMSSD on Android). */\n hrv: readonly TimedValue[];\n steps: readonly SpanValue[];\n /** When the person was asleep. */\n asleep: readonly Interval[];\n workouts: readonly Interval[];\n}\n\nexport interface IntradayOptions {\n /** First and last local date to build, both included. */\n from: string;\n to: string;\n clock: ZoneClock;\n /** Where the data read ends (epoch ms); no bucket starts at or after it. Undefined: the dates are complete. */\n until?: number;\n}\n\n/** One local quarter-hour being filled. Two UTC quarter-hours share one in the repeated fall-back hour. */\ninterface Slot {\n date: string;\n t: string;\n /** Real time the bucket covers: 15 minutes, 30 for the repeated hour. */\n spanMs: number;\n hrSum: number;\n hrCount: number;\n hrvSum: number;\n hrvCount: number;\n steps: number;\n asleepMs: number;\n workout: boolean;\n}\n\nconst pad2 = (n: number) => String(n).padStart(2, '0');\n\n/** Start of the UTC quarter-hour an instant falls in. */\nconst floorToBucket = (t: number) => t - (((t % BUCKET_MS) + BUCKET_MS) % BUCKET_MS);\n\n/** The local date and HH:MM a bucket starting at `start` is named by. */\nfunction nameOf(start: number, clock: ZoneClock): { date: string; t: string } {\n const wall = start + clock.offsetMs(start);\n const minute = Math.floor((((wall % DAY_MS) + DAY_MS) % DAY_MS) / 60_000);\n const quarter = minute - (minute % INTRADAY_BUCKET_MINUTES);\n return { date: isoDate(wall), t: `${pad2(Math.floor(quarter / 60))}:${pad2(quarter % 60)}` };\n}\n\nconst inRange = (v: number, [lo, hi]: readonly [number, number]) => Number.isFinite(v) && v >= lo && v <= hi;\n\n/** What a filled slot sends, or undefined when it has nothing. */\nfunction toBucket(slot: Slot): IntradayBucket | undefined {\n const bucket: IntradayBucket = { t: slot.t };\n if (slot.hrCount) bucket.hr = Math.round(slot.hrSum / slot.hrCount);\n if (slot.hrvCount) bucket.hrv = Math.round(slot.hrvSum / slot.hrvCount);\n const steps = Math.round(slot.steps);\n if (steps > 0 && inRange(steps, INTRADAY_RANGES.steps)) bucket.steps = steps;\n if (slot.asleepMs > 0 && slot.asleepMs * 2 >= slot.spanMs) bucket.sleep = true;\n if (slot.workout) bucket.workout = true;\n return Object.keys(bucket).length > 1 ? bucket : undefined;\n}\n\n/** Buckets keyed by local date, each date's sorted by `t`; a date with none is absent. */\nexport function buildIntraday(input: IntradayInput, opts: IntradayOptions): Record<string, IntradayBucket[]> {\n const { clock, from, to } = opts;\n const windowStart = clock.startOfDay(from);\n const windowEnd = Math.min(clock.startOfDay(addDays(to, 1)), opts.until ?? Infinity);\n\n // Every bucket in the window, by the UTC quarter-hour it starts at.\n const slots = new Map<number, Slot>();\n const byName = new Map<string, Slot>();\n for (let start = floorToBucket(windowStart); start < windowEnd; start += BUCKET_MS) {\n const { date, t } = nameOf(start, clock);\n if (date >= from && date <= to) {\n const key = `${date} ${t}`;\n const slot = byName.get(key) ?? {\n date,\n t,\n spanMs: 0,\n hrSum: 0,\n hrCount: 0,\n hrvSum: 0,\n hrvCount: 0,\n steps: 0,\n asleepMs: 0,\n workout: false,\n };\n slot.spanMs += BUCKET_MS;\n byName.set(key, slot);\n slots.set(start, slot);\n }\n }\n\n /** Each bucket a stretch overlaps, with how much of it (ms). */\n const overlapping = (start: number, end: number) => {\n const a = Math.max(start, windowStart);\n const b = Math.min(end, windowEnd);\n const out: Array<[Slot, number]> = [];\n for (let bucket = floorToBucket(a); bucket < b; bucket += BUCKET_MS) {\n const slot = slots.get(bucket);\n if (slot) out.push([slot, Math.min(b, bucket + BUCKET_MS) - Math.max(a, bucket)]);\n }\n return out;\n };\n const at = (t: number) => (t >= windowStart && t < windowEnd ? slots.get(floorToBucket(t)) : undefined);\n\n for (const s of input.heartRate) {\n const slot = at(s.t);\n if (slot && inRange(s.value, INTRADAY_RANGES.hr)) {\n slot.hrSum += s.value;\n slot.hrCount += 1;\n }\n }\n for (const s of input.hrv) {\n const slot = at(s.t);\n if (slot && inRange(s.value, INTRADAY_RANGES.hrv)) {\n slot.hrvSum += s.value;\n slot.hrvCount += 1;\n }\n }\n for (const s of input.steps) {\n if (Number.isFinite(s.value) && s.value > 0) {\n if (s.end > s.start) {\n for (const [slot, ms] of overlapping(s.start, s.end)) slot.steps += (s.value * ms) / (s.end - s.start);\n } else {\n const slot = at(s.start);\n if (slot) slot.steps += s.value;\n }\n }\n }\n for (const [a, b] of unionIntervals(input.asleep)) {\n for (const [slot, ms] of overlapping(a, b)) slot.asleepMs += ms;\n }\n for (const [a, b] of input.workouts) {\n for (const [slot] of overlapping(a, b)) slot.workout = true;\n }\n\n const out: Record<string, IntradayBucket[]> = {};\n for (const slot of byName.values()) {\n const bucket = toBucket(slot);\n if (bucket) {\n if (!out[slot.date]) out[slot.date] = [];\n out[slot.date].push(bucket);\n }\n }\n for (const date of Object.keys(out)) {\n out[date] = out[date].sort((a, b) => a.t.localeCompare(b.t)).slice(0, MAX_INTRADAY_BUCKETS);\n }\n return out;\n}\n"],"names":["out"],"mappings":"sKA0BA,MAAM,YAAY,uBAA0B,GAAA,GAAA;AAC5C,MAAM,MAAS,GAAA,KAAA;AAiCf,MAAM,IAAA,GAAO,CAAC,CAAc,KAAA,MAAA,CAAO,CAAC,CAAE,CAAA,QAAA,CAAS,GAAG,GAAG,CAAA;AAGrD,MAAM,gBAAgB,CAAC,CAAA,KAAc,CAAK,GAAA,CAAA,CAAA,GAAI,YAAY,SAAa,IAAA,SAAA;AAGvE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dailyTotals: [],
4
+ stepSpans: [],
4
5
  heartRate: [],
5
6
  restingHr: [],
6
7
  hrv: [],
@@ -16,6 +17,8 @@ function emptyRawHealthData(hrvMethod) {
16
17
  bmi: [],
17
18
  waistCm: [],
18
19
  bodyTempC: [],
20
+ wristTempC: [],
21
+ mindful: [],
19
22
  bloodPressure: [],
20
23
  glucose: []
21
24
  };
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sources":["../../../src/features/health/model.ts"],"sourcesContent":["/**\n * What a platform reader hands the day builder: one neutral shape for HealthKit\n * and Health Connect, so the bucketing (days, nights, zones, ranges) is written\n * and tested once. The `fromHealthKit` / `fromHealthConnect` mappers turn each\n * library's records into this; the readers only fetch.\n *\n * Instants are epoch milliseconds.\n */\n\nimport type { MealRelation } from './types';\n\n/** Totals the platform already de-duplicated across sources (phone + watch), per local day. */\nexport interface DailyTotals {\n date: string;\n steps?: number;\n activeCalories?: number;\n distanceMeters?: number;\n activeMinutes?: number;\n}\n\nexport interface TimedValue {\n t: number;\n value: number;\n}\n\nexport type SleepStage = 'inBed' | 'asleep' | 'light' | 'deep' | 'rem' | 'awake' | 'outOfBed';\n\nexport interface SleepSegment {\n start: number;\n end: number;\n stage: SleepStage;\n /**\n * Which writer recorded it (HealthKit bundle id, Health Connect data\n * origin). A night is taken from ONE writer so a watch and a phone\n * tracking the same night are never added together.\n */\n sourceKey: string;\n}\n\nexport interface RawWorkout {\n id: string;\n start: number;\n end: number;\n /** Already normalized (see workoutTypes.ts). */\n type: string;\n /** Active time without pauses, when the source knows it. */\n durationMin?: number;\n calories?: number;\n distanceMeters?: number;\n /** From the source's own workout statistics; else derived from heart-rate samples. */\n avgHr?: number;\n maxHr?: number;\n}\n\n/** A blood-pressure reading another app wrote (Omron, Withings ...), with the store's id. */\nexport interface RawBloodPressure {\n id: string;\n t: number;\n systolic: number;\n diastolic: number;\n}\n\nexport interface RawGlucose {\n id: string;\n t: number;\n mgdl: number;\n meal?: MealRelation;\n}\n\nexport interface RawHealthData {\n dailyTotals: DailyTotals[];\n heartRate: TimedValue[];\n restingHr: TimedValue[];\n hrv: TimedValue[];\n hrvMethod: 'rmssd' | 'sdnn';\n sleep: SleepSegment[];\n workouts: RawWorkout[];\n weightKg: TimedValue[];\n vo2Max: TimedValue[];\n /** Percent, 0-100. */\n spo2: TimedValue[];\n respiratoryRate: TimedValue[];\n /** Body measurements another app (a brand scale's own app) wrote. Percent 0-100 for body fat. */\n bodyFatPct: TimedValue[];\n leanMassKg: TimedValue[];\n bmi: TimedValue[];\n waistCm: TimedValue[];\n bodyTempC: TimedValue[];\n bloodPressure: RawBloodPressure[];\n glucose: RawGlucose[];\n}\n\nexport function emptyRawHealthData(hrvMethod: 'rmssd' | 'sdnn'): RawHealthData {\n return {\n dailyTotals: [],\n heartRate: [],\n restingHr: [],\n hrv: [],\n hrvMethod,\n sleep: [],\n workouts: [],\n weightKg: [],\n vo2Max: [],\n spo2: [],\n respiratoryRate: [],\n bodyFatPct: [],\n leanMassKg: [],\n bmi: [],\n waistCm: [],\n bodyTempC: [],\n bloodPressure: [],\n glucose: [],\n };\n}\n"],"names":[],"mappings":"AAqFO,SAAS,mBAAmB,SAA4C,EAAA;AAC7E,EAAO,OAAA;AAAA,IACL,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,WAAW,EAAC;AAAA,IACZ,KAAK,EAAC;AAAA,IACN,SAAA;AAAA,IACA,OAAO,EAAC;AAAA,IACR,UAAU,EAAC;AAAA,IACX,UAAU,EAAC;AAAA,IACX,QAAQ,EAAC;AAAA,IACT,MAAM,EAAC;AAAA,IACP,iBAAiB,EAAC;AAAA,IAClB,YAAY,EAAC;AAAA,IACb,YAAY,EAAC;AAAA,IACb,KAAK,EAAC;AAAA,IACN,SAAS,EAAC;AAAA,IACV,WAAW,EAAC;AAAA,IACZ,eAAe,EAAC;AAAA,IAChB,SAAS;AAAC,GACZ;AACF"}
1
+ {"version":3,"file":"model.js","sources":["../../../src/features/health/model.ts"],"sourcesContent":["/**\n * What a platform reader hands the day builder: one neutral shape for HealthKit\n * and Health Connect, so the bucketing (days, nights, zones, ranges) is written\n * and tested once. The `fromHealthKit` / `fromHealthConnect` mappers turn each\n * library's records into this; the readers only fetch.\n *\n * Instants are epoch milliseconds.\n */\n\nimport type { MealRelation } from './types';\n\n/** Totals the platform already de-duplicated across sources (phone + watch), per local day. */\nexport interface DailyTotals {\n date: string;\n steps?: number;\n activeCalories?: number;\n distanceMeters?: number;\n activeMinutes?: number;\n /** Minutes outdoors in daylight (Apple Watch, iOS 17+). */\n daylightMinutes?: number;\n /** Resting (basal) energy, kcal. */\n restingCalories?: number;\n}\n\nexport interface TimedValue {\n t: number;\n value: number;\n}\n\nexport interface TimeSpan {\n start: number;\n end: number;\n}\n\n/** An amount counted over a stretch of time (the steps in a statistics bucket). */\nexport interface SpanValue {\n start: number;\n end: number;\n value: number;\n}\n\nexport type SleepStage = 'inBed' | 'asleep' | 'light' | 'deep' | 'rem' | 'awake' | 'outOfBed';\n\nexport interface SleepSegment {\n start: number;\n end: number;\n stage: SleepStage;\n /**\n * Which writer recorded it (HealthKit bundle id, Health Connect data\n * origin). A night is taken from ONE writer so a watch and a phone\n * tracking the same night are never added together.\n */\n sourceKey: string;\n /**\n * An `inBed` that only restates a record's own span (a Health Connect\n * sleep session) rather than one the source recorded on its own (the\n * iPhone's bedtime, a sleep app's \"in bed\"). It still counts as time in\n * bed, but sleep latency is never measured from it.\n */\n implied?: boolean;\n}\n\nexport interface RawWorkout {\n id: string;\n start: number;\n end: number;\n /** Already normalized (see workoutTypes.ts). */\n type: string;\n /** Active time without pauses, when the source knows it. */\n durationMin?: number;\n calories?: number;\n distanceMeters?: number;\n /** From the source's own workout statistics; else derived from heart-rate samples. */\n avgHr?: number;\n maxHr?: number;\n /** Elevation climbed during the workout, meters. */\n elevationMeters?: number;\n}\n\n/** A blood-pressure reading another app wrote (Omron, Withings ...), with the store's id. */\nexport interface RawBloodPressure {\n id: string;\n t: number;\n systolic: number;\n diastolic: number;\n}\n\nexport interface RawGlucose {\n id: string;\n t: number;\n mgdl: number;\n meal?: MealRelation;\n}\n\nexport interface RawHealthData {\n dailyTotals: DailyTotals[];\n /**\n * Steps per quarter-hour for the 15-minute buckets (intraday.ts), merged\n * across phone and watch by the platform like the daily totals.\n */\n stepSpans: SpanValue[];\n heartRate: TimedValue[];\n restingHr: TimedValue[];\n hrv: TimedValue[];\n hrvMethod: 'rmssd' | 'sdnn';\n sleep: SleepSegment[];\n workouts: RawWorkout[];\n weightKg: TimedValue[];\n vo2Max: TimedValue[];\n /** Percent, 0-100. */\n spo2: TimedValue[];\n respiratoryRate: TimedValue[];\n /** Body measurements another app (a brand scale's own app) wrote. Percent 0-100 for body fat. */\n bodyFatPct: TimedValue[];\n leanMassKg: TimedValue[];\n bmi: TimedValue[];\n waistCm: TimedValue[];\n bodyTempC: TimedValue[];\n /** Overnight wrist temperature (absolute C), at the END of the night it was measured over. */\n wristTempC: TimedValue[];\n /** Mindfulness sessions (meditation, breathing). */\n mindful: TimeSpan[];\n bloodPressure: RawBloodPressure[];\n glucose: RawGlucose[];\n}\n\nexport function emptyRawHealthData(hrvMethod: 'rmssd' | 'sdnn'): RawHealthData {\n return {\n dailyTotals: [],\n stepSpans: [],\n heartRate: [],\n restingHr: [],\n hrv: [],\n hrvMethod,\n sleep: [],\n workouts: [],\n weightKg: [],\n vo2Max: [],\n spo2: [],\n respiratoryRate: [],\n bodyFatPct: [],\n leanMassKg: [],\n bmi: [],\n waistCm: [],\n bodyTempC: [],\n wristTempC: [],\n mindful: [],\n bloodPressure: [],\n glucose: [],\n };\n}\n"],"names":[],"mappings":"AAsHO,SAAS,mBAAmB,SAA4C,EAAA;AAC7E,EAAO,OAAA;AAAA,IACL,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,WAAW,EAAC;AAAA,IACZ,WAAW,EAAC;AAAA,IACZ,KAAK,EAAC;AAAA,IACN,SAAA;AAAA,IACA,OAAO,EAAC;AAAA,IACR,UAAU,EAAC;AAAA,IACX,UAAU,EAAC;AAAA,IACX,QAAQ,EAAC;AAAA,IACT,MAAM,EAAC;AAAA,IACP,iBAAiB,EAAC;AAAA,IAClB,YAAY,EAAC;AAAA,IACb,YAAY,EAAC;AAAA,IACb,KAAK,EAAC;AAAA,IACN,SAAS,EAAC;AAAA,IACV,WAAW,EAAC;AAAA,IACZ,YAAY,EAAC;AAAA,IACb,SAAS,EAAC;AAAA,IACV,eAAe,EAAC;AAAA,IAChB,SAAS;AAAC,GACZ;AACF"}
@@ -1,6 +1,9 @@
1
1
  const HEALTH_DATA_TYPES = [{
2
2
  id: "sleep",
3
3
  label: "Sleep"
4
+ }, {
5
+ id: "wristTemp",
6
+ label: "Wrist temperature"
4
7
  }, {
5
8
  id: "heartRate",
6
9
  label: "Heart rate"
@@ -19,12 +22,24 @@ const HEALTH_DATA_TYPES = [{
19
22
  }, {
20
23
  id: "activeCalories",
21
24
  label: "Active energy"
25
+ }, {
26
+ id: "restingCalories",
27
+ label: "Resting energy"
22
28
  }, {
23
29
  id: "exercise",
24
30
  label: "Exercise minutes"
25
31
  }, {
26
32
  id: "workouts",
27
33
  label: "Workouts"
34
+ }, {
35
+ id: "elevation",
36
+ label: "Elevation gained"
37
+ }, {
38
+ id: "daylight",
39
+ label: "Time in daylight"
40
+ }, {
41
+ id: "mindful",
42
+ label: "Mindful minutes"
28
43
  }, {
29
44
  id: "weight",
30
45
  label: "Weight"
@@ -1 +1 @@
1
- {"version":3,"file":"reader.js","sources":["../../../src/features/health/reader.ts"],"sourcesContent":["/**\n * What the sync engine needs from a platform. healthkitReader.ts (iOS) and\n * healthConnectReader.ts (Android) implement it; tests use fakes.\n */\nimport type { RawHealthData } from './model';\nimport type { ZoneClock } from './time';\nimport type { DeviceHealthSource } from './types';\n\nexport type HealthDataType =\n | 'steps'\n | 'distance'\n | 'activeCalories'\n | 'exercise'\n | 'heartRate'\n | 'restingHr'\n | 'hrv'\n | 'sleep'\n | 'workouts'\n | 'weight'\n | 'vo2Max'\n | 'spo2'\n | 'respiratoryRate'\n | 'bodyFat'\n | 'leanMass'\n | 'bmi'\n | 'waist'\n | 'bodyTemp'\n | 'bloodPressure'\n | 'bloodGlucose';\n\n/** What the screen lists under \"Shared with Yantra\", in this order. */\nexport const HEALTH_DATA_TYPES: ReadonlyArray<{ id: HealthDataType; label: string }> = [\n { id: 'sleep', label: 'Sleep' },\n { id: 'heartRate', label: 'Heart rate' },\n { id: 'restingHr', label: 'Resting heart rate' },\n { id: 'hrv', label: 'Heart rate variability' },\n { id: 'steps', label: 'Steps' },\n { id: 'distance', label: 'Distance' },\n { id: 'activeCalories', label: 'Active energy' },\n { id: 'exercise', label: 'Exercise minutes' },\n { id: 'workouts', label: 'Workouts' },\n { id: 'weight', label: 'Weight' },\n { id: 'vo2Max', label: 'VO2 max' },\n { id: 'spo2', label: 'Blood oxygen' },\n { id: 'respiratoryRate', label: 'Respiratory rate' },\n { id: 'bodyFat', label: 'Body fat' },\n { id: 'leanMass', label: 'Lean body mass' },\n { id: 'bmi', label: 'BMI' },\n { id: 'waist', label: 'Waist' },\n { id: 'bodyTemp', label: 'Body temperature' },\n { id: 'bloodPressure', label: 'Blood pressure' },\n { id: 'bloodGlucose', label: 'Blood glucose' },\n];\n\nexport function labelOf(type: HealthDataType): string {\n return HEALTH_DATA_TYPES.find((t) => t.id === type)?.label ?? type;\n}\n\nexport type HealthAvailability =\n | { status: 'available' }\n /** Android: the Health Connect app is not installed (Android 13 and older). */\n | { status: 'not-installed' }\n /** Android: Health Connect is installed but needs an update. */\n | { status: 'needs-update' }\n | { status: 'unsupported'; reason: string };\n\nexport interface ReadResult {\n raw: RawHealthData;\n /** Types that could not be read (permission off, provider error). The rest still syncs. */\n unreadable: HealthDataType[];\n}\n\nexport interface HealthReader {\n readonly source: DeviceHealthSource;\n /** What the platform calls its health store, for the screen. */\n readonly storeName: string;\n availability(): Promise<HealthAvailability>;\n /**\n * Shows the system permission sheet. Resolves with the types granted, or\n * null when the platform does not tell apps (HealthKit hides read access).\n */\n requestAccess(): Promise<HealthDataType[] | null>;\n /** Granted read types, or null when the platform does not tell apps. */\n grantedTypes(): Promise<HealthDataType[] | null>;\n /** Everything recorded between two instants. */\n read(range: { start: number; end: number }, clock: ZoneClock): Promise<ReadResult>;\n /** Give the permissions back where the platform allows it (Health Connect); a no-op on iOS. */\n revoke(): Promise<void>;\n /** The platform's own screen for this app's permissions, when it has one. */\n openSettings?(): Promise<void>;\n}\n"],"names":[],"mappings":"AAUO,MAAM,oBAGR,CAAC;AAAA,EACJ,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,WAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,WAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,KAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,gBAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,QAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,QAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,MAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,iBAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,SAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,KAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,eAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,cAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAC;AACM,SAAS,QAAQ,IAA8B,EAAA;AA1EtD,EAAA,IAAA,EAAA,EAAA,EAAA;AA2EE,EAAO,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,iBAAA,CAAkB,KAAK,CAAK,CAAA,KAAA,CAAA,CAAE,OAAO,IAAI,CAAA,KAAzC,IAA4C,GAAA,MAAA,GAAA,EAAA,CAAA,KAAA,KAA5C,IAAqD,GAAA,EAAA,GAAA,IAAA;AAC9D"}
1
+ {"version":3,"file":"reader.js","sources":["../../../src/features/health/reader.ts"],"sourcesContent":["/**\n * What the sync engine needs from a platform. healthkitReader.ts (iOS) and\n * healthConnectReader.ts (Android) implement it; tests use fakes.\n */\nimport type { RawHealthData } from './model';\nimport type { ZoneClock } from './time';\nimport type { DeviceHealthSource } from './types';\n\nexport type HealthDataType =\n | 'steps'\n | 'distance'\n | 'activeCalories'\n | 'restingCalories'\n | 'exercise'\n | 'heartRate'\n | 'restingHr'\n | 'hrv'\n | 'sleep'\n | 'wristTemp'\n | 'workouts'\n | 'elevation'\n | 'daylight'\n | 'mindful'\n | 'weight'\n | 'vo2Max'\n | 'spo2'\n | 'respiratoryRate'\n | 'bodyFat'\n | 'leanMass'\n | 'bmi'\n | 'waist'\n | 'bodyTemp'\n | 'bloodPressure'\n | 'bloodGlucose';\n\n/**\n * What the screen lists under \"Data Yantra reads\", in this order. Each\n * platform reads some of them (`HealthReader.types`); the screen lists those.\n */\nexport const HEALTH_DATA_TYPES: ReadonlyArray<{ id: HealthDataType; label: string }> = [\n { id: 'sleep', label: 'Sleep' },\n { id: 'wristTemp', label: 'Wrist temperature' },\n { id: 'heartRate', label: 'Heart rate' },\n { id: 'restingHr', label: 'Resting heart rate' },\n { id: 'hrv', label: 'Heart rate variability' },\n { id: 'steps', label: 'Steps' },\n { id: 'distance', label: 'Distance' },\n { id: 'activeCalories', label: 'Active energy' },\n { id: 'restingCalories', label: 'Resting energy' },\n { id: 'exercise', label: 'Exercise minutes' },\n { id: 'workouts', label: 'Workouts' },\n { id: 'elevation', label: 'Elevation gained' },\n { id: 'daylight', label: 'Time in daylight' },\n { id: 'mindful', label: 'Mindful minutes' },\n { id: 'weight', label: 'Weight' },\n { id: 'vo2Max', label: 'VO2 max' },\n { id: 'spo2', label: 'Blood oxygen' },\n { id: 'respiratoryRate', label: 'Respiratory rate' },\n { id: 'bodyFat', label: 'Body fat' },\n { id: 'leanMass', label: 'Lean body mass' },\n { id: 'bmi', label: 'BMI' },\n { id: 'waist', label: 'Waist' },\n { id: 'bodyTemp', label: 'Body temperature' },\n { id: 'bloodPressure', label: 'Blood pressure' },\n { id: 'bloodGlucose', label: 'Blood glucose' },\n];\n\nexport function labelOf(type: HealthDataType): string {\n return HEALTH_DATA_TYPES.find((t) => t.id === type)?.label ?? type;\n}\n\nexport type HealthAvailability =\n | { status: 'available' }\n /** Android: the Health Connect app is not installed (Android 13 and older). */\n | { status: 'not-installed' }\n /** Android: Health Connect is installed but needs an update. */\n | { status: 'needs-update' }\n | { status: 'unsupported'; reason: string };\n\nexport interface ReadResult {\n raw: RawHealthData;\n /** Types that could not be read (permission off, provider error). The rest still syncs. */\n unreadable: HealthDataType[];\n /**\n * Types this version of the app reads that the person was never asked\n * about (added in an update, or by a newer OS). They are not read until\n * the permission sheet shows them; the rest still syncs.\n */\n needsAccess?: HealthDataType[];\n}\n\nexport interface HealthReader {\n readonly source: DeviceHealthSource;\n /** What the platform calls its health store, for the screen. */\n readonly storeName: string;\n /** The data types read on this device (platform and OS version). */\n readonly types: readonly HealthDataType[];\n availability(): Promise<HealthAvailability>;\n /**\n * Shows the system permission sheet. Resolves with the types granted, or\n * null when the platform does not tell apps (HealthKit hides read access).\n */\n requestAccess(): Promise<HealthDataType[] | null>;\n /** Granted read types, or null when the platform does not tell apps. */\n grantedTypes(): Promise<HealthDataType[] | null>;\n /** Everything recorded between two instants. */\n read(range: { start: number; end: number }, clock: ZoneClock): Promise<ReadResult>;\n /** Give the permissions back where the platform allows it (Health Connect); a no-op on iOS. */\n revoke(): Promise<void>;\n /** The platform's own screen for this app's permissions, when it has one. */\n openSettings?(): Promise<void>;\n}\n"],"names":[],"mappings":"AAaO,MAAM,oBAGR,CAAC;AAAA,EACJ,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,WAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,WAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,WAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,KAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,OAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,UAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,gBAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAAG,EAAA;AAAA,EACD,EAAI,EAAA,iBAAA;AAAA,EACJ,KAAO,EAAA;AACT,CAA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,EAAA,GAAA,iBAAA,CAAkB,KAAK,CAAK,CAAA,KAAA,CAAA,CAAE,OAAO,IAAI,CAAA,KAAzC,IAA4C,GAAA,MAAA,GAAA,EAAA,CAAA,KAAA,KAA5C,IAAqD,GAAA,EAAA,GAAA,IAAA;AAC9D"}
@@ -15,7 +15,9 @@ var __spreadValues = (a, b) => {
15
15
  return a;
16
16
  };
17
17
  const SESSION_GAP_MS = 2 * 36e5;
18
+ const AWAKENING_MIN_MS = 2 * 6e4;
18
19
  const ASLEEP = ["asleep", "light", "deep", "rem"];
20
+ const AWAKE = ["awake", "outOfBed"];
19
21
  function unionIntervals(intervals) {
20
22
  const sorted = intervals.filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0]);
21
23
  const out = [];
@@ -29,6 +31,19 @@ function unionIntervals(intervals) {
29
31
  function measure(intervals) {
30
32
  return unionIntervals(intervals).reduce((n, [a, b]) => n + (b - a), 0);
31
33
  }
34
+ function subtract(a, b) {
35
+ const cut = unionIntervals(b);
36
+ const out = [];
37
+ for (const [a0, a1] of unionIntervals(a)) {
38
+ let from = a0;
39
+ for (const [b0, b1] of cut.filter(([c0, c1]) => c1 > a0 && c0 < a1)) {
40
+ if (b0 > from) out.push([from, b0]);
41
+ from = Math.max(from, b1);
42
+ }
43
+ if (from < a1) out.push([from, a1]);
44
+ }
45
+ return out;
46
+ }
32
47
  function intersect(a, b) {
33
48
  const out = [];
34
49
  const ua = unionIntervals(a);
@@ -46,8 +61,7 @@ const toMin = (ms) => Math.round(ms / 6e3) / 10;
46
61
  function sessionsOf(segments) {
47
62
  var _a;
48
63
  const bySource = /* @__PURE__ */ new Map();
49
- for (const s of segments) {
50
- if (!(s.end > s.start)) continue;
64
+ for (const s of segments.filter((x) => x.end > x.start)) {
51
65
  bySource.set(s.sourceKey, [...(_a = bySource.get(s.sourceKey)) != null ? _a : [], s]);
52
66
  }
53
67
  const sessions = [];
@@ -74,6 +88,7 @@ function sessionsOf(segments) {
74
88
  function summarize(session, clock) {
75
89
  const of = (stages) => session.segments.filter((s) => stages.includes(s.stage)).map((s) => [s.start, s.end]);
76
90
  const asleep = of(ASLEEP);
91
+ const asleepUnion = unionIntervals(asleep);
77
92
  const asleepMs = measure(asleep);
78
93
  const deep = measure(of(["deep"]));
79
94
  const rem = measure(of(["rem"]));
@@ -89,11 +104,17 @@ function summarize(session, clock) {
89
104
  const end = Math.max(...(body.length ? body : session.segments).map((s) => s.end));
90
105
  const night = {
91
106
  date: clock.dateOf(end - 1),
107
+ asleep: asleepUnion,
92
108
  start,
93
109
  end,
94
110
  sourceKey: session.sourceKey
95
111
  };
96
112
  if (asleepMs > 0) night.sleepMinutes = toMin(asleepMs);
113
+ const awakeOrUp = of(AWAKE);
114
+ if (asleepUnion.length && (hasStages || awakeOrUp.length)) {
115
+ const between = [asleepUnion[0][0], asleepUnion[asleepUnion.length - 1][1]];
116
+ night.awakenings = subtract(intersect(awakeOrUp, [between]), asleepUnion).filter(([a, b]) => b - a >= AWAKENING_MIN_MS).length;
117
+ }
97
118
  if (hasStages) {
98
119
  night.deepMinutes = toMin(deep);
99
120
  night.remMinutes = toMin(rem);
@@ -118,6 +139,39 @@ const measureSession = (s) => {
118
139
  var _a;
119
140
  return (_a = s.night.inBedMinutes) != null ? _a : 0;
120
141
  };
142
+ const recordedInBed = (s) => s.stage === "inBed" && !s.implied;
143
+ function latencyMs(chosen, summaries) {
144
+ var _a;
145
+ const asleepAt = (_a = chosen.night.asleep[0]) == null ? void 0 : _a[0];
146
+ if (asleepAt === void 0) return void 0;
147
+ const starts = chosen.session.segments.filter((s) => recordedInBed(s) && s.start <= asleepAt).map((s) => s.start);
148
+ const bedtimes = summaries.filter((o) => o.session.sourceKey !== chosen.session.sourceKey && o.asleepMs === 0 && o.session.start <= asleepAt && o.session.end > asleepAt);
149
+ for (const other of bedtimes) {
150
+ const inBed = other.session.segments.filter((s) => recordedInBed(s) && s.start <= asleepAt);
151
+ if (inBed.length) starts.push(Math.min(...inBed.map((s) => s.start)));
152
+ }
153
+ return starts.length ? asleepAt - Math.min(...starts) : void 0;
154
+ }
155
+ function sleepSpans(segments) {
156
+ return unionIntervals(sessionsOf(segments).filter((s) => s.segments.some((x) => ASLEEP.includes(x.stage))).map((s) => [s.start, s.end]));
157
+ }
158
+ function asleepIntervals(segments, clock) {
159
+ const summaries = sessionsOf(segments).map((s) => summarize(s, clock)).sort((a, b) => a.session.start - b.session.start);
160
+ const asleep = [];
161
+ let pick;
162
+ let stretchEnd = -Infinity;
163
+ for (const s of summaries) {
164
+ if (pick && s.session.start < stretchEnd) {
165
+ pick = better(pick, s);
166
+ } else {
167
+ if (pick) asleep.push(...pick.night.asleep);
168
+ pick = s;
169
+ }
170
+ stretchEnd = Math.max(stretchEnd, s.session.end);
171
+ }
172
+ if (pick) asleep.push(...pick.night.asleep);
173
+ return unionIntervals(asleep);
174
+ }
121
175
  function buildNights(segments, clock) {
122
176
  const summaries = sessionsOf(segments).map((s) => summarize(s, clock));
123
177
  const best = /* @__PURE__ */ new Map();
@@ -137,7 +191,9 @@ function buildNights(segments, clock) {
137
191
  if (night.sleepMinutes !== void 0 && night.inBedMinutes !== void 0) {
138
192
  night.inBedMinutes = Math.max(night.inBedMinutes, night.sleepMinutes);
139
193
  }
194
+ const latency = latencyMs(chosen, summaries);
195
+ if (latency !== void 0) night.latencyMin = toMin(latency);
140
196
  nights.set(date, night);
141
197
  }
142
198
  return nights;
143
- }export{SESSION_GAP_MS,buildNights,unionIntervals};//# sourceMappingURL=sleep.js.map
199
+ }export{AWAKENING_MIN_MS,SESSION_GAP_MS,asleepIntervals,buildNights,sleepSpans,unionIntervals};//# sourceMappingURL=sleep.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sleep.js","sources":["../../../src/features/health/sleep.ts"],"sourcesContent":["/**\n * Nights from sleep segments.\n *\n * Rules (the contract: \"the night that ENDED on a date belongs to that date\"):\n * - Segments are grouped per writer (`sourceKey`) and chained into sessions;\n * a gap longer than SESSION_GAP_MS starts a new session.\n * - A session belongs to the local date its last segment ends on.\n * - One session per date: the one with sleep stages wins over one without\n * (a watch over a phone), then the one with the most sleep. A nap that day\n * does not replace the night, and two writers are never added together.\n * - Minutes are measured on the UNION of intervals, so overlapping samples\n * (HealthKit keeps every writer's copy) are not double counted.\n * - In bed: the session's own time in bed (minus \"out of bed\"), or a phone's\n * separate in-bed-only record over the same night when that is longer. It\n * is never less than asleep + awake.\n */\nimport type { SleepSegment, SleepStage } from './model';\nimport type { ZoneClock } from './time';\n\n/** A break this long between segments ends a session. */\nexport const SESSION_GAP_MS = 2 * 3_600_000;\n\nexport interface Night {\n date: string;\n sleepMinutes?: number;\n inBedMinutes?: number;\n deepMinutes?: number;\n remMinutes?: number;\n lightMinutes?: number;\n awakeMinutes?: number;\n start: number;\n end: number;\n sourceKey: string;\n}\n\ntype Interval = [number, number];\n\nconst ASLEEP: readonly SleepStage[] = ['asleep', 'light', 'deep', 'rem'];\n\nexport function unionIntervals(intervals: readonly Interval[]): Interval[] {\n const sorted = intervals.filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0]);\n const out: Interval[] = [];\n for (const [a, b] of sorted) {\n const last = out[out.length - 1];\n if (last && a <= last[1]) last[1] = Math.max(last[1], b);\n else out.push([a, b]);\n }\n return out;\n}\n\nfunction measure(intervals: readonly Interval[]): number {\n return unionIntervals(intervals).reduce((n, [a, b]) => n + (b - a), 0);\n}\n\nfunction intersect(a: readonly Interval[], b: readonly Interval[]): Interval[] {\n const out: Interval[] = [];\n const ua = unionIntervals(a);\n const ub = unionIntervals(b);\n for (const [a0, a1] of ua) {\n for (const [b0, b1] of ub) {\n const lo = Math.max(a0, b0);\n const hi = Math.min(a1, b1);\n if (hi > lo) out.push([lo, hi]);\n }\n }\n return out;\n}\n\nconst toMin = (ms: number) => Math.round(ms / 6_000) / 10;\n\ninterface Session {\n sourceKey: string;\n segments: SleepSegment[];\n start: number;\n end: number;\n}\n\nfunction sessionsOf(segments: readonly SleepSegment[]): Session[] {\n const bySource = new Map<string, SleepSegment[]>();\n for (const s of segments) {\n if (!(s.end > s.start)) continue;\n bySource.set(s.sourceKey, [...(bySource.get(s.sourceKey) ?? []), s]);\n }\n const sessions: Session[] = [];\n for (const [sourceKey, list] of bySource) {\n list.sort((a, b) => a.start - b.start);\n let cur: Session | null = null;\n for (const seg of list) {\n if (cur && seg.start <= cur.end + SESSION_GAP_MS) {\n cur.segments.push(seg);\n cur.end = Math.max(cur.end, seg.end);\n } else {\n cur = { sourceKey, segments: [seg], start: seg.start, end: seg.end };\n sessions.push(cur);\n }\n }\n }\n return sessions;\n}\n\ninterface Summary {\n session: Session;\n asleepMs: number;\n hasStages: boolean;\n night: Night;\n}\n\nfunction summarize(session: Session, clock: ZoneClock): Summary {\n const of = (stages: readonly SleepStage[]) =>\n session.segments.filter((s) => stages.includes(s.stage)).map((s): Interval => [s.start, s.end]);\n const asleep = of(ASLEEP);\n const asleepMs = measure(asleep);\n const deep = measure(of(['deep']));\n const rem = measure(of(['rem']));\n const light = measure(of(['light']));\n const hasStages = deep + rem + light > 0;\n // Awake inside the night: awake time that is not also recorded as asleep.\n const awakeIntervals = of(['awake']);\n const awakeMs = measure(awakeIntervals) - measure(intersect(awakeIntervals, asleep));\n const inBedAll = of(['inBed', 'awake', ...ASLEEP]);\n const outOfBed = of(['outOfBed']);\n const inBedMs = measure(inBedAll) - measure(intersect(inBedAll, outOfBed));\n const body = session.segments.filter((s) => s.stage !== 'outOfBed');\n const start = Math.min(...(body.length ? body : session.segments).map((s) => s.start));\n const end = Math.max(...(body.length ? body : session.segments).map((s) => s.end));\n\n const night: Night = { date: clock.dateOf(end - 1), start, end, sourceKey: session.sourceKey };\n if (asleepMs > 0) night.sleepMinutes = toMin(asleepMs);\n if (hasStages) {\n night.deepMinutes = toMin(deep);\n night.remMinutes = toMin(rem);\n night.lightMinutes = toMin(light);\n }\n if (awakeMs > 0 || hasStages) night.awakeMinutes = toMin(Math.max(0, awakeMs));\n if (inBedMs > 0) night.inBedMinutes = toMin(Math.max(inBedMs, asleepMs + Math.max(0, awakeMs)));\n return { session, asleepMs, hasStages, night };\n}\n\nfunction better(a: Summary, b: Summary): Summary {\n if (a.asleepMs > 0 !== b.asleepMs > 0) return a.asleepMs > 0 ? a : b;\n if (a.hasStages !== b.hasStages) return a.hasStages ? a : b;\n if (a.asleepMs !== b.asleepMs) return a.asleepMs > b.asleepMs ? a : b;\n return measureSession(a) >= measureSession(b) ? a : b;\n}\n\nconst measureSession = (s: Summary) => s.night.inBedMinutes ?? 0;\n\n/** One night per local date, keyed by the date the night ended. */\nexport function buildNights(segments: readonly SleepSegment[], clock: ZoneClock): Map<string, Night> {\n const summaries = sessionsOf(segments).map((s) => summarize(s, clock));\n const best = new Map<string, Summary>();\n for (const s of summaries) {\n const cur = best.get(s.night.date);\n best.set(s.night.date, cur ? better(cur, s) : s);\n }\n const nights = new Map<string, Night>();\n for (const [date, chosen] of best) {\n const night = { ...chosen.night };\n // A phone's own \"in bed\" record over the same night (another writer).\n // Only from sessions that record time in bed and nothing else (the\n // iPhone's bedtime schedule). Another tracker's own night is a rival\n // estimate, not a better in-bed figure.\n const otherInBed = summaries\n .filter((s) => s.session.sourceKey !== night.sourceKey && s.asleepMs === 0)\n .flatMap((s) => s.session.segments.filter((x) => x.stage === 'inBed'))\n .map((s): Interval => [s.start, s.end]);\n const touching = unionIntervals(otherInBed).filter(([a, b]) => b > night.start && a < night.end);\n if (touching.length) {\n const otherMin = toMin(measure(touching));\n if (night.inBedMinutes === undefined || otherMin > night.inBedMinutes) night.inBedMinutes = otherMin;\n }\n if (night.sleepMinutes !== undefined && night.inBedMinutes !== undefined) {\n night.inBedMinutes = Math.max(night.inBedMinutes, night.sleepMinutes);\n }\n nights.set(date, night);\n }\n return nights;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAoBO,MAAM,iBAAiB,CAAI,GAAA;AAclC,MAAM,MAAgC,GAAA,CAAC,QAAU,EAAA,OAAA,EAAS,QAAQ,KAAK,CAAA;AAChE,SAAS,eAAe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E9F,IAAA,IAAI,KAAM,CAAA,YAAA,KAAiB,MAAa,IAAA,KAAA,CAAM,iBAAiB,MAAW,EAAA;AACxE,MAAA,KAAA,CAAM,eAAe,IAAK,CAAA,GAAA,CAAI,KAAM,CAAA,YAAA,EAAc,MAAM,YAAY,CAAA;AAAA;AAEtE,IAAO,MAAA,CAAA,GAAA,CAAI,MAAM,KAAK,CAAA;AAAA;AAExB,EAAO,OAAA,MAAA;AACT"}
1
+ {"version":3,"file":"sleep.js","sources":["../../../src/features/health/sleep.ts"],"sourcesContent":["/**\n * Nights from sleep segments.\n *\n * Rules (the contract: \"the night that ENDED on a date belongs to that date\"):\n * - Segments are grouped per writer (`sourceKey`) and chained into sessions;\n * a gap longer than SESSION_GAP_MS starts a new session.\n * - A session belongs to the local date its last segment ends on.\n * - One session per date: the one with sleep stages wins over one without\n * (a watch over a phone), then the one with the most sleep. A nap that day\n * does not replace the night, and two writers are never added together.\n * - Minutes are measured on the UNION of intervals, so overlapping samples\n * (HealthKit keeps every writer's copy) are not double counted.\n * - In bed: the session's own time in bed (minus \"out of bed\"), or a phone's\n * separate in-bed-only record over the same night when that is longer. It\n * is never less than asleep + awake.\n * - Awakenings: awake (or out-of-bed) stretches of AWAKENING_MIN_MS or more\n * between the first and the last asleep segment. Only counted when the\n * writer records how the night was spent (stages or awake segments); a\n * writer that only says \"asleep\" never claims 0.\n * - Latency: from getting into bed to the first asleep segment, only when\n * in bed was recorded on its own (the iPhone's bedtime, a sleep app's \"in\n * bed\"), never from a record's own span (`implied`).\n * - Asleep intervals for the 15-minute buckets cover every stretch of sleep\n * (naps too), each from one writer.\n */\nimport type { SleepSegment, SleepStage } from './model';\nimport type { ZoneClock } from './time';\n\n/** A break this long between segments ends a session. */\nexport const SESSION_GAP_MS = 2 * 3_600_000;\n/** An awake stretch at least this long counts as waking up. */\nexport const AWAKENING_MIN_MS = 2 * 60_000;\n\nexport type Interval = [number, number];\n\nexport interface Night {\n date: string;\n sleepMinutes?: number;\n inBedMinutes?: number;\n deepMinutes?: number;\n remMinutes?: number;\n lightMinutes?: number;\n awakeMinutes?: number;\n /** Awake stretches of 2+ minutes between falling asleep and the last sleep. */\n awakenings?: number;\n /** Minutes from getting into bed (recorded on its own) to the first asleep segment. */\n latencyMin?: number;\n /** When the person was asleep (union of the asleep stages), for heart rate while asleep. */\n asleep: Interval[];\n start: number;\n end: number;\n sourceKey: string;\n}\n\nconst ASLEEP: readonly SleepStage[] = ['asleep', 'light', 'deep', 'rem'];\nconst AWAKE: readonly SleepStage[] = ['awake', 'outOfBed'];\n\nexport function unionIntervals(intervals: readonly Interval[]): Interval[] {\n const sorted = intervals.filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0]);\n const out: Interval[] = [];\n for (const [a, b] of sorted) {\n const last = out[out.length - 1];\n if (last && a <= last[1]) last[1] = Math.max(last[1], b);\n else out.push([a, b]);\n }\n return out;\n}\n\nfunction measure(intervals: readonly Interval[]): number {\n return unionIntervals(intervals).reduce((n, [a, b]) => n + (b - a), 0);\n}\n\n/** `a` with every part that is also in `b` taken out. */\nfunction subtract(a: readonly Interval[], b: readonly Interval[]): Interval[] {\n const cut = unionIntervals(b);\n const out: Interval[] = [];\n for (const [a0, a1] of unionIntervals(a)) {\n let from = a0;\n for (const [b0, b1] of cut.filter(([c0, c1]) => c1 > a0 && c0 < a1)) {\n if (b0 > from) out.push([from, b0]);\n from = Math.max(from, b1);\n }\n if (from < a1) out.push([from, a1]);\n }\n return out;\n}\n\nfunction intersect(a: readonly Interval[], b: readonly Interval[]): Interval[] {\n const out: Interval[] = [];\n const ua = unionIntervals(a);\n const ub = unionIntervals(b);\n for (const [a0, a1] of ua) {\n for (const [b0, b1] of ub) {\n const lo = Math.max(a0, b0);\n const hi = Math.min(a1, b1);\n if (hi > lo) out.push([lo, hi]);\n }\n }\n return out;\n}\n\nconst toMin = (ms: number) => Math.round(ms / 6_000) / 10;\n\ninterface Session {\n sourceKey: string;\n segments: SleepSegment[];\n start: number;\n end: number;\n}\n\nfunction sessionsOf(segments: readonly SleepSegment[]): Session[] {\n const bySource = new Map<string, SleepSegment[]>();\n for (const s of segments.filter((x) => x.end > x.start)) {\n bySource.set(s.sourceKey, [...(bySource.get(s.sourceKey) ?? []), s]);\n }\n const sessions: Session[] = [];\n for (const [sourceKey, list] of bySource) {\n list.sort((a, b) => a.start - b.start);\n let cur: Session | null = null;\n for (const seg of list) {\n if (cur && seg.start <= cur.end + SESSION_GAP_MS) {\n cur.segments.push(seg);\n cur.end = Math.max(cur.end, seg.end);\n } else {\n cur = { sourceKey, segments: [seg], start: seg.start, end: seg.end };\n sessions.push(cur);\n }\n }\n }\n return sessions;\n}\n\ninterface Summary {\n session: Session;\n asleepMs: number;\n hasStages: boolean;\n night: Night;\n}\n\nfunction summarize(session: Session, clock: ZoneClock): Summary {\n const of = (stages: readonly SleepStage[]) =>\n session.segments.filter((s) => stages.includes(s.stage)).map((s): Interval => [s.start, s.end]);\n const asleep = of(ASLEEP);\n const asleepUnion = unionIntervals(asleep);\n const asleepMs = measure(asleep);\n const deep = measure(of(['deep']));\n const rem = measure(of(['rem']));\n const light = measure(of(['light']));\n const hasStages = deep + rem + light > 0;\n // Awake inside the night: awake time that is not also recorded as asleep.\n const awakeIntervals = of(['awake']);\n const awakeMs = measure(awakeIntervals) - measure(intersect(awakeIntervals, asleep));\n const inBedAll = of(['inBed', 'awake', ...ASLEEP]);\n const outOfBed = of(['outOfBed']);\n const inBedMs = measure(inBedAll) - measure(intersect(inBedAll, outOfBed));\n const body = session.segments.filter((s) => s.stage !== 'outOfBed');\n const start = Math.min(...(body.length ? body : session.segments).map((s) => s.start));\n const end = Math.max(...(body.length ? body : session.segments).map((s) => s.end));\n\n const night: Night = {\n date: clock.dateOf(end - 1),\n asleep: asleepUnion,\n start,\n end,\n sourceKey: session.sourceKey,\n };\n if (asleepMs > 0) night.sleepMinutes = toMin(asleepMs);\n const awakeOrUp = of(AWAKE);\n if (asleepUnion.length && (hasStages || awakeOrUp.length)) {\n const between: Interval = [asleepUnion[0][0], asleepUnion[asleepUnion.length - 1][1]];\n night.awakenings = subtract(intersect(awakeOrUp, [between]), asleepUnion).filter(\n ([a, b]) => b - a >= AWAKENING_MIN_MS,\n ).length;\n }\n if (hasStages) {\n night.deepMinutes = toMin(deep);\n night.remMinutes = toMin(rem);\n night.lightMinutes = toMin(light);\n }\n if (awakeMs > 0 || hasStages) night.awakeMinutes = toMin(Math.max(0, awakeMs));\n if (inBedMs > 0) night.inBedMinutes = toMin(Math.max(inBedMs, asleepMs + Math.max(0, awakeMs)));\n return { session, asleepMs, hasStages, night };\n}\n\nfunction better(a: Summary, b: Summary): Summary {\n if (a.asleepMs > 0 !== b.asleepMs > 0) return a.asleepMs > 0 ? a : b;\n if (a.hasStages !== b.hasStages) return a.hasStages ? a : b;\n if (a.asleepMs !== b.asleepMs) return a.asleepMs > b.asleepMs ? a : b;\n return measureSession(a) >= measureSession(b) ? a : b;\n}\n\nconst measureSession = (s: Summary) => s.night.inBedMinutes ?? 0;\n\nconst recordedInBed = (s: SleepSegment) => s.stage === 'inBed' && !s.implied;\n\n/**\n * Time from getting into bed to the first asleep segment. Into bed is the\n * earliest recorded in-bed start at or before falling asleep: the writer's own\n * in-bed record, or another writer's in-bed-only session (the iPhone's\n * bedtime) that was running when sleep began. Undefined when nothing recorded\n * in bed on its own, or sleep began before it.\n */\nfunction latencyMs(chosen: Summary, summaries: readonly Summary[]): number | undefined {\n const asleepAt = chosen.night.asleep[0]?.[0];\n if (asleepAt === undefined) return undefined;\n const starts = chosen.session.segments.filter((s) => recordedInBed(s) && s.start <= asleepAt).map((s) => s.start);\n // Another writer's in-bed-only session, running when sleep began.\n const bedtimes = summaries.filter(\n (o) =>\n o.session.sourceKey !== chosen.session.sourceKey &&\n o.asleepMs === 0 &&\n o.session.start <= asleepAt &&\n o.session.end > asleepAt,\n );\n for (const other of bedtimes) {\n const inBed = other.session.segments.filter((s) => recordedInBed(s) && s.start <= asleepAt);\n if (inBed.length) starts.push(Math.min(...inBed.map((s) => s.start)));\n }\n return starts.length ? asleepAt - Math.min(...starts) : undefined;\n}\n\n/**\n * Every stretch someone was in a sleep session (any writer, naps too), from\n * its first to its last segment: the time awake heart rate leaves out. A\n * session that never says \"asleep\" (a phone's in-bed record alone) is not one.\n */\nexport function sleepSpans(segments: readonly SleepSegment[]): Interval[] {\n return unionIntervals(\n sessionsOf(segments)\n .filter((s) => s.segments.some((x) => ASLEEP.includes(x.stage)))\n .map((s): Interval => [s.start, s.end]),\n );\n}\n\n/**\n * When the person was asleep, at any time of day (naps too), for the\n * 15-minute buckets. Sessions of different writers that overlap are one\n * stretch of sleep, taken from the one writer buildNights would pick, so\n * another app's plain \"asleep\" never covers the minutes a watch recorded as\n * awake.\n */\nexport function asleepIntervals(segments: readonly SleepSegment[], clock: ZoneClock): Interval[] {\n const summaries = sessionsOf(segments)\n .map((s) => summarize(s, clock))\n .sort((a, b) => a.session.start - b.session.start);\n const asleep: Interval[] = [];\n let pick: Summary | undefined;\n let stretchEnd = -Infinity;\n for (const s of summaries) {\n if (pick && s.session.start < stretchEnd) {\n pick = better(pick, s);\n } else {\n if (pick) asleep.push(...pick.night.asleep);\n pick = s;\n }\n stretchEnd = Math.max(stretchEnd, s.session.end);\n }\n if (pick) asleep.push(...pick.night.asleep);\n return unionIntervals(asleep);\n}\n\n/** One night per local date, keyed by the date the night ended. */\nexport function buildNights(segments: readonly SleepSegment[], clock: ZoneClock): Map<string, Night> {\n const summaries = sessionsOf(segments).map((s) => summarize(s, clock));\n const best = new Map<string, Summary>();\n for (const s of summaries) {\n const cur = best.get(s.night.date);\n best.set(s.night.date, cur ? better(cur, s) : s);\n }\n const nights = new Map<string, Night>();\n for (const [date, chosen] of best) {\n const night = { ...chosen.night };\n // A phone's own \"in bed\" record over the same night (another writer).\n // Only from sessions that record time in bed and nothing else (the\n // iPhone's bedtime schedule). Another tracker's own night is a rival\n // estimate, not a better in-bed figure.\n const otherInBed = summaries\n .filter((s) => s.session.sourceKey !== night.sourceKey && s.asleepMs === 0)\n .flatMap((s) => s.session.segments.filter((x) => x.stage === 'inBed'))\n .map((s): Interval => [s.start, s.end]);\n const touching = unionIntervals(otherInBed).filter(([a, b]) => b > night.start && a < night.end);\n if (touching.length) {\n const otherMin = toMin(measure(touching));\n if (night.inBedMinutes === undefined || otherMin > night.inBedMinutes) night.inBedMinutes = otherMin;\n }\n if (night.sleepMinutes !== undefined && night.inBedMinutes !== undefined) {\n night.inBedMinutes = Math.max(night.inBedMinutes, night.sleepMinutes);\n }\n const latency = latencyMs(chosen, summaries);\n if (latency !== undefined) night.latencyMin = toMin(latency);\n nights.set(date, night);\n }\n return nights;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AA6BO,MAAM,iBAAiB,CAAI,GAAA;AAE3B,MAAM,mBAAmB,CAAI,GAAA;AAoBpC,MAAM,MAAgC,GAAA,CAAC,QAAU,EAAA,OAAA,EAAS,QAAQ,KAAK,CAAA;AACvE,MAAM,KAAA,GAA+B,CAAC,OAAA,EAAS,UAAU,CAAA;AAClD,SAAS,eAAe,SAA4C,EAAA;AACzE,EAAM,MAAA,MAAA,GAAS,UAAU,MAAO,CAAA,CAAC,CAAC,CAAG,EAAA,CAAC,MAAM,CAAI,GAAA,CAAC,EAAE,IAAK,CAAA,CAAC,GAAG,CAAM,KAAA,CAAA,CAAE,CAAC,CAAI,GAAA,CAAA,CAAE,CAAC,CAAC,CAAA;AAC7E,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,MAAQ,EAAA;AAC3B,IAAA,MAAM,IAAO,GAAA,GAAA,CAAI,GAAI,CAAA,MAAA,GAAS,CAAC,CAAA;AAC/B,IAAA,IAAI,IAAQ,IAAA,CAAA,IAAK,IAAK,CAAA,CAAC,CAAG,EAAA,IAAA,CAAK,CAAC,CAAA,GAAI,IAAK,CAAA,GAAA,CAAI,IAAK,CAAA,CAAC,GAAG,CAAC,CAAA;AAAA,S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1,4 +1,4 @@
1
- import {buildHealthDays,chunkDays}from'./buildDays.js';import {FitnessApiError}from'./fitnessClient.js';import {syncWindow,rememberDates}from'./syncState.js';import {addDays}from'./time.js';import {ageOn,maxHrForAge}from'./zones.js';var __defProp = Object.defineProperty;
1
+ import {HR_RECOVERY_WINDOW_MS,buildHealthDays,chunkDays}from'./buildDays.js';import {FitnessApiError}from'./fitnessClient.js';import {syncWindow,rememberDates}from'./syncState.js';import {addDays}from'./time.js';import {ageOn,maxHrForAge}from'./zones.js';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -20,8 +20,29 @@ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
20
  const SLICE_DAYS = 7;
21
21
  const PAD_BEFORE_MS = 12 * 36e5;
22
22
  const MAX_DROPPED_LINES = 20;
23
+ function describeSyncError(err) {
24
+ if (err instanceof FitnessApiError) {
25
+ switch (err.kind) {
26
+ case "auth":
27
+ return "Yantra could not confirm your sign-in. Sign out and back in, then try again.";
28
+ case "network":
29
+ return "No connection to Yantra. Check your internet connection and try again.";
30
+ case "timeout":
31
+ return "Yantra took too long to answer. Try again in a moment.";
32
+ case "unavailable":
33
+ return "The Fitness service is not available right now. Your data will sync later.";
34
+ default:
35
+ return `Yantra did not accept the data: ${err.message}`;
36
+ }
37
+ }
38
+ if (err instanceof Error && err.name === "HealthAccessNeededError") {
39
+ return "Apple Health needs your permission again. Tap Sync now to allow it.";
40
+ }
41
+ const message = err instanceof Error ? err.message : String(err);
42
+ return `Could not read your health data: ${message}`;
43
+ }
23
44
  async function runHealthSync(initial, deps) {
24
- var _a;
45
+ var _a, _b;
25
46
  const now = (_a = deps.now) != null ? _a : Date.now;
26
47
  const startedAt = new Date(now()).toISOString();
27
48
  let state = __spreadProps(__spreadValues({}, initial), {
@@ -49,6 +70,7 @@ async function runHealthSync(initial, deps) {
49
70
  let stored = 0;
50
71
  const dropped = [];
51
72
  const unreadable = /* @__PURE__ */ new Set();
73
+ const needsAccess = /* @__PURE__ */ new Set();
52
74
  const save = async (next) => {
53
75
  var _a2;
54
76
  state = next;
@@ -66,22 +88,24 @@ async function runHealthSync(initial, deps) {
66
88
  for (let sliceFrom = from; sliceFrom <= to; sliceFrom = addDays(sliceFrom, SLICE_DAYS)) {
67
89
  const sliceTo = minDate(addDays(sliceFrom, SLICE_DAYS - 1), to);
68
90
  const start = deps.clock.startOfDay(sliceFrom) - PAD_BEFORE_MS;
69
- const end = Math.min(now(), deps.clock.startOfDay(addDays(sliceTo, 1)));
70
- const {
71
- raw,
72
- unreadable: missing
73
- } = await deps.reader.read({
91
+ const end = Math.min(now(), deps.clock.startOfDay(addDays(sliceTo, 1)) + HR_RECOVERY_WINDOW_MS);
92
+ const read = await deps.reader.read({
74
93
  start,
75
94
  end
76
95
  }, deps.clock);
77
- missing.forEach((t) => unreadable.add(t));
96
+ read.unreadable.forEach((t) => unreadable.add(t));
97
+ (_b = read.needsAccess) == null ? void 0 : _b.forEach((t) => needsAccess.add(t));
98
+ const {
99
+ raw
100
+ } = read;
78
101
  const built = buildHealthDays(raw, {
79
102
  from: sliceFrom,
80
103
  to: sliceTo,
81
104
  clock: deps.clock,
82
105
  source: deps.reader.source,
83
106
  maxHr,
84
- syncedAt: new Date(now()).toISOString()
107
+ syncedAt: new Date(now()).toISOString(),
108
+ dataEnd: end
85
109
  });
86
110
  dropped.push(...built.dropped);
87
111
  for (const chunk of chunkDays(built.days)) {
@@ -99,6 +123,7 @@ async function runHealthSync(initial, deps) {
99
123
  lastRunDays: stored,
100
124
  lastError: void 0,
101
125
  unreadableTypes: [...unreadable],
126
+ needsAccessTypes: [...needsAccess],
102
127
  lastDropped: dropped.slice(0, MAX_DROPPED_LINES)
103
128
  }));
104
129
  return {
@@ -119,25 +144,4 @@ async function runHealthSync(initial, deps) {
119
144
  };
120
145
  }
121
146
  }
122
- const minDate = (a, b) => a < b ? a : b;
123
- function describeSyncError(err) {
124
- if (err instanceof FitnessApiError) {
125
- switch (err.kind) {
126
- case "auth":
127
- return "Yantra could not confirm your sign-in. Sign out and back in, then try again.";
128
- case "network":
129
- return "No connection to Yantra. Check your internet connection and try again.";
130
- case "timeout":
131
- return "Yantra took too long to answer. Try again in a moment.";
132
- case "unavailable":
133
- return "The Fitness service is not available right now. Your data will sync later.";
134
- default:
135
- return `Yantra did not accept the data: ${err.message}`;
136
- }
137
- }
138
- if (err instanceof Error && err.name === "HealthAccessNeededError") {
139
- return "Apple Health needs your permission again. Tap Sync now to allow it.";
140
- }
141
- const message = err instanceof Error ? err.message : String(err);
142
- return `Could not read your health data: ${message}`;
143
- }export{SLICE_DAYS,describeSyncError,runHealthSync};//# sourceMappingURL=syncEngine.js.map
147
+ const minDate = (a, b) => a < b ? a : b;export{SLICE_DAYS,describeSyncError,runHealthSync};//# sourceMappingURL=syncEngine.js.map