@jsb188/mday 1.1.10 → 1.1.11

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 (119) hide show
  1. package/package.json +105 -54
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +35 -9
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +20 -4
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/integration.ts +8 -9
  13. package/src/constants/log.ts +7 -410
  14. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  15. package/src/constants/logTaxonomy.generated.ts +1103 -0
  16. package/src/constants/noteDoc.ts +77 -0
  17. package/src/constants/organization.ts +13 -15
  18. package/src/constants/pageRoute.ts +23 -0
  19. package/src/constants/schedule.ts +220 -0
  20. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  21. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  22. package/src/constants/sheet.ts +154 -6
  23. package/src/constants/sheetRegionSources.generated.ts +578 -0
  24. package/src/constants/square.ts +6 -6
  25. package/src/constants/storage.ts +56 -7
  26. package/src/constants/usage.ts +79 -0
  27. package/src/schemas/editLogEntry.ts +1010 -777
  28. package/src/schemas/fieldDocsQuery.ts +12 -0
  29. package/src/schemas/inboundContact.ts +60 -55
  30. package/src/schemas/logsQuery.ts +55 -49
  31. package/src/schemas/organization.ts +49 -46
  32. package/src/types/account.d.ts +4 -1
  33. package/src/types/agentDoc.d.ts +64 -0
  34. package/src/types/agentMemory.d.ts +74 -0
  35. package/src/types/campaign.d.ts +683 -0
  36. package/src/types/dataTable.d.ts +175 -256
  37. package/src/types/docAccess.d.ts +96 -0
  38. package/src/types/email.d.ts +83 -12
  39. package/src/types/fieldDoc.d.ts +273 -0
  40. package/src/types/inboundContact.d.ts +2 -1
  41. package/src/types/log.d.ts +209 -341
  42. package/src/types/noteDoc.d.ts +86 -0
  43. package/src/types/organization.d.ts +83 -40
  44. package/src/types/pageRoute.d.ts +48 -0
  45. package/src/types/schedule.d.ts +391 -0
  46. package/src/types/sheet.d.ts +862 -30
  47. package/src/types/storage.d.ts +206 -125
  48. package/src/types/usage.d.ts +106 -0
  49. package/src/types/workflow.d.ts +149 -18
  50. package/src/utils/agentDoc.ts +109 -0
  51. package/src/utils/aiChat.ts +26 -0
  52. package/src/utils/campaign.ts +741 -0
  53. package/src/utils/campaignFormEditor.ts +871 -0
  54. package/src/utils/dataTable.ts +425 -410
  55. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  56. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  57. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  58. package/src/utils/dataTableRowDocument.ts +508 -0
  59. package/src/utils/dataTableSource.ts +230 -0
  60. package/src/utils/docAccess.ts +383 -0
  61. package/src/utils/documentName.ts +53 -0
  62. package/src/utils/email.ts +112 -53
  63. package/src/utils/fieldDoc.ts +113 -0
  64. package/src/utils/log.ts +169 -176
  65. package/src/utils/logRegistryValue.ts +90 -0
  66. package/src/utils/logStoreRead.ts +266 -0
  67. package/src/utils/logTaxonomy.ts +76 -0
  68. package/src/utils/logTaxonomyDisplay.ts +439 -0
  69. package/src/utils/noteDoc.ts +827 -0
  70. package/src/utils/organization.ts +510 -91
  71. package/src/utils/pageRoute.ts +71 -0
  72. package/src/utils/schedule.ts +799 -0
  73. package/src/utils/scheduleEvaluation.ts +1994 -0
  74. package/src/utils/scheduleICS.ts +246 -0
  75. package/src/utils/scheduleRuleTemplates.ts +188 -0
  76. package/src/utils/sheet.ts +4842 -39
  77. package/src/utils/sheetAxisMove.ts +830 -0
  78. package/src/utils/sheetBootstrap.ts +1769 -0
  79. package/src/utils/sheetCommand.ts +423 -0
  80. package/src/utils/sheetExport.ts +238 -0
  81. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  82. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  83. package/src/utils/sheetJournal.ts +78 -0
  84. package/src/utils/sheetNumberFormat.ts +1211 -0
  85. package/src/utils/sheetRegion.ts +374 -0
  86. package/src/utils/sheetRegionFilter.ts +1259 -0
  87. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  88. package/src/utils/sheetSequence.ts +148 -0
  89. package/src/utils/sheetSnapshot.ts +992 -0
  90. package/src/utils/sheetStructureEdit.ts +1284 -0
  91. package/src/utils/square.ts +22 -12
  92. package/src/utils/storage.ts +152 -0
  93. package/src/utils/table-route.ts +127 -11
  94. package/src/utils/workflow.ts +191 -23
  95. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  96. package/tests/docAccess.test.ts +525 -0
  97. package/tests/editLogEntry.test.ts +112 -0
  98. package/tests/noteDoc.test.ts +669 -0
  99. package/tests/schedule.test.ts +693 -0
  100. package/tests/scheduleEvaluation.test.ts +1970 -0
  101. package/tests/scheduleICS.test.ts +208 -0
  102. package/tests/scheduleRuleTemplates.test.ts +176 -0
  103. package/tests/scheduleSweepInvariants.test.ts +428 -0
  104. package/tests/sheetAxisMove.test.ts +343 -0
  105. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  106. package/tests/sheetRegionFilter.test.ts +1135 -0
  107. package/tests/sheetSequence.test.ts +41 -0
  108. package/tests/sheetStructureEdit.test.ts +82 -0
  109. package/tsconfig.json +10 -10
  110. package/vitest.config.ts +8 -0
  111. package/src/constants/log-activityTexts.ts +0 -235
  112. package/src/constants/product.ts +0 -42
  113. package/src/constants/report.ts +0 -44
  114. package/src/schemas/productsQuery.ts +0 -53
  115. package/src/schemas/reportsQuery.ts +0 -20
  116. package/src/types/product.d.ts +0 -84
  117. package/src/types/report.d.ts +0 -290
  118. package/src/utils/product-calEvent.ts +0 -455
  119. package/src/utils/report.ts +0 -158
