@chipmobilesdk/rn-notification 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +257 -166
  2. package/README.md +420 -410
  3. package/package.json +61 -75
  4. package/skills/sdk-rn-notification/SKILL.md +172 -173
  5. package/src/channel/migrate.ts +285 -289
  6. package/src/channel/tone-map.ts +130 -130
  7. package/src/channel/validate-tone.ts +61 -61
  8. package/src/contract/channel.ts +192 -188
  9. package/src/contract/diagnostics.ts +102 -102
  10. package/src/contract/errors.ts +142 -134
  11. package/src/contract/index.ts +10 -10
  12. package/src/contract/interaction.ts +62 -62
  13. package/src/contract/notification.ts +118 -118
  14. package/src/contract/permission.ts +55 -60
  15. package/src/contract/reconcile.ts +88 -88
  16. package/src/contract/recurrence.ts +129 -129
  17. package/src/diagnostics/burst.ts +101 -101
  18. package/src/diagnostics/events.ts +81 -72
  19. package/src/diagnostics/redact.ts +55 -72
  20. package/src/diagnostics/snapshot.ts +100 -64
  21. package/src/engine/adapter.ts +172 -172
  22. package/src/engine/codec.ts +89 -89
  23. package/src/engine/notify-kit-engine.ts +715 -707
  24. package/src/index.ts +208 -208
  25. package/src/initialize.ts +247 -236
  26. package/src/interaction/index.ts +146 -146
  27. package/src/maintenance/cycle.ts +150 -154
  28. package/src/maintenance/permission-refresh.ts +39 -41
  29. package/src/maintenance/reanchor.ts +101 -101
  30. package/src/maintenance/toggle.ts +66 -64
  31. package/src/maintenance/verify.ts +83 -83
  32. package/src/maintenance/window-refresh.ts +64 -64
  33. package/src/permission/index.ts +183 -183
  34. package/src/permission/state.ts +77 -77
  35. package/src/push/envelope.ts +165 -165
  36. package/src/push/fcm-provider.ts +150 -146
  37. package/src/push/gate.ts +190 -190
  38. package/src/push/index.ts +33 -29
  39. package/src/push/instructions.ts +114 -109
  40. package/src/push/provider-adapter.ts +54 -54
  41. package/src/push/signout.ts +65 -65
  42. package/src/reconcile/chunk.ts +53 -53
  43. package/src/reconcile/diff.ts +142 -145
  44. package/src/reconcile/duplicates.ts +73 -73
  45. package/src/reconcile/index.ts +180 -180
  46. package/src/reconcile/truncate.ts +56 -56
  47. package/src/recurrence/clock-guard.ts +73 -71
  48. package/src/recurrence/expand.ts +326 -319
  49. package/src/recurrence/index.ts +270 -259
  50. package/src/repeat/expiry.ts +53 -55
  51. package/src/repeat/index.ts +54 -54
  52. package/src/repeat/marker.ts +72 -72
  53. package/src/repeat/place.ts +73 -73
  54. package/src/schedule/anchor.ts +294 -267
  55. package/src/schedule/index.ts +174 -181
  56. package/src/schedule/partition.ts +88 -85
  57. package/src/schedule/resolve-moment.ts +80 -80
  58. package/src/schedule/validate-content.ts +111 -111
  59. package/src/schedule/validate-identifier.ts +126 -126
  60. package/src/schedule/writer.ts +55 -55
  61. package/src/state/caps.ts +71 -71
  62. package/src/state/dedup-ledger.ts +35 -35
  63. package/src/state/interaction-buffer.ts +101 -73
  64. package/src/state/mmkv-store.ts +92 -75
  65. package/src/state/permission-history.ts +41 -41
  66. package/src/state/record.ts +270 -263
  67. package/src/state/reset.ts +41 -41
  68. package/src/state/series-ledger.ts +91 -91
  69. package/src/state/store.ts +43 -40
  70. package/src/testing/conformance/index.ts +258 -248
  71. package/src/testing/fake-engine.ts +462 -468
  72. package/src/testing/fake-provider.ts +126 -129
  73. package/src/testing/faults.ts +72 -72
  74. package/src/testing/index.ts +23 -28
  75. package/src/testing/measure.ts +337 -337
@@ -1,259 +1,270 @@
1
- /**
2
- * Series registration and the lookahead window.
3
- *
4
- * A caller declares a rule once. The package expands it inside a finite window
5
- * and refreshes that window on its own, because only it knows when the horizon
6
- * has moved — that is the one piece of recurrence knowledge the consumer does
7
- * not have.
8
- *
9
- * Occurrences carry derived identifiers, so re-expanding a series recognises
10
- * what it already scheduled instead of creating duplicates. That is what makes
11
- * a window refresh with nothing to do cost zero platform operations.
12
- *
13
- * Occurrences are written through the shared `ScheduleWriter`, like every other
14
- * consumer notification, so a repeating tone gets its stop marker and the
15
- * platform ceiling is respected here too.
16
- */
17
-
18
- import type {
19
- RecurrenceRule,
20
- SeriesResult,
21
- SeriesSummary,
22
- LookaheadConfig,
23
- } from '../contract/recurrence';
24
- import type { NotificationRequest, PendingEntry } from '../contract/notification';
25
- import type { ResolvedTone } from '../contract/channel';
26
- import type { NotificationEngineAdapter } from '../engine/adapter';
27
- import type { StateManager } from '../state/record';
28
- import { partsInZone, type TimeZoneReader } from '../schedule/anchor';
29
- import { validateIdentifier } from '../schedule/validate-identifier';
30
- import { validateRequest } from '../schedule';
31
- import { createScheduleWriter } from '../schedule/writer';
32
- import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
33
- import { expand, occurrenceKey, type Occurrence } from './expand';
34
- import { guardAgainstClockChange } from './clock-guard';
35
- import { listSeries as readLedger, readSeries, removeSeries, upsertSeries } from '../state/series-ledger';
36
-
37
- export interface RecurrenceDependencies {
38
- readonly engine: NotificationEngineAdapter;
39
- readonly state: StateManager;
40
- readonly resolveTone: (toneId: string) => ResolvedTone | undefined;
41
- readonly timeZone: TimeZoneReader;
42
- readonly now: () => number;
43
- readonly lookahead: LookaheadConfig;
44
- readonly canScheduleExactly: () => boolean;
45
- readonly emit?: (code: string, message: string, context?: Record<string, unknown>) => void;
46
- }
47
-
48
- /** Builds the request for one occurrence from the series template. */
49
- function toRequest(rule: RecurrenceRule, occurrence: Occurrence): NotificationRequest {
50
- return {
51
- id: occurrence.id,
52
- content: rule.template.content,
53
- tone: rule.template.tone,
54
- moment: { at: occurrence.at, anchoring: occurrence.anchoring },
55
- routing: rule.template.routing,
56
- actions: rule.template.actions,
57
- ownerTag: rule.template.ownerTag,
58
- groupTag: rule.template.groupTag,
59
- };
60
- }
61
-
62
- const belongsTo = (entry: PendingEntry, seriesId: string) =>
63
- entry.seriesId === seriesId || entry.id.startsWith(`${seriesId}#`);
64
-
65
- /**
66
- * The latest occurrence a ledger entry written before 0.4.0 had emitted. Those
67
- * entries kept no key, so it is read back off the device: the last occurrence
68
- * still pending is the last one emitted.
69
- */
70
- function recoverLastEmittedKey(
71
- pending: readonly PendingEntry[],
72
- anchoring: RecurrenceRule['anchoring'],
73
- zone: string,
74
- ): string | undefined {
75
- if (pending.length === 0) return undefined;
76
- const latest = Math.max(...pending.map(entry => entry.resolvedAt));
77
- return occurrenceKey(partsInZone(latest, anchoring === 'absolute' ? 'UTC' : zone));
78
- }
79
-
80
- export function createRecurrence(deps: RecurrenceDependencies) {
81
- const emit = deps.emit ?? (() => {});
82
- const writer = createScheduleWriter(deps.engine);
83
-
84
- /**
85
- * Validates the template as the request every occurrence will be, once, so
86
- * a series is refused at registration for exactly what a direct schedule
87
- * would be refused for — an undeclared tone, too many actions, an oversized
88
- * routing payload — rather than failing later inside maintenance.
89
- */
90
- const validateTemplate = (rule: RecurrenceRule): ResolvedTone =>
91
- validateRequest(
92
- {
93
- id: rule.id,
94
- content: rule.template.content,
95
- tone: rule.template.tone,
96
- moment: { at: deps.now(), anchoring: rule.anchoring ?? 'wallClock' },
97
- routing: rule.template.routing,
98
- actions: rule.template.actions,
99
- ownerTag: rule.template.ownerTag,
100
- groupTag: rule.template.groupTag,
101
- },
102
- deps.resolveTone,
103
- );
104
-
105
- const toneFor = (rule: RecurrenceRule): ResolvedTone => {
106
- const tone = deps.resolveTone(rule.template.tone);
107
- if (tone === undefined) {
108
- throw new NotificationError(
109
- DIAGNOSTIC_CODES.UNDECLARED_TONE,
110
- `Tone "${rule.template.tone}" was never declared in the package configuration.`,
111
- { toneId: rule.template.tone, seriesId: rule.id },
112
- );
113
- }
114
- return tone;
115
- };
116
-
117
- /** Expands and registers, scheduling only occurrences the device lacks. */
118
- const materialize = async (rule: RecurrenceRule, tone: ResolvedTone): Promise<SeriesResult> => {
119
- const now = deps.now();
120
- const zone = deps.timeZone();
121
- const previous = readSeries(deps.state, rule.id);
122
-
123
- const pending = await deps.engine.getPending();
124
- const ofSeries = pending.filter(entry => belongsTo(entry, rule.id));
125
-
126
- const expansion = expand({
127
- rule,
128
- from: now,
129
- lookahead: deps.lookahead,
130
- timeZone: zone,
131
- alreadyEmitted: previous?.emittedCount ?? 0,
132
- lastEmittedKey:
133
- previous?.lastEmittedKey ??
134
- (previous !== undefined ? recoverLastEmittedKey(ofSeries, rule.anchoring, zone) : undefined),
135
- });
136
-
137
- const guarded = guardAgainstClockChange({
138
- occurrences: expansion.occurrences,
139
- previousHorizon: previous?.expandedThrough,
140
- now,
141
- previousNow: previous?.at,
142
- });
143
-
144
- if (guarded.discontinuity !== 'none') {
145
- emit(
146
- 'CLOCK_DISCONTINUITY',
147
- `Device clock moved ${guarded.discontinuity}; ${guarded.suppressed} already-handled occurrence(s) were suppressed rather than re-delivered.`,
148
- { direction: guarded.discontinuity, suppressed: guarded.suppressed, seriesId: rule.id },
149
- );
150
- }
151
-
152
- const wanted = new Set(guarded.occurrences.map(occurrence => occurrence.id));
153
-
154
- // Upcoming entries of this series the expansion no longer produces: ones
155
- // written under the instant-based identity before 0.4.0, or ones whose slot
156
- // the rule no longer has. Left in place, each would fire beside its
157
- // replacement. Entries already due are left alone — they may be firing now.
158
- const stale = ofSeries.filter(entry => !wanted.has(entry.id) && entry.resolvedAt > now);
159
- for (const entry of stale) {
160
- await writer.cancel(entry.id);
161
- }
162
-
163
- const onDevice = new Set(ofSeries.filter(entry => !stale.includes(entry)).map(entry => entry.id));
164
- const missing = guarded.occurrences.filter(occurrence => !onDevice.has(occurrence.id));
165
-
166
- // The same ceiling reconciliation respects: soonest first, the rest
167
- // registered by a later refresh once they move into range.
168
- const room = Math.max(0, (await writer.capacity()) - (pending.length - stale.length));
169
- const toSchedule = missing.slice(0, room);
170
- if (toSchedule.length < missing.length) {
171
- emit(
172
- DIAGNOSTIC_CODES.TRUNCATED_OVER_CEILING,
173
- `Series "${rule.id}" has ${missing.length - toSchedule.length} occurrence(s) beyond the platform ceiling; they are registered by a later window refresh.`,
174
- { seriesId: rule.id, dropped: missing.length - toSchedule.length },
175
- );
176
- }
177
-
178
- const approximate = !deps.canScheduleExactly();
179
- for (const occurrence of toSchedule) {
180
- await writer.write({
181
- request: toRequest(rule, occurrence),
182
- resolvedAt: occurrence.at,
183
- tone,
184
- // The zone the series was expanded against; absent for absolute series.
185
- anchoringGeneration: occurrence.anchoring === 'absolute' ? undefined : zone,
186
- approximate,
187
- seriesId: rule.id,
188
- });
189
- }
190
-
191
- // Counted once, when first emitted — whether or not the ceiling let it on
192
- // the device yet. Occurrences re-produced from an earlier expansion are not
193
- // counted again.
194
- const newlyEmitted = guarded.occurrences.filter(occurrence => !occurrence.previouslyEmitted);
195
- const lastEmittedKey =
196
- newlyEmitted.length > 0 ? newlyEmitted[newlyEmitted.length - 1].key : previous?.lastEmittedKey;
197
-
198
- upsertSeries(
199
- deps.state,
200
- rule,
201
- {
202
- expandedThrough: expansion.expandedThrough,
203
- emittedCount: (previous?.emittedCount ?? 0) + newlyEmitted.length,
204
- exhausted: expansion.exhausted,
205
- lastEmittedKey,
206
- },
207
- now,
208
- );
209
-
210
- return {
211
- seriesId: rule.id,
212
- scheduled: toSchedule.length,
213
- expandedThrough: expansion.expandedThrough,
214
- exhausted: expansion.exhausted,
215
- cancelled: stale.map(entry => entry.id),
216
- };
217
- };
218
-
219
- return {
220
- async registerSeries(rule: RecurrenceRule): Promise<SeriesResult> {
221
- validateIdentifier(rule.id, 'seriesId');
222
- return materialize(rule, validateTemplate(rule));
223
- },
224
-
225
- /** Re-expands a tracked series. Called by the window-refresh maintenance step. */
226
- async refreshSeries(rule: RecurrenceRule): Promise<SeriesResult> {
227
- return materialize(rule, toneFor(rule));
228
- },
229
-
230
- async cancelSeries(seriesId: string): Promise<readonly string[]> {
231
- validateIdentifier(seriesId, 'seriesId');
232
-
233
- // Every occurrence already scheduled from this series goes, identified by
234
- // its derived prefix rather than by a list the ledger would have to keep
235
- // in sync with the device.
236
- const pending = await deps.engine.getPending();
237
- const ids = pending.filter(entry => belongsTo(entry, seriesId)).map(entry => entry.id);
238
-
239
- await deps.engine.cancelMany(ids);
240
- for (const id of ids) await writer.releaseStop(id);
241
- removeSeries(deps.state, seriesId);
242
- return ids;
243
- },
244
-
245
- async listSeries(): Promise<readonly SeriesSummary[]> {
246
- const pending = await deps.engine.getPending();
247
-
248
- return readLedger(deps.state).map(entry => ({
249
- seriesId: entry.seriesId,
250
- anchoring: entry.anchoring,
251
- expandedThrough: entry.expandedThrough,
252
- pendingOccurrences: pending.filter(p => belongsTo(p, entry.seriesId)).length,
253
- exhausted: entry.exhausted,
254
- }));
255
- },
256
- };
257
- }
258
-
259
- export type Recurrence = ReturnType<typeof createRecurrence>;
1
+ /**
2
+ * Series registration and the lookahead window.
3
+ *
4
+ * A caller declares a rule once. The package expands it inside a finite window
5
+ * and refreshes that window on its own, because only it knows when the horizon
6
+ * has moved — that is the one piece of recurrence knowledge the consumer does
7
+ * not have.
8
+ *
9
+ * Occurrences carry derived identifiers, so re-expanding a series recognises
10
+ * what it already scheduled instead of creating duplicates. That is what makes
11
+ * a window refresh with nothing to do cost zero platform operations.
12
+ *
13
+ * Occurrences are written through the shared `ScheduleWriter`, like every other
14
+ * consumer notification, so a repeating tone gets its stop marker and the
15
+ * platform ceiling is respected here too.
16
+ */
17
+
18
+ import type {
19
+ RecurrenceRule,
20
+ SeriesResult,
21
+ SeriesSummary,
22
+ LookaheadConfig,
23
+ } from '../contract/recurrence';
24
+ import type { NotificationRequest, PendingEntry } from '../contract/notification';
25
+ import type { ResolvedTone } from '../contract/channel';
26
+ import type { NotificationEngineAdapter } from '../engine/adapter';
27
+ import type { StateManager } from '../state/record';
28
+ import { partsInZone, type TimeZoneReader } from '../schedule/anchor';
29
+ import { validateIdentifier } from '../schedule/validate-identifier';
30
+ import { validateRequest } from '../schedule';
31
+ import { createScheduleWriter } from '../schedule/writer';
32
+ import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
33
+ import { expand, occurrenceKey, type Occurrence } from './expand';
34
+ import { guardAgainstClockChange } from './clock-guard';
35
+ import {
36
+ listSeries as readLedger,
37
+ readSeries,
38
+ removeSeries,
39
+ upsertSeries,
40
+ } from '../state/series-ledger';
41
+
42
+ export interface RecurrenceDependencies {
43
+ readonly engine: NotificationEngineAdapter;
44
+ readonly state: StateManager;
45
+ readonly resolveTone: (toneId: string) => ResolvedTone | undefined;
46
+ readonly timeZone: TimeZoneReader;
47
+ readonly now: () => number;
48
+ readonly lookahead: LookaheadConfig;
49
+ readonly canScheduleExactly: () => boolean;
50
+ readonly emit?: (code: string, message: string, context?: Record<string, unknown>) => void;
51
+ }
52
+
53
+ /** Builds the request for one occurrence from the series template. */
54
+ function toRequest(rule: RecurrenceRule, occurrence: Occurrence): NotificationRequest {
55
+ return {
56
+ id: occurrence.id,
57
+ content: rule.template.content,
58
+ tone: rule.template.tone,
59
+ moment: { at: occurrence.at, anchoring: occurrence.anchoring },
60
+ routing: rule.template.routing,
61
+ actions: rule.template.actions,
62
+ ownerTag: rule.template.ownerTag,
63
+ groupTag: rule.template.groupTag,
64
+ };
65
+ }
66
+
67
+ const belongsTo = (entry: PendingEntry, seriesId: string) =>
68
+ entry.seriesId === seriesId || entry.id.startsWith(`${seriesId}#`);
69
+
70
+ /**
71
+ * The latest occurrence a ledger entry written before 0.4.0 had emitted. Those
72
+ * entries kept no key, so it is read back off the device: the last occurrence
73
+ * still pending is the last one emitted.
74
+ */
75
+ function recoverLastEmittedKey(
76
+ pending: readonly PendingEntry[],
77
+ anchoring: RecurrenceRule['anchoring'],
78
+ zone: string,
79
+ ): string | undefined {
80
+ if (pending.length === 0) return undefined;
81
+ const latest = Math.max(...pending.map(entry => entry.resolvedAt));
82
+ return occurrenceKey(partsInZone(latest, anchoring === 'absolute' ? 'UTC' : zone));
83
+ }
84
+
85
+ export function createRecurrence(deps: RecurrenceDependencies) {
86
+ const emit = deps.emit ?? (() => {});
87
+ const writer = createScheduleWriter(deps.engine);
88
+
89
+ /**
90
+ * Validates the template as the request every occurrence will be, once, so
91
+ * a series is refused at registration for exactly what a direct schedule
92
+ * would be refused for — an undeclared tone, too many actions, an oversized
93
+ * routing payload — rather than failing later inside maintenance.
94
+ */
95
+ const validateTemplate = (rule: RecurrenceRule): ResolvedTone =>
96
+ validateRequest(
97
+ {
98
+ id: rule.id,
99
+ content: rule.template.content,
100
+ tone: rule.template.tone,
101
+ moment: { at: deps.now(), anchoring: rule.anchoring ?? 'wallClock' },
102
+ routing: rule.template.routing,
103
+ actions: rule.template.actions,
104
+ ownerTag: rule.template.ownerTag,
105
+ groupTag: rule.template.groupTag,
106
+ },
107
+ deps.resolveTone,
108
+ );
109
+
110
+ const toneFor = (rule: RecurrenceRule): ResolvedTone => {
111
+ const tone = deps.resolveTone(rule.template.tone);
112
+ if (tone === undefined) {
113
+ throw new NotificationError(
114
+ DIAGNOSTIC_CODES.UNDECLARED_TONE,
115
+ `Tone "${rule.template.tone}" was never declared in the package configuration.`,
116
+ { toneId: rule.template.tone, seriesId: rule.id },
117
+ );
118
+ }
119
+ return tone;
120
+ };
121
+
122
+ /** Expands and registers, scheduling only occurrences the device lacks. */
123
+ const materialize = async (rule: RecurrenceRule, tone: ResolvedTone): Promise<SeriesResult> => {
124
+ const now = deps.now();
125
+ const zone = deps.timeZone();
126
+ const previous = readSeries(deps.state, rule.id);
127
+
128
+ const pending = await deps.engine.getPending();
129
+ const ofSeries = pending.filter(entry => belongsTo(entry, rule.id));
130
+
131
+ const expansion = expand({
132
+ rule,
133
+ from: now,
134
+ lookahead: deps.lookahead,
135
+ timeZone: zone,
136
+ alreadyEmitted: previous?.emittedCount ?? 0,
137
+ lastEmittedKey:
138
+ previous?.lastEmittedKey ??
139
+ (previous !== undefined
140
+ ? recoverLastEmittedKey(ofSeries, rule.anchoring, zone)
141
+ : undefined),
142
+ });
143
+
144
+ const guarded = guardAgainstClockChange({
145
+ occurrences: expansion.occurrences,
146
+ previousHorizon: previous?.expandedThrough,
147
+ now,
148
+ previousNow: previous?.at,
149
+ });
150
+
151
+ if (guarded.discontinuity !== 'none') {
152
+ emit(
153
+ 'CLOCK_DISCONTINUITY',
154
+ `Device clock moved ${guarded.discontinuity}; ${guarded.suppressed} already-handled occurrence(s) were suppressed rather than re-delivered.`,
155
+ { direction: guarded.discontinuity, suppressed: guarded.suppressed, seriesId: rule.id },
156
+ );
157
+ }
158
+
159
+ const wanted = new Set(guarded.occurrences.map(occurrence => occurrence.id));
160
+
161
+ // Upcoming entries of this series the expansion no longer produces: ones
162
+ // written under the instant-based identity before 0.4.0, or ones whose slot
163
+ // the rule no longer has. Left in place, each would fire beside its
164
+ // replacement. Entries already due are left alone — they may be firing now.
165
+ const stale = ofSeries.filter(entry => !wanted.has(entry.id) && entry.resolvedAt > now);
166
+ for (const entry of stale) {
167
+ await writer.cancel(entry.id);
168
+ }
169
+
170
+ const onDevice = new Set(
171
+ ofSeries.filter(entry => !stale.includes(entry)).map(entry => entry.id),
172
+ );
173
+ const missing = guarded.occurrences.filter(occurrence => !onDevice.has(occurrence.id));
174
+
175
+ // The same ceiling reconciliation respects: soonest first, the rest
176
+ // registered by a later refresh once they move into range.
177
+ const room = Math.max(0, (await writer.capacity()) - (pending.length - stale.length));
178
+ const toSchedule = missing.slice(0, room);
179
+ if (toSchedule.length < missing.length) {
180
+ emit(
181
+ DIAGNOSTIC_CODES.TRUNCATED_OVER_CEILING,
182
+ `Series "${rule.id}" has ${missing.length - toSchedule.length} occurrence(s) beyond the platform ceiling; they are registered by a later window refresh.`,
183
+ { seriesId: rule.id, dropped: missing.length - toSchedule.length },
184
+ );
185
+ }
186
+
187
+ const approximate = !deps.canScheduleExactly();
188
+ for (const occurrence of toSchedule) {
189
+ await writer.write({
190
+ request: toRequest(rule, occurrence),
191
+ resolvedAt: occurrence.at,
192
+ tone,
193
+ // The zone the series was expanded against; absent for absolute series.
194
+ anchoringGeneration: occurrence.anchoring === 'absolute' ? undefined : zone,
195
+ approximate,
196
+ seriesId: rule.id,
197
+ });
198
+ }
199
+
200
+ // Counted once, when first emitted — whether or not the ceiling let it on
201
+ // the device yet. Occurrences re-produced from an earlier expansion are not
202
+ // counted again.
203
+ const newlyEmitted = guarded.occurrences.filter(occurrence => !occurrence.previouslyEmitted);
204
+ const lastEmittedKey =
205
+ newlyEmitted.length > 0
206
+ ? newlyEmitted[newlyEmitted.length - 1].key
207
+ : previous?.lastEmittedKey;
208
+
209
+ upsertSeries(
210
+ deps.state,
211
+ rule,
212
+ {
213
+ expandedThrough: expansion.expandedThrough,
214
+ emittedCount: (previous?.emittedCount ?? 0) + newlyEmitted.length,
215
+ exhausted: expansion.exhausted,
216
+ lastEmittedKey,
217
+ },
218
+ now,
219
+ );
220
+
221
+ return {
222
+ seriesId: rule.id,
223
+ scheduled: toSchedule.length,
224
+ expandedThrough: expansion.expandedThrough,
225
+ exhausted: expansion.exhausted,
226
+ cancelled: stale.map(entry => entry.id),
227
+ };
228
+ };
229
+
230
+ return {
231
+ async registerSeries(rule: RecurrenceRule): Promise<SeriesResult> {
232
+ validateIdentifier(rule.id, 'seriesId');
233
+ return materialize(rule, validateTemplate(rule));
234
+ },
235
+
236
+ /** Re-expands a tracked series. Called by the window-refresh maintenance step. */
237
+ async refreshSeries(rule: RecurrenceRule): Promise<SeriesResult> {
238
+ return materialize(rule, toneFor(rule));
239
+ },
240
+
241
+ async cancelSeries(seriesId: string): Promise<readonly string[]> {
242
+ validateIdentifier(seriesId, 'seriesId');
243
+
244
+ // Every occurrence already scheduled from this series goes, identified by
245
+ // its derived prefix rather than by a list the ledger would have to keep
246
+ // in sync with the device.
247
+ const pending = await deps.engine.getPending();
248
+ const ids = pending.filter(entry => belongsTo(entry, seriesId)).map(entry => entry.id);
249
+
250
+ await deps.engine.cancelMany(ids);
251
+ for (const id of ids) await writer.releaseStop(id);
252
+ removeSeries(deps.state, seriesId);
253
+ return ids;
254
+ },
255
+
256
+ async listSeries(): Promise<readonly SeriesSummary[]> {
257
+ const pending = await deps.engine.getPending();
258
+
259
+ return readLedger(deps.state).map(entry => ({
260
+ seriesId: entry.seriesId,
261
+ anchoring: entry.anchoring,
262
+ expandedThrough: entry.expandedThrough,
263
+ pendingOccurrences: pending.filter(p => belongsTo(p, entry.seriesId)).length,
264
+ exhausted: entry.exhausted,
265
+ }));
266
+ },
267
+ };
268
+ }
269
+
270
+ export type Recurrence = ReturnType<typeof createRecurrence>;