@@ -0,0 +1,799 @@
1
+ import {
2
+ DEFAULT_TIMEZONE,
3
+ isValidTimeZone,
4
+ } from '@jsb188/app/utils/timeZone.ts';
5
+ import { DateTime } from 'luxon';
6
+ import {
7
+ SCHEDULE_MATERIALIZATION_HORIZON_DAYS,
8
+ SCHEDULE_OCCURRENCE_MAX_DURATION_MINUTES,
9
+ SCHEDULE_RECURRENCE_FREQ_ENUMS,
10
+ SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH,
11
+ SCHEDULE_RECURRENCE_MAX_INTERVAL,
12
+ SCHEDULE_RECURRENCE_MAX_ITERATIONS,
13
+ SCHEDULE_SLOT_KEY_MAX_LENGTH,
14
+ SCHEDULE_SLOT_LABEL_MAX_LENGTH,
15
+ } from '../constants/schedule.ts';
16
+ import type {
17
+ ScheduleExpandedInstance,
18
+ ScheduleRecurrenceObj,
19
+ ScheduleSlotTemplateObj,
20
+ } from '../types/schedule.d.ts';
21
+
22
+ /**
23
+ * Recurrence expansion and schedule value helpers, shared by the server
24
+ * materialization job and any client-side preview of a recurring series.
25
+ *
26
+ * Expansion walks LOCAL calendar dates in the series timezone and stamps the
27
+ * anchor's wall-clock time onto each one, so a 7:00am shift stays 7:00am
28
+ * across a daylight-saving transition instead of drifting to 6:00 or 8:00.
29
+ */
30
+
31
+ // Longest each month can ever be; February counts a leap day so a "February
32
+ // 29th" yearly rule stays valid
33
+ const MAX_DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
34
+
35
+ /**
36
+ * The local wall-clock time a series repeats at.
37
+ */
38
+
39
+ interface ScheduleAnchorTime {
40
+ hour: number;
41
+ minute: number;
42
+ second: number;
43
+ millisecond: number;
44
+ }
45
+
46
+ interface ScheduleExpandOptions {
47
+ // Only instances starting at or after this instant are returned
48
+ from?: Date | null;
49
+ // Only instances starting strictly before this instant are returned
50
+ to?: Date | null;
51
+ // Largest number of instances to return
52
+ limit?: number | null;
53
+ }
54
+
55
+ /**
56
+ * The series facts expansion needs. Accepting this shape rather than a full
57
+ * row lets a client preview an unsaved series.
58
+ */
59
+
60
+ export interface ScheduleExpandableSeries {
61
+ recurrence: ScheduleRecurrenceObj;
62
+ timeZone: string;
63
+ startsAt: Date | string;
64
+ endsAt?: Date | string | null;
65
+ durationMinutes: number;
66
+ allDay?: boolean | null;
67
+ }
68
+
69
+ /*
70
+ * Coerce one value into a Date, returning null when it cannot be read as one.
71
+ */
72
+
73
+ function toDateOrNull(value?: Date | string | number | null): Date | null {
74
+ if (value === null || value === undefined) {
75
+ return null;
76
+ }
77
+
78
+ const date = value instanceof Date ? value : new Date(value);
79
+
80
+ return Number.isNaN(date.getTime()) ? null : date;
81
+ }
82
+
83
+ /*
84
+ * Return a de-duplicated, ascending list of the integers in one input array,
85
+ * keeping only values that pass the caller's range test.
86
+ */
87
+
88
+ function getNormalizedIntegerList(
89
+ values: unknown,
90
+ isInRange: (value: number) => boolean,
91
+ ): number[] | null {
92
+ if (!Array.isArray(values) || !values.length) {
93
+ return null;
94
+ }
95
+
96
+ const normalized = new Set<number>();
97
+
98
+ for (const value of values) {
99
+ const int = Number(value);
100
+ if (!Number.isInteger(int) || !isInRange(int)) {
101
+ return null;
102
+ }
103
+
104
+ normalized.add(int);
105
+ }
106
+
107
+ return Array.from(normalized).sort((a, b) => a - b);
108
+ }
109
+
110
+ /*
111
+ * Order month days so expansion emits them chronologically; the "last day of
112
+ * the month" sentinel always sorts last.
113
+ */
114
+
115
+ function getSortedMonthDays(monthDays: number[]): number[] {
116
+ return [...monthDays].sort(
117
+ (a, b) =>
118
+ (a === SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH ? 32 : a) -
119
+ (b === SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH ? 32 : b),
120
+ );
121
+ }
122
+
123
+ /*
124
+ * Order a plain list of calendar units ascending.
125
+ *
126
+ * Every generator below must emit chronologically, because the expander stops
127
+ * at the first instance past its bound with a `break`. Fed an unordered list, a
128
+ * generator emits a later unit before an earlier one, the break fires on the
129
+ * later one, and the earlier one is silently never produced — a shift that
130
+ * simply is not on the schedule, with nothing to indicate it was dropped.
131
+ *
132
+ * validateScheduleRecurrence already sorts what it stores, so a rule read back
133
+ * from the database is safe. This is for the other documented entry point: a
134
+ * client previewing an UNSAVED series passes its rule straight here, and that
135
+ * rule has not been through the validator.
136
+ */
137
+
138
+ function getSortedRecurrenceUnits(units: number[]): number[] {
139
+ return [...units].sort((a, b) => a - b);
140
+ }
141
+
142
+ /**
143
+ * Validate and normalize one recurrence input into the shape stored in
144
+ * schedule_series."recurrence". Returns the normalized rule or a human
145
+ * readable error; never throws.
146
+ */
147
+
148
+ export function validateScheduleRecurrence(input: unknown): {
149
+ recurrence?: ScheduleRecurrenceObj;
150
+ error?: string;
151
+ } {
152
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
153
+ return { error: 'Recurrence must be an object.' };
154
+ }
155
+
156
+ const raw = input as Record<string, unknown>;
157
+ const freq = String(raw.freq || '');
158
+
159
+ if (
160
+ !SCHEDULE_RECURRENCE_FREQ_ENUMS.includes(
161
+ freq as ScheduleRecurrenceObj['freq'],
162
+ )
163
+ ) {
164
+ return {
165
+ error: `Recurrence frequency must be one of: ${SCHEDULE_RECURRENCE_FREQ_ENUMS.join(', ')}.`,
166
+ };
167
+ }
168
+
169
+ const interval =
170
+ raw.interval === undefined || raw.interval === null
171
+ ? 1
172
+ : Number(raw.interval);
173
+ if (
174
+ !Number.isInteger(interval) ||
175
+ interval < 1 ||
176
+ interval > SCHEDULE_RECURRENCE_MAX_INTERVAL
177
+ ) {
178
+ return {
179
+ error: `Recurrence interval must be a whole number between 1 and ${SCHEDULE_RECURRENCE_MAX_INTERVAL}.`,
180
+ };
181
+ }
182
+
183
+ const recurrence: ScheduleRecurrenceObj = {
184
+ freq: freq as ScheduleRecurrenceObj['freq'],
185
+ interval,
186
+ };
187
+
188
+ if (raw.byWeekday !== undefined && raw.byWeekday !== null) {
189
+ const byWeekday = getNormalizedIntegerList(
190
+ raw.byWeekday,
191
+ (value) => value >= 0 && value <= 6,
192
+ );
193
+ if (!byWeekday) {
194
+ return {
195
+ error:
196
+ 'Recurrence weekdays must be whole numbers from 0 (Sunday) to 6 (Saturday).',
197
+ };
198
+ }
199
+
200
+ recurrence.byWeekday = byWeekday;
201
+ }
202
+
203
+ if (raw.byMonthDay !== undefined && raw.byMonthDay !== null) {
204
+ const byMonthDay = getNormalizedIntegerList(
205
+ raw.byMonthDay,
206
+ (value) =>
207
+ (value >= 1 && value <= 31) ||
208
+ value === SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH,
209
+ );
210
+ if (!byMonthDay) {
211
+ return {
212
+ error:
213
+ 'Recurrence month days must be whole numbers from 1 to 31, or -1 for the last day of the month.',
214
+ };
215
+ }
216
+
217
+ recurrence.byMonthDay = byMonthDay;
218
+ }
219
+
220
+ if (raw.byMonth !== undefined && raw.byMonth !== null) {
221
+ const byMonth = getNormalizedIntegerList(
222
+ raw.byMonth,
223
+ (value) => value >= 1 && value <= 12,
224
+ );
225
+ if (!byMonth) {
226
+ return {
227
+ error:
228
+ 'Recurrence months must be whole numbers from 1 (January) to 12 (December).',
229
+ };
230
+ }
231
+
232
+ recurrence.byMonth = byMonth;
233
+ }
234
+
235
+ if (raw.count !== undefined && raw.count !== null) {
236
+ const count = Number(raw.count);
237
+ if (!Number.isInteger(count) || count < 1) {
238
+ return { error: 'Recurrence count must be a whole number of 1 or more.' };
239
+ }
240
+
241
+ recurrence.count = count;
242
+ }
243
+
244
+ if (raw.until !== undefined && raw.until !== null) {
245
+ const until = toDateOrNull(raw.until as string);
246
+ if (!until) {
247
+ return { error: 'Recurrence end date is not a valid date.' };
248
+ }
249
+
250
+ recurrence.until = until.toISOString();
251
+ }
252
+
253
+ // Weekday and month-day narrowing only mean something for the frequency
254
+ // that iterates over that unit; silently keeping them would make two
255
+ // different-looking rules behave identically
256
+ if (recurrence.byWeekday && recurrence.freq !== 'WEEKLY') {
257
+ return {
258
+ error: 'Recurrence weekdays can only be used with a weekly frequency.',
259
+ };
260
+ }
261
+
262
+ if (
263
+ recurrence.byMonthDay &&
264
+ recurrence.freq !== 'MONTHLY' &&
265
+ recurrence.freq !== 'YEARLY'
266
+ ) {
267
+ return {
268
+ error:
269
+ 'Recurrence month days can only be used with a monthly or yearly frequency.',
270
+ };
271
+ }
272
+
273
+ if (recurrence.byMonth && recurrence.freq !== 'YEARLY') {
274
+ return {
275
+ error: 'Recurrence months can only be used with a yearly frequency.',
276
+ };
277
+ }
278
+
279
+ // A yearly rule can name a day its months never reach — "February 30th".
280
+ // The expander is bounded so such a rule cannot hang, but it would produce
281
+ // a series that silently never fires, which is worse than refusing it.
282
+ if (
283
+ recurrence.freq === 'YEARLY' &&
284
+ recurrence.byMonth?.length &&
285
+ recurrence.byMonthDay?.length
286
+ ) {
287
+ const longestListedMonth = Math.max(
288
+ ...recurrence.byMonth.map((month) => MAX_DAYS_IN_MONTH[month - 1] || 0),
289
+ );
290
+ const reachesAnyDay = recurrence.byMonthDay.some(
291
+ (monthDay) =>
292
+ monthDay === SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH ||
293
+ monthDay <= longestListedMonth,
294
+ );
295
+
296
+ if (!reachesAnyDay) {
297
+ return {
298
+ error:
299
+ 'Recurrence never occurs: none of the selected months contain any of the selected days.',
300
+ };
301
+ }
302
+ }
303
+
304
+ return { recurrence };
305
+ }
306
+
307
+ /**
308
+ * Validate one slot template list (schedule_series."slotTemplate", and the
309
+ * slot rows stamped onto each generated occurrence).
310
+ */
311
+
312
+ export function validateScheduleSlotTemplate(input: unknown): {
313
+ slotTemplate?: ScheduleSlotTemplateObj[];
314
+ error?: string;
315
+ } {
316
+ if (input === undefined || input === null) {
317
+ return { slotTemplate: [] };
318
+ }
319
+
320
+ if (!Array.isArray(input)) {
321
+ return { error: 'Slot requirements must be a list.' };
322
+ }
323
+
324
+ const slotTemplate: ScheduleSlotTemplateObj[] = [];
325
+ const usedKeys = new Set<string>();
326
+
327
+ for (let i = 0; i < input.length; i++) {
328
+ const raw = input[i];
329
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
330
+ return { error: 'Each slot requirement must be an object.' };
331
+ }
332
+
333
+ const key = String(raw.key || '').trim();
334
+ if (!key) {
335
+ return { error: 'Each slot requirement needs a key.' };
336
+ }
337
+
338
+ // Rejected rather than truncated: two long keys sharing a prefix would
339
+ // silently collapse into one. The bounds match the schedule_slots
340
+ // column widths, so an over-length value can never reach a write —
341
+ // which for a series would mean the value sits happily in the
342
+ // slotTemplate JSONB and only fails later, during materialization.
343
+ if (key.length > SCHEDULE_SLOT_KEY_MAX_LENGTH) {
344
+ return {
345
+ error: `Slot requirement key is too long (max ${SCHEDULE_SLOT_KEY_MAX_LENGTH} characters): "${key}".`,
346
+ };
347
+ }
348
+
349
+ if (
350
+ raw.label &&
351
+ String(raw.label).length > SCHEDULE_SLOT_LABEL_MAX_LENGTH
352
+ ) {
353
+ return {
354
+ error: `Slot requirement label is too long (max ${SCHEDULE_SLOT_LABEL_MAX_LENGTH} characters).`,
355
+ };
356
+ }
357
+
358
+ if (usedKeys.has(key)) {
359
+ return {
360
+ error: `Slot requirement keys must be unique; "${key}" is repeated.`,
361
+ };
362
+ }
363
+
364
+ const requiredCount =
365
+ raw.requiredCount === undefined || raw.requiredCount === null
366
+ ? 1
367
+ : Number(raw.requiredCount);
368
+ if (!Number.isInteger(requiredCount) || requiredCount < 0) {
369
+ return {
370
+ error: `Slot requirement "${key}" needs a whole required count of 0 or more.`,
371
+ };
372
+ }
373
+
374
+ usedKeys.add(key);
375
+
376
+ slotTemplate.push({
377
+ key,
378
+ label: raw.label ? String(raw.label) : null,
379
+ requiredCount,
380
+ predicate:
381
+ raw.predicate &&
382
+ typeof raw.predicate === 'object' &&
383
+ !Array.isArray(raw.predicate)
384
+ ? raw.predicate
385
+ : null,
386
+ ordinal: i,
387
+ });
388
+ }
389
+
390
+ return { slotTemplate };
391
+ }
392
+
393
+ /*
394
+ * Return the series timezone, falling back to the platform default when the
395
+ * stored value is missing or is not a zone this runtime knows.
396
+ */
397
+
398
+ function getSeriesTimeZone(timeZone?: string | null): string {
399
+ return timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
400
+ }
401
+
402
+ /*
403
+ * Read the local wall-clock time one series repeats at.
404
+ */
405
+
406
+ function getAnchorTime(anchor: DateTime): ScheduleAnchorTime {
407
+ return {
408
+ hour: anchor.hour,
409
+ minute: anchor.minute,
410
+ second: anchor.second,
411
+ millisecond: anchor.millisecond,
412
+ };
413
+ }
414
+
415
+ /*
416
+ * Stamp the series wall-clock time onto one local calendar date.
417
+ *
418
+ * A local time inside a spring-forward gap (02:30 on a day where 02:00-03:00
419
+ * does not exist) is moved forward past the gap by luxon rather than dropped:
420
+ * a daily 02:30 series still produces exactly one instance that day, which is
421
+ * what every calendar client does. The null return is the guard for a date
422
+ * luxon cannot represent at all, not for the DST gap.
423
+ */
424
+
425
+ function getInstanceStart(
426
+ localDate: DateTime,
427
+ anchorTime: ScheduleAnchorTime,
428
+ ): DateTime | null {
429
+ const start = localDate.set(anchorTime);
430
+
431
+ return start.isValid ? start : null;
432
+ }
433
+
434
+ /*
435
+ * Generate candidate local dates for a DAILY rule.
436
+ *
437
+ * Every generator below bounds its OWN step count rather than relying on the
438
+ * consumer to stop pulling. A consumer-side cap can only count values it
439
+ * actually received, so a rule that yields nothing — "the 30th of February",
440
+ * or the 31st visited only in February by a 12-month interval — would spin
441
+ * inside the generator forever and never hand control back. That is a
442
+ * synchronous loop, so it takes the whole event loop with it.
443
+ */
444
+
445
+ function* iterateDailyDates(
446
+ anchorDate: DateTime,
447
+ interval: number,
448
+ ): Generator<DateTime> {
449
+ for (let step = 0; step < SCHEDULE_RECURRENCE_MAX_ITERATIONS; step++) {
450
+ yield anchorDate.plus({ days: step * interval });
451
+ }
452
+ }
453
+
454
+ /*
455
+ * Generate candidate local dates for a WEEKLY rule. Weeks advance by the
456
+ * interval and each listed weekday inside a week is emitted in order, so the
457
+ * stream stays chronological.
458
+ */
459
+
460
+ function* iterateWeeklyDates(
461
+ anchorDate: DateTime,
462
+ interval: number,
463
+ byWeekday?: number[] | null,
464
+ ): Generator<DateTime> {
465
+ // Luxon weekdays run 1 (Monday) to 7 (Sunday); the stored rule uses the
466
+ // JavaScript convention of 0 (Sunday) to 6 (Saturday)
467
+ const anchorWeekday = anchorDate.weekday % 7;
468
+ const weekdays = byWeekday?.length
469
+ ? getSortedRecurrenceUnits(byWeekday)
470
+ : [anchorWeekday];
471
+ // Sunday of the week containing the anchor
472
+ const firstWeekStart = anchorDate.minus({ days: anchorWeekday });
473
+
474
+ for (let step = 0; step < SCHEDULE_RECURRENCE_MAX_ITERATIONS; step++) {
475
+ const weekStart = firstWeekStart.plus({ weeks: step * interval });
476
+
477
+ for (const weekday of weekdays) {
478
+ yield weekStart.plus({ days: weekday });
479
+ }
480
+ }
481
+ }
482
+
483
+ /*
484
+ * Yield the requested month days that actually exist inside one month, in
485
+ * ascending order and at most once each.
486
+ *
487
+ * Two rules are applied here so both the monthly and yearly iterators get
488
+ * them. A day the month is too short for is skipped rather than rolled into
489
+ * the next month — "the 31st" must not silently become March 3rd. And the
490
+ * last-day sentinel is resolved before de-duplication, so a rule listing both
491
+ * -1 and 31 emits one instance in a 31-day month rather than two, which would
492
+ * otherwise double-count against the recurrence's own "count" bound.
493
+ */
494
+
495
+ function* iterateMonthDaysWithin(
496
+ monthStart: DateTime,
497
+ monthDays: number[],
498
+ ): Generator<DateTime> {
499
+ const daysInMonth = monthStart.daysInMonth || 0;
500
+ const emitted = new Set<number>();
501
+
502
+ for (const monthDay of monthDays) {
503
+ const day =
504
+ monthDay === SCHEDULE_RECURRENCE_LAST_DAY_OF_MONTH
505
+ ? daysInMonth
506
+ : monthDay;
507
+
508
+ if (day && day <= daysInMonth && !emitted.has(day)) {
509
+ emitted.add(day);
510
+ yield monthStart.set({ day });
511
+ }
512
+ }
513
+ }
514
+
515
+ /*
516
+ * Generate candidate local dates for a MONTHLY rule.
517
+ */
518
+
519
+ function* iterateMonthlyDates(
520
+ anchorDate: DateTime,
521
+ interval: number,
522
+ byMonthDay?: number[] | null,
523
+ ): Generator<DateTime> {
524
+ const monthDays = getSortedMonthDays(
525
+ byMonthDay?.length ? byMonthDay : [anchorDate.day],
526
+ );
527
+ const firstMonthStart = anchorDate.startOf('month');
528
+
529
+ for (let step = 0; step < SCHEDULE_RECURRENCE_MAX_ITERATIONS; step++) {
530
+ const monthStart = firstMonthStart.plus({ months: step * interval });
531
+
532
+ yield* iterateMonthDaysWithin(monthStart, monthDays);
533
+ }
534
+ }
535
+
536
+ /*
537
+ * Generate candidate local dates for a YEARLY rule.
538
+ */
539
+
540
+ function* iterateYearlyDates(
541
+ anchorDate: DateTime,
542
+ interval: number,
543
+ byMonth?: number[] | null,
544
+ byMonthDay?: number[] | null,
545
+ ): Generator<DateTime> {
546
+ const months = byMonth?.length
547
+ ? getSortedRecurrenceUnits(byMonth)
548
+ : [anchorDate.month];
549
+ const monthDays = getSortedMonthDays(
550
+ byMonthDay?.length ? byMonthDay : [anchorDate.day],
551
+ );
552
+ const firstYearStart = anchorDate.startOf('year');
553
+
554
+ for (let step = 0; step < SCHEDULE_RECURRENCE_MAX_ITERATIONS; step++) {
555
+ const yearStart = firstYearStart.plus({ years: step * interval });
556
+
557
+ for (const month of months) {
558
+ yield* iterateMonthDaysWithin(yearStart.set({ month }), monthDays);
559
+ }
560
+ }
561
+ }
562
+
563
+ /*
564
+ * Pick the candidate-date generator for one recurrence frequency.
565
+ */
566
+
567
+ function getRecurrenceDateIterator(
568
+ recurrence: ScheduleRecurrenceObj,
569
+ anchorDate: DateTime,
570
+ ): Generator<DateTime> {
571
+ const interval =
572
+ recurrence.interval && recurrence.interval > 0 ? recurrence.interval : 1;
573
+
574
+ switch (recurrence.freq) {
575
+ case 'DAILY':
576
+ return iterateDailyDates(anchorDate, interval);
577
+ case 'WEEKLY':
578
+ return iterateWeeklyDates(anchorDate, interval, recurrence.byWeekday);
579
+ case 'MONTHLY':
580
+ return iterateMonthlyDates(anchorDate, interval, recurrence.byMonthDay);
581
+ case 'YEARLY':
582
+ return iterateYearlyDates(
583
+ anchorDate,
584
+ interval,
585
+ recurrence.byMonth,
586
+ recurrence.byMonthDay,
587
+ );
588
+ }
589
+ }
590
+
591
+ /**
592
+ * Compute one occurrence's end instant. All-day entries advance by local
593
+ * calendar days so a day stays a day across a daylight-saving transition;
594
+ * timed entries advance by absolute minutes so a four-hour shift is always
595
+ * four hours of work.
596
+ */
597
+
598
+ export function getScheduleOccurrenceEndAt(
599
+ startAt: Date,
600
+ durationMinutes: number,
601
+ timeZone: string,
602
+ allDay?: boolean | null,
603
+ ): Date {
604
+ if (!allDay) {
605
+ return new Date(startAt.getTime() + durationMinutes * 60_000);
606
+ }
607
+
608
+ const zone = getSeriesTimeZone(timeZone);
609
+ const days = Math.max(1, Math.round(durationMinutes / 1440));
610
+
611
+ return DateTime.fromJSDate(startAt).setZone(zone).plus({ days }).toJSDate();
612
+ }
613
+
614
+ /**
615
+ * Expand one recurring series into concrete instances.
616
+ *
617
+ * Instances are produced in chronological order from the series start so
618
+ * "count" stays meaningful even when only a later window is requested; the
619
+ * from/to bounds filter that stream rather than reseeding it.
620
+ */
621
+
622
+ export function expandScheduleSeriesInstances(
623
+ series: ScheduleExpandableSeries,
624
+ options: ScheduleExpandOptions = {},
625
+ ): ScheduleExpandedInstance[] {
626
+ const startsAt = toDateOrNull(series.startsAt);
627
+ if (!startsAt) {
628
+ return [];
629
+ }
630
+
631
+ const zone = getSeriesTimeZone(series.timeZone);
632
+ const anchor = DateTime.fromJSDate(startsAt).setZone(zone);
633
+ if (!anchor.isValid) {
634
+ return [];
635
+ }
636
+
637
+ const anchorTime = getAnchorTime(anchor);
638
+ const anchorDate = anchor.startOf('day');
639
+ const from = toDateOrNull(options.from);
640
+ const to = toDateOrNull(options.to);
641
+ const limit =
642
+ options.limit && options.limit > 0
643
+ ? options.limit
644
+ : Number.POSITIVE_INFINITY;
645
+ const until = toDateOrNull(series.recurrence?.until);
646
+ const seriesEndsAt = toDateOrNull(series.endsAt);
647
+ const maxCount =
648
+ series.recurrence?.count && series.recurrence.count > 0
649
+ ? series.recurrence.count
650
+ : Number.POSITIVE_INFINITY;
651
+
652
+ // The last instant any instance may start at; whichever bound is tightest
653
+ const hardStopAt = [until, seriesEndsAt, to]
654
+ .filter((value): value is Date => !!value)
655
+ .reduce<Date | null>(
656
+ (tightest, value) => (!tightest || value < tightest ? value : tightest),
657
+ null,
658
+ );
659
+
660
+ const instances: ScheduleExpandedInstance[] = [];
661
+ const dates = getRecurrenceDateIterator(series.recurrence, anchorDate);
662
+ let emittedFromSeriesStart = 0;
663
+ let iterations = 0;
664
+
665
+ for (const localDate of dates) {
666
+ if (++iterations > SCHEDULE_RECURRENCE_MAX_ITERATIONS) {
667
+ break;
668
+ }
669
+
670
+ const start = getInstanceStart(localDate, anchorTime);
671
+ if (!start) {
672
+ continue;
673
+ }
674
+
675
+ const startAt = start.toJSDate();
676
+
677
+ // Weekly and monthly iteration can emit dates inside the anchor's own
678
+ // week or month that fall before the series began
679
+ if (startAt < startsAt) {
680
+ continue;
681
+ }
682
+
683
+ // "until" and the series end are inclusive bounds on the start instant;
684
+ // "to" is exclusive, and is applied again when the instance is kept
685
+ if (until && startAt > until) {
686
+ break;
687
+ }
688
+
689
+ if (seriesEndsAt && startAt > seriesEndsAt) {
690
+ break;
691
+ }
692
+
693
+ if (to && startAt >= to) {
694
+ break;
695
+ }
696
+
697
+ emittedFromSeriesStart++;
698
+ if (emittedFromSeriesStart > maxCount) {
699
+ break;
700
+ }
701
+
702
+ if (from && startAt < from) {
703
+ continue;
704
+ }
705
+
706
+ instances.push({
707
+ recurrenceKey: startAt,
708
+ startAt,
709
+ endAt: getScheduleOccurrenceEndAt(
710
+ startAt,
711
+ series.durationMinutes,
712
+ zone,
713
+ series.allDay,
714
+ ),
715
+ });
716
+
717
+ if (instances.length >= limit) {
718
+ break;
719
+ }
720
+
721
+ if (hardStopAt && startAt >= hardStopAt) {
722
+ break;
723
+ }
724
+ }
725
+
726
+ return instances;
727
+ }
728
+
729
+ /**
730
+ * Return the instant the materialization horizon should reach from "now".
731
+ */
732
+
733
+ export function getScheduleMaterializationHorizon(now: Date): Date {
734
+ return new Date(
735
+ now.getTime() + SCHEDULE_MATERIALIZATION_HORIZON_DAYS * 86_400_000,
736
+ );
737
+ }
738
+
739
+ /**
740
+ * Check whether one duration is within the range an occurrence may span.
741
+ */
742
+
743
+ export function isValidScheduleDurationMinutes(
744
+ durationMinutes: unknown,
745
+ ): boolean {
746
+ const minutes = Number(durationMinutes);
747
+
748
+ return (
749
+ Number.isInteger(minutes) &&
750
+ minutes > 0 &&
751
+ minutes <= SCHEDULE_OCCURRENCE_MAX_DURATION_MINUTES
752
+ );
753
+ }
754
+
755
+ /**
756
+ * Render one recurrence rule as an RFC 5545 RRULE line for calendar feed
757
+ * export. The stored rule is the source of truth; this is a one-way
758
+ * projection used only when generating ICS.
759
+ */
760
+
761
+ export function getScheduleRecurrenceRRule(
762
+ recurrence: ScheduleRecurrenceObj,
763
+ ): string {
764
+ const weekdayCodes = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
765
+ const parts = [`FREQ=${recurrence.freq}`];
766
+
767
+ if (recurrence.interval && recurrence.interval > 1) {
768
+ parts.push(`INTERVAL=${recurrence.interval}`);
769
+ }
770
+
771
+ if (recurrence.byWeekday?.length) {
772
+ parts.push(
773
+ `BYDAY=${recurrence.byWeekday.map((weekday) => weekdayCodes[weekday]).join(',')}`,
774
+ );
775
+ }
776
+
777
+ if (recurrence.byMonthDay?.length) {
778
+ parts.push(`BYMONTHDAY=${recurrence.byMonthDay.join(',')}`);
779
+ }
780
+
781
+ if (recurrence.byMonth?.length) {
782
+ parts.push(`BYMONTH=${recurrence.byMonth.join(',')}`);
783
+ }
784
+
785
+ if (recurrence.count) {
786
+ parts.push(`COUNT=${recurrence.count}`);
787
+ }
788
+
789
+ if (recurrence.until) {
790
+ parts.push(
791
+ `UNTIL=${new Date(recurrence.until)
792
+ .toISOString()
793
+ .replace(/[-:]/g, '')
794
+ .replace(/\.\d{3}/, '')}`,
795
+ );
796
+ }
797
+
798
+ return parts.join(';');
799
+ }