@thyrith/momentkh 2.5.5 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1063 @@
1
+ "use strict";
2
+ /**
3
+ * MomentKH - Standalone Khmer Calendar Library (TypeScript)
4
+ *
5
+ * A simplified, standalone library for Khmer calendar conversion
6
+ * No dependencies required
7
+ *
8
+ * Based on:
9
+ * - khmer_calendar.cpp implementation
10
+ * - Original momentkh library
11
+ *
12
+ * @version 2.0.0
13
+ * @license MIT
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.constants = exports.DayOfWeek = exports.EraYear = exports.AnimalYear = exports.MonthIndex = exports.MoonPhase = void 0;
17
+ exports.fromGregorian = fromGregorian;
18
+ exports.fromKhmer = fromKhmer;
19
+ exports.getNewYear = getNewYear;
20
+ exports.format = format;
21
+ exports.fromDate = fromDate;
22
+ exports.toDate = toDate;
23
+ // ============================================================================
24
+ // Type Definitions
25
+ // ============================================================================
26
+ // Enums for better type safety and ease of use
27
+ var MoonPhase;
28
+ (function (MoonPhase) {
29
+ MoonPhase[MoonPhase["Waxing"] = 0] = "Waxing";
30
+ MoonPhase[MoonPhase["Waning"] = 1] = "Waning"; // រោច
31
+ })(MoonPhase || (exports.MoonPhase = MoonPhase = {}));
32
+ var MonthIndex;
33
+ (function (MonthIndex) {
34
+ MonthIndex[MonthIndex["Migasir"] = 0] = "Migasir";
35
+ MonthIndex[MonthIndex["Boss"] = 1] = "Boss";
36
+ MonthIndex[MonthIndex["Meak"] = 2] = "Meak";
37
+ MonthIndex[MonthIndex["Phalkun"] = 3] = "Phalkun";
38
+ MonthIndex[MonthIndex["Cheit"] = 4] = "Cheit";
39
+ MonthIndex[MonthIndex["Pisakh"] = 5] = "Pisakh";
40
+ MonthIndex[MonthIndex["Jesth"] = 6] = "Jesth";
41
+ MonthIndex[MonthIndex["Asadh"] = 7] = "Asadh";
42
+ MonthIndex[MonthIndex["Srap"] = 8] = "Srap";
43
+ MonthIndex[MonthIndex["Phatrabot"] = 9] = "Phatrabot";
44
+ MonthIndex[MonthIndex["Assoch"] = 10] = "Assoch";
45
+ MonthIndex[MonthIndex["Kadeuk"] = 11] = "Kadeuk";
46
+ MonthIndex[MonthIndex["Pathamasadh"] = 12] = "Pathamasadh";
47
+ MonthIndex[MonthIndex["Tutiyasadh"] = 13] = "Tutiyasadh"; // ទុតិយាសាឍ
48
+ })(MonthIndex || (exports.MonthIndex = MonthIndex = {}));
49
+ var AnimalYear;
50
+ (function (AnimalYear) {
51
+ AnimalYear[AnimalYear["Chhut"] = 0] = "Chhut";
52
+ AnimalYear[AnimalYear["Chlov"] = 1] = "Chlov";
53
+ AnimalYear[AnimalYear["Khal"] = 2] = "Khal";
54
+ AnimalYear[AnimalYear["Thos"] = 3] = "Thos";
55
+ AnimalYear[AnimalYear["Rong"] = 4] = "Rong";
56
+ AnimalYear[AnimalYear["Masagn"] = 5] = "Masagn";
57
+ AnimalYear[AnimalYear["Momee"] = 6] = "Momee";
58
+ AnimalYear[AnimalYear["Momae"] = 7] = "Momae";
59
+ AnimalYear[AnimalYear["Vok"] = 8] = "Vok";
60
+ AnimalYear[AnimalYear["Roka"] = 9] = "Roka";
61
+ AnimalYear[AnimalYear["Cho"] = 10] = "Cho";
62
+ AnimalYear[AnimalYear["Kor"] = 11] = "Kor"; // កុរ - Pig
63
+ })(AnimalYear || (exports.AnimalYear = AnimalYear = {}));
64
+ var EraYear;
65
+ (function (EraYear) {
66
+ EraYear[EraYear["SamridhiSak"] = 0] = "SamridhiSak";
67
+ EraYear[EraYear["AekSak"] = 1] = "AekSak";
68
+ EraYear[EraYear["ToSak"] = 2] = "ToSak";
69
+ EraYear[EraYear["TreiSak"] = 3] = "TreiSak";
70
+ EraYear[EraYear["ChattvaSak"] = 4] = "ChattvaSak";
71
+ EraYear[EraYear["PanchaSak"] = 5] = "PanchaSak";
72
+ EraYear[EraYear["ChhaSak"] = 6] = "ChhaSak";
73
+ EraYear[EraYear["SappaSak"] = 7] = "SappaSak";
74
+ EraYear[EraYear["AtthaSak"] = 8] = "AtthaSak";
75
+ EraYear[EraYear["NappaSak"] = 9] = "NappaSak"; // នព្វស័ក
76
+ })(EraYear || (exports.EraYear = EraYear = {}));
77
+ var DayOfWeek;
78
+ (function (DayOfWeek) {
79
+ DayOfWeek[DayOfWeek["Sunday"] = 0] = "Sunday";
80
+ DayOfWeek[DayOfWeek["Monday"] = 1] = "Monday";
81
+ DayOfWeek[DayOfWeek["Tuesday"] = 2] = "Tuesday";
82
+ DayOfWeek[DayOfWeek["Wednesday"] = 3] = "Wednesday";
83
+ DayOfWeek[DayOfWeek["Thursday"] = 4] = "Thursday";
84
+ DayOfWeek[DayOfWeek["Friday"] = 5] = "Friday";
85
+ DayOfWeek[DayOfWeek["Saturday"] = 6] = "Saturday"; // សៅរ៍
86
+ })(DayOfWeek || (exports.DayOfWeek = DayOfWeek = {}));
87
+ // ============================================================================
88
+ // Constants and Locale Data
89
+ // ============================================================================
90
+ const LunarMonths = {
91
+ 'មិគសិរ': 0, 'បុស្ស': 1, 'មាឃ': 2, 'ផល្គុន': 3,
92
+ 'ចេត្រ': 4, 'ពិសាខ': 5, 'ជេស្ឋ': 6, 'អាសាឍ': 7,
93
+ 'ស្រាពណ៍': 8, 'ភទ្របទ': 9, 'អស្សុជ': 10, 'កត្ដិក': 11,
94
+ 'បឋមាសាឍ': 12, 'ទុតិយាសាឍ': 13
95
+ };
96
+ const LunarMonthNames = [
97
+ 'មិគសិរ', 'បុស្ស', 'មាឃ', 'ផល្គុន', 'ចេត្រ', 'ពិសាខ',
98
+ 'ជេស្ឋ', 'អាសាឍ', 'ស្រាពណ៍', 'ភទ្របទ', 'អស្សុជ', 'កត្ដិក',
99
+ 'បឋមាសាឍ', 'ទុតិយាសាឍ'
100
+ ];
101
+ const SolarMonthNames = [
102
+ 'មករា', 'កុម្ភៈ', 'មីនា', 'មេសា', 'ឧសភា', 'មិថុនា',
103
+ 'កក្កដា', 'សីហា', 'កញ្ញា', 'តុលា', 'វិច្ឆិកា', 'ធ្នូ'
104
+ ];
105
+ const AnimalYearNames = [
106
+ 'ជូត', 'ឆ្លូវ', 'ខាល', 'ថោះ', 'រោង', 'ម្សាញ់',
107
+ 'មមី', 'មមែ', 'វក', 'រកា', 'ច', 'កុរ'
108
+ ];
109
+ const EraYearNames = [
110
+ 'សំរឹទ្ធិស័ក', 'ឯកស័ក', 'ទោស័ក', 'ត្រីស័ក', 'ចត្វាស័ក',
111
+ 'បញ្ចស័ក', 'ឆស័ក', 'សប្តស័ក', 'អដ្ឋស័ក', 'នព្វស័ក'
112
+ ];
113
+ const WeekdayNames = [
114
+ 'អាទិត្យ', 'ចន្ទ', 'អង្គារ', 'ពុធ', 'ព្រហស្បតិ៍', 'សុក្រ', 'សៅរ៍'
115
+ ];
116
+ const WeekdayNamesShort = ['អា', 'ច', 'អ', 'ព', 'ព្រ', 'សុ', 'ស'];
117
+ const MoonStatusNames = ['កើត', 'រោច'];
118
+ const MoonStatusShort = ['ក', 'រ'];
119
+ const MoonDaySymbols = [
120
+ '᧡', '᧢', '᧣', '᧤', '᧥', '᧦', '᧧', '᧨', '᧩', '᧪',
121
+ '᧫', '᧬', '᧭', '᧮', '᧯', '᧱', '᧲', '᧳', '᧴', '᧵',
122
+ '᧶', '᧷', '᧸', '᧹', '᧺', '᧻', '᧼', '᧽', '᧾', '᧿'
123
+ ];
124
+ const KhmerNumerals = {
125
+ '0': '០', '1': '១', '2': '២', '3': '៣', '4': '៤',
126
+ '5': '៥', '6': '៦', '7': '៧', '8': '៨', '9': '៩'
127
+ };
128
+ // Exceptional New Year moments (cached values for specific years)
129
+ const khNewYearMoments = {
130
+ '1879': '12-04-1879 11:36',
131
+ '1897': '13-04-1897 02:00',
132
+ '2011': '14-04-2011 13:12',
133
+ '2012': '14-04-2012 19:11',
134
+ '2013': '14-04-2013 02:12',
135
+ '2014': '14-04-2014 08:07',
136
+ '2015': '14-04-2015 14:02',
137
+ '2024': '13-04-2024 22:17',
138
+ };
139
+ // ============================================================================
140
+ // Utility Functions
141
+ // ============================================================================
142
+ function toKhmerNumeral(num) {
143
+ return String(num).replace(/\d/g, d => KhmerNumerals[d]);
144
+ }
145
+ function isGregorianLeapYear(year) {
146
+ return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
147
+ }
148
+ function getDaysInGregorianMonth(year, month) {
149
+ const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
150
+ if (month === 2 && isGregorianLeapYear(year)) {
151
+ return 29;
152
+ }
153
+ return daysInMonth[month - 1];
154
+ }
155
+ // Julian Day Number conversion
156
+ function gregorianToJulianDay(year, month, day) {
157
+ const a = Math.floor((14 - month) / 12);
158
+ const y = year + 4800 - a;
159
+ const m = month + 12 * a - 3;
160
+ return day + Math.floor((153 * m + 2) / 5) + 365 * y +
161
+ Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;
162
+ }
163
+ function julianDayToGregorian(jdn) {
164
+ const a = jdn + 32044;
165
+ const b = Math.floor((4 * a + 3) / 146097);
166
+ const c = a - Math.floor((146097 * b) / 4);
167
+ const d = Math.floor((4 * c + 3) / 1461);
168
+ const e = c - Math.floor((1461 * d) / 4);
169
+ const m = Math.floor((5 * e + 2) / 153);
170
+ const day = e - Math.floor((153 * m + 2) / 5) + 1;
171
+ const month = m + 3 - 12 * Math.floor(m / 10);
172
+ const year = 100 * b + d - 4800 + Math.floor(m / 10);
173
+ return { year, month, day };
174
+ }
175
+ function getDayOfWeek(year, month, day) {
176
+ const jdn = gregorianToJulianDay(year, month, day);
177
+ // JDN % 7: where 0=Monday, 1=Tuesday, ..., 6=Sunday
178
+ // We want: 0=Sunday, 1=Monday, ..., 6=Saturday
179
+ // So we need to convert: (jdn + 1) % 7
180
+ return (jdn + 1) % 7;
181
+ }
182
+ // ============================================================================
183
+ // Input Validation Functions
184
+ // ============================================================================
185
+ /**
186
+ * Validates Gregorian date parameters
187
+ * @throws {Error} If any parameter is invalid
188
+ */
189
+ function validateGregorianDate(year, month, day, hour = 0, minute = 0, second = 0) {
190
+ // Validate types
191
+ if (typeof year !== 'number' || isNaN(year)) {
192
+ throw new Error(`Invalid year: ${year}. Year must be a valid number.`);
193
+ }
194
+ if (typeof month !== 'number' || isNaN(month)) {
195
+ throw new Error(`Invalid month: ${month}. Month must be a valid number.`);
196
+ }
197
+ if (typeof day !== 'number' || isNaN(day)) {
198
+ throw new Error(`Invalid day: ${day}. Day must be a valid number.`);
199
+ }
200
+ if (typeof hour !== 'number' || isNaN(hour)) {
201
+ throw new Error(`Invalid hour: ${hour}. Hour must be a valid number.`);
202
+ }
203
+ if (typeof minute !== 'number' || isNaN(minute)) {
204
+ throw new Error(`Invalid minute: ${minute}. Minute must be a valid number.`);
205
+ }
206
+ if (typeof second !== 'number' || isNaN(second)) {
207
+ throw new Error(`Invalid second: ${second}. Second must be a valid number.`);
208
+ }
209
+ // Validate month range (1-12)
210
+ if (month < 1 || month > 12) {
211
+ throw new Error(`Invalid month: ${month}. Month must be between 1 and 12.`);
212
+ }
213
+ // Validate day range for the specific month/year
214
+ const daysInMonth = getDaysInGregorianMonth(year, month);
215
+ if (day < 1 || day > daysInMonth) {
216
+ const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
217
+ 'July', 'August', 'September', 'October', 'November', 'December'];
218
+ throw new Error(`Invalid day: ${day}. ${monthNames[month - 1]} ${year} has ${daysInMonth} days.`);
219
+ }
220
+ // Validate hour (0-23)
221
+ if (hour < 0 || hour > 23) {
222
+ throw new Error(`Invalid hour: ${hour}. Hour must be between 0 and 23.`);
223
+ }
224
+ // Validate minute (0-59)
225
+ if (minute < 0 || minute > 59) {
226
+ throw new Error(`Invalid minute: ${minute}. Minute must be between 0 and 59.`);
227
+ }
228
+ // Validate second (0-59)
229
+ if (second < 0 || second > 59) {
230
+ throw new Error(`Invalid second: ${second}. Second must be between 0 and 59.`);
231
+ }
232
+ }
233
+ /**
234
+ * Validates Khmer date parameters
235
+ * @throws {Error} If any parameter is invalid
236
+ */
237
+ function validateKhmerDate(day, moonPhase, monthIndex, beYear) {
238
+ // Validate types
239
+ if (typeof day !== 'number' || isNaN(day)) {
240
+ throw new Error(`Invalid day: ${day}. Day must be a valid number.`);
241
+ }
242
+ if (typeof moonPhase !== 'number' || isNaN(moonPhase)) {
243
+ throw new Error(`Invalid moonPhase: ${moonPhase}. moonPhase must be a valid number.`);
244
+ }
245
+ if (typeof monthIndex !== 'number' || isNaN(monthIndex)) {
246
+ throw new Error(`Invalid monthIndex: ${monthIndex}. monthIndex must be a valid number.`);
247
+ }
248
+ if (typeof beYear !== 'number' || isNaN(beYear)) {
249
+ throw new Error(`Invalid beYear: ${beYear}. beYear must be a valid number.`);
250
+ }
251
+ // Validate day (1-15)
252
+ if (day < 1 || day > 15) {
253
+ throw new Error(`Invalid day: ${day}. Lunar day must be between 1 and 15.`);
254
+ }
255
+ // Validate moonPhase (0 = Waxing, 1 = Waning)
256
+ const moonPhaseNum = typeof moonPhase === 'number' ? moonPhase : moonPhase;
257
+ if (moonPhaseNum !== 0 && moonPhaseNum !== 1) {
258
+ throw new Error(`Invalid moonPhase: ${moonPhase}. moonPhase must be 0 (Waxing/កើត) or 1 (Waning/រោច).`);
259
+ }
260
+ // Validate monthIndex (0-13)
261
+ const monthIndexNum = typeof monthIndex === 'number' ? monthIndex : monthIndex;
262
+ if (monthIndexNum < 0 || monthIndexNum > 13) {
263
+ throw new Error(`Invalid monthIndex: ${monthIndex}. monthIndex must be between 0 and 13.`);
264
+ }
265
+ // Validate beYear (reasonable range: 2000-3000)
266
+ if (beYear < 2000 || beYear > 3000) {
267
+ throw new Error(`Invalid beYear: ${beYear}. beYear must be between 2000 and 3000.`);
268
+ }
269
+ // Additional validation: check if leap months (12, 13) are used in non-leap years
270
+ // This is done in the conversion function since it requires more complex logic
271
+ }
272
+ /**
273
+ * Validates JavaScript Date object
274
+ * @throws {Error} If Date object is invalid
275
+ */
276
+ function validateDateObject(date) {
277
+ if (!(date instanceof Date)) {
278
+ throw new Error('Invalid input: Expected a Date object.');
279
+ }
280
+ if (isNaN(date.getTime())) {
281
+ throw new Error('Invalid Date object: Date is not a valid date.');
282
+ }
283
+ }
284
+ // ============================================================================
285
+ // Era Conversions
286
+ // ============================================================================
287
+ function adToJs(adYear) {
288
+ return adYear - 638;
289
+ }
290
+ function adToBe(adYear) {
291
+ return adYear + 544;
292
+ }
293
+ function beToAd(beYear) {
294
+ return beYear - 544;
295
+ }
296
+ function jsToAd(jsYear) {
297
+ return jsYear + 638;
298
+ }
299
+ function beToJs(beYear) {
300
+ return beYear - 1182;
301
+ }
302
+ function jsToBe(jsYear) {
303
+ return jsYear + 1182;
304
+ }
305
+ // ============================================================================
306
+ // Calendar Calculation Functions
307
+ // ============================================================================
308
+ function getAharkun(beYear) {
309
+ return Math.floor((beYear * 292207 + 499) / 800) + 4;
310
+ }
311
+ function getAharkunMod(beYear) {
312
+ return (beYear * 292207 + 499) % 800;
313
+ }
314
+ function getKromthupul(beYear) {
315
+ return 800 - getAharkunMod(beYear);
316
+ }
317
+ function getAvoman(beYear) {
318
+ return (getAharkun(beYear) * 11 + 25) % 692;
319
+ }
320
+ function getBodithey(beYear) {
321
+ const aharkun = getAharkun(beYear);
322
+ return (Math.floor((aharkun * 11 + 25) / 692) + aharkun + 29) % 30;
323
+ }
324
+ function isKhmerSolarLeap(beYear) {
325
+ return getKromthupul(beYear) <= 207;
326
+ }
327
+ function isKhmerLeapDayByCalculation(beYear) {
328
+ const avoman = getAvoman(beYear);
329
+ const isSolarLeap = isKhmerSolarLeap(beYear);
330
+ if (avoman === 0 && getAvoman(beYear - 1) === 137) {
331
+ return true;
332
+ }
333
+ else if (isSolarLeap) {
334
+ return avoman < 127;
335
+ }
336
+ else if (avoman === 137 && getAvoman(beYear + 1) === 0) {
337
+ return false;
338
+ }
339
+ else if (avoman < 138) {
340
+ return true;
341
+ }
342
+ return false;
343
+ }
344
+ function isKhmerLeapMonth(beYear) {
345
+ const bodithey = getBodithey(beYear);
346
+ const boditheyNextYear = getBodithey(beYear + 1);
347
+ if (bodithey === 25 && boditheyNextYear === 5) {
348
+ return false;
349
+ }
350
+ return (bodithey === 24 && boditheyNextYear === 6) ||
351
+ (bodithey >= 25) ||
352
+ (bodithey < 6);
353
+ }
354
+ function getLeapType(beYear) {
355
+ if (isKhmerLeapMonth(beYear)) {
356
+ return 1; // Leap month (អធិកមាស)
357
+ }
358
+ else if (isKhmerLeapDayByCalculation(beYear)) {
359
+ return 2; // Leap day (ចន្ទ្រាធិមាស)
360
+ }
361
+ else if (isKhmerLeapMonth(beYear - 1)) {
362
+ let previousYear = beYear - 1;
363
+ while (true) {
364
+ if (isKhmerLeapDayByCalculation(previousYear)) {
365
+ return 2;
366
+ }
367
+ previousYear -= 1;
368
+ if (!isKhmerLeapMonth(previousYear)) {
369
+ return 0;
370
+ }
371
+ }
372
+ }
373
+ return 0; // Regular year
374
+ }
375
+ function getNumberOfDaysInKhmerMonth(monthIndex, beYear) {
376
+ const leapType = getLeapType(beYear);
377
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
378
+ if (idx === MonthIndex.Jesth && leapType === 2) { // ជេស្ឋ with leap day
379
+ return 30;
380
+ }
381
+ if (idx === MonthIndex.Pathamasadh || idx === MonthIndex.Tutiyasadh) { // បឋមាសាឍ, ទុតិយាសាឍ
382
+ return leapType === 1 ? 30 : 0;
383
+ }
384
+ // Alternating pattern: even months = 29 days, odd months = 30 days
385
+ // មិគសិរ:29, បុស្ស:30, មាឃ:29, ផល្គុន:30, ចេត្រ:29, ពិសាខ:30, ជេស្ឋ:29, អាសាឍ:30, etc.
386
+ return idx % 2 === 0 ? 29 : 30;
387
+ }
388
+ function getNumberOfDaysInKhmerYear(beYear) {
389
+ const leapType = getLeapType(beYear);
390
+ if (leapType === 1)
391
+ return 384; // Leap month
392
+ if (leapType === 2)
393
+ return 355; // Leap day
394
+ return 354; // Regular
395
+ }
396
+ function nextMonthOf(monthIndex, beYear) {
397
+ const leapType = getLeapType(beYear);
398
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
399
+ if (idx === MonthIndex.Jesth && leapType === 1) { // ជេស្ឋ in leap month year
400
+ return MonthIndex.Pathamasadh; // បឋមាសាឍ
401
+ }
402
+ if (idx === MonthIndex.Kadeuk)
403
+ return MonthIndex.Migasir; // កត្ដិក -> មិគសិរ
404
+ if (idx === MonthIndex.Pathamasadh)
405
+ return MonthIndex.Tutiyasadh; // បឋមាសាឍ -> ទុតិយាសាឍ
406
+ if (idx === MonthIndex.Tutiyasadh)
407
+ return MonthIndex.Srap; // ទុតិយាសាឍ -> ស្រាពណ៍
408
+ return (idx + 1);
409
+ }
410
+ function previousMonthOf(monthIndex, beYear) {
411
+ const leapType = getLeapType(beYear);
412
+ const idx = typeof monthIndex === 'number' ? monthIndex : monthIndex;
413
+ if (idx === MonthIndex.Migasir)
414
+ return MonthIndex.Kadeuk; // មិគសិរ -> កត្ដិក
415
+ if (idx === MonthIndex.Srap && leapType === 1)
416
+ return MonthIndex.Tutiyasadh; // ស្រាពណ៍ -> ទុតិយាសាឍ (leap)
417
+ if (idx === MonthIndex.Tutiyasadh)
418
+ return MonthIndex.Pathamasadh; // ទុតិយាសាឍ -> បឋមាសាឍ
419
+ if (idx === MonthIndex.Pathamasadh)
420
+ return MonthIndex.Jesth; // បឋមាសាឍ -> ជេស្ឋ
421
+ return (idx - 1);
422
+ }
423
+ // ============================================================================
424
+ // Khmer New Year Calculation (JS Year based)
425
+ // ============================================================================
426
+ function getAharkunJs(jsYear) {
427
+ const h = jsYear * 292207 + 373;
428
+ return Math.floor(h / 800) + 1;
429
+ }
430
+ function getAvomanJs(jsYear) {
431
+ return (getAharkunJs(jsYear) * 11 + 650) % 692;
432
+ }
433
+ function getKromthupulJs(jsYear) {
434
+ return 800 - ((292207 * jsYear + 373) % 800);
435
+ }
436
+ function getBoditheyJs(jsYear) {
437
+ const aharkun = getAharkunJs(jsYear);
438
+ const a = 11 * aharkun + 650;
439
+ return (aharkun + Math.floor(a / 692)) % 30;
440
+ }
441
+ function isAdhikameas(jsYear) {
442
+ const bodithey = getBoditheyJs(jsYear);
443
+ const boditheyNext = getBoditheyJs(jsYear + 1);
444
+ if (bodithey === 24 && boditheyNext === 6)
445
+ return true;
446
+ if (bodithey === 25 && boditheyNext === 5)
447
+ return false;
448
+ return bodithey > 24 || bodithey < 6;
449
+ }
450
+ function isChantrathimeas(jsYear) {
451
+ const avoman = getAvomanJs(jsYear);
452
+ const avomanNext = getAvomanJs(jsYear + 1);
453
+ const avomanPrev = getAvomanJs(jsYear - 1);
454
+ const isSolarLeap = getKromthupulJs(jsYear) <= 207;
455
+ if (avoman === 0 && avomanPrev === 137)
456
+ return true;
457
+ if (isSolarLeap)
458
+ return avoman < 127;
459
+ if (avoman === 137 && avomanNext === 0)
460
+ return false;
461
+ if (!isSolarLeap && avoman < 138)
462
+ return true;
463
+ if (avomanPrev === 137 && avoman === 0)
464
+ return true;
465
+ return false;
466
+ }
467
+ function has366Days(jsYear) {
468
+ return getKromthupulJs(jsYear) <= 207;
469
+ }
470
+ function getSunInfo(jsYear, sotin) {
471
+ const infoOfPrevYear = {
472
+ kromathopol: getKromthupulJs(jsYear - 1)
473
+ };
474
+ // Sun average as Libda
475
+ const r2 = 800 * sotin + infoOfPrevYear.kromathopol;
476
+ const reasey = Math.floor(r2 / 24350);
477
+ const r3 = r2 % 24350;
478
+ const angsar = Math.floor(r3 / 811);
479
+ const r4 = r3 % 811;
480
+ const l1 = Math.floor(r4 / 14);
481
+ const libda = l1 - 3;
482
+ const sunAverageAsLibda = (30 * 60 * reasey) + (60 * angsar) + libda;
483
+ // Left over
484
+ const s1 = ((30 * 60 * 2) + (60 * 20));
485
+ let leftOver = sunAverageAsLibda - s1;
486
+ if (sunAverageAsLibda < s1) {
487
+ leftOver += (30 * 60 * 12);
488
+ }
489
+ const kaen = Math.floor(leftOver / (30 * 60));
490
+ // Last left over
491
+ let rs = -1;
492
+ if ([0, 1, 2].includes(kaen)) {
493
+ rs = kaen;
494
+ }
495
+ else if ([3, 4, 5].includes(kaen)) {
496
+ rs = (30 * 60 * 6) - leftOver;
497
+ }
498
+ else if ([6, 7, 8].includes(kaen)) {
499
+ rs = leftOver - (30 * 60 * 6);
500
+ }
501
+ else if ([9, 10, 11].includes(kaen)) {
502
+ rs = ((30 * 60 * 11) + (60 * 29) + 60) - leftOver;
503
+ }
504
+ const lastLeftOver = {
505
+ reasey: Math.floor(rs / (30 * 60)),
506
+ angsar: Math.floor((rs % (30 * 60)) / 60),
507
+ libda: rs % 60
508
+ };
509
+ // Khan and pouichalip
510
+ let khan, pouichalip;
511
+ if (lastLeftOver.angsar >= 15) {
512
+ khan = 2 * lastLeftOver.reasey + 1;
513
+ pouichalip = 60 * (lastLeftOver.angsar - 15) + lastLeftOver.libda;
514
+ }
515
+ else {
516
+ khan = 2 * lastLeftOver.reasey;
517
+ pouichalip = 60 * lastLeftOver.angsar + lastLeftOver.libda;
518
+ }
519
+ // Chhaya sun
520
+ const chhayaSunMap = [
521
+ { multiplicity: 35, chhaya: 0 },
522
+ { multiplicity: 32, chhaya: 35 },
523
+ { multiplicity: 27, chhaya: 67 },
524
+ { multiplicity: 22, chhaya: 94 },
525
+ { multiplicity: 13, chhaya: 116 },
526
+ { multiplicity: 5, chhaya: 129 }
527
+ ];
528
+ const chhayaSun = khan <= 5 ? chhayaSunMap[khan] : { multiplicity: 0, chhaya: 134 };
529
+ const q = Math.floor((pouichalip * chhayaSun.multiplicity) / 900);
530
+ const pholAsLibda = q + chhayaSun.chhaya;
531
+ // Sun inauguration
532
+ const sunInaugurationAsLibda = kaen <= 5
533
+ ? sunAverageAsLibda - pholAsLibda
534
+ : sunAverageAsLibda + pholAsLibda;
535
+ return {
536
+ sunInaugurationAsLibda,
537
+ reasey: Math.floor(sunInaugurationAsLibda / (30 * 60)),
538
+ angsar: Math.floor((sunInaugurationAsLibda % (30 * 60)) / 60),
539
+ libda: sunInaugurationAsLibda % 60
540
+ };
541
+ }
542
+ function getNewYearInfo(jsYear) {
543
+ const sotins = has366Days(jsYear - 1)
544
+ ? [363, 364, 365, 366]
545
+ : [362, 363, 364, 365];
546
+ const newYearsDaySotins = sotins.map(sotin => getSunInfo(jsYear, sotin));
547
+ // Find time of new year
548
+ let timeOfNewYear = { hour: 0, minute: 0 };
549
+ for (const sotin of newYearsDaySotins) {
550
+ if (sotin.angsar === 0) {
551
+ const minutes = (24 * 60) - (sotin.libda * 24);
552
+ timeOfNewYear = {
553
+ hour: Math.floor(minutes / 60) % 24,
554
+ minute: minutes % 60
555
+ };
556
+ break;
557
+ }
558
+ }
559
+ // Number of Vanabat days
560
+ const numberOfVanabatDays = (newYearsDaySotins[0].angsar === 0) ? 2 : 1;
561
+ return {
562
+ timeOfNewYear,
563
+ numberOfVanabatDays,
564
+ newYearsDaySotins
565
+ };
566
+ }
567
+ // ============================================================================
568
+ // Khmer Date Class
569
+ // ============================================================================
570
+ class KhmerDate {
571
+ constructor(day, moonPhase, monthIndex, beYear) {
572
+ this.day = day;
573
+ this.moonPhase = moonPhase;
574
+ this.monthIndex = monthIndex;
575
+ this.beYear = beYear;
576
+ }
577
+ // Get day number (0-29) - converts from 1-based internal to 0-based external
578
+ getDayNumber() {
579
+ if (this.moonPhase === MoonPhase.Waxing) { // កើត
580
+ return this.day - 1; // day 1-15 → dayNum 0-14
581
+ }
582
+ else { // រោច
583
+ return 15 + (this.day - 1); // day 1-15 → dayNum 15-29
584
+ }
585
+ }
586
+ static fromDayNumber(dayNum) {
587
+ // Converts from 0-based dayNum to 1-based day
588
+ if (dayNum < 15) {
589
+ return { day: dayNum + 1, moonPhase: MoonPhase.Waxing }; // dayNum 0-14 → day 1-15
590
+ }
591
+ else {
592
+ return { day: (dayNum - 15) + 1, moonPhase: MoonPhase.Waning }; // dayNum 15-29 → day 1-15
593
+ }
594
+ }
595
+ addDays(count) {
596
+ if (count === 0)
597
+ return this;
598
+ if (count < 0)
599
+ return this.subtractDays(-count);
600
+ let result = new KhmerDate(this.day, this.moonPhase, this.monthIndex, this.beYear);
601
+ let remaining = count;
602
+ while (remaining > 0) {
603
+ const daysInMonth = getNumberOfDaysInKhmerMonth(result.monthIndex, result.beYear);
604
+ const currentDayNum = result.getDayNumber();
605
+ const daysLeftInMonth = (daysInMonth - 1) - currentDayNum;
606
+ if (remaining <= daysLeftInMonth) {
607
+ const newDayNum = currentDayNum + remaining;
608
+ const newDay = KhmerDate.fromDayNumber(newDayNum);
609
+ let newBeYear = result.beYear;
610
+ if (result.monthIndex === MonthIndex.Pisakh) { // ពិសាខ
611
+ if (result.moonPhase === MoonPhase.Waxing && newDay.moonPhase === MoonPhase.Waning) {
612
+ newBeYear++;
613
+ }
614
+ }
615
+ result = new KhmerDate(newDay.day, newDay.moonPhase, result.monthIndex, newBeYear);
616
+ remaining = 0;
617
+ }
618
+ else {
619
+ remaining -= (daysLeftInMonth + 1);
620
+ const nextMonth = nextMonthOf(result.monthIndex, result.beYear);
621
+ const newBeYear = (result.monthIndex === MonthIndex.Cheit) ? result.beYear + 1 : result.beYear;
622
+ result = new KhmerDate(1, MoonPhase.Waxing, nextMonth, newBeYear); // Start at 1កើត
623
+ }
624
+ }
625
+ return result;
626
+ }
627
+ subtractDays(count) {
628
+ if (count === 0)
629
+ return this;
630
+ let result = new KhmerDate(this.day, this.moonPhase, this.monthIndex, this.beYear);
631
+ let remaining = count;
632
+ while (remaining > 0) {
633
+ const currentDayNum = result.getDayNumber();
634
+ if (remaining <= currentDayNum) {
635
+ const newDayNum = currentDayNum - remaining;
636
+ const newDay = KhmerDate.fromDayNumber(newDayNum);
637
+ let newBeYear = result.beYear;
638
+ if (result.monthIndex === MonthIndex.Pisakh) { // ពិសាខ
639
+ if (result.moonPhase === MoonPhase.Waning && newDay.moonPhase === MoonPhase.Waxing) {
640
+ newBeYear--;
641
+ }
642
+ }
643
+ result = new KhmerDate(newDay.day, newDay.moonPhase, result.monthIndex, newBeYear);
644
+ remaining = 0;
645
+ }
646
+ else {
647
+ remaining -= (currentDayNum + 1);
648
+ const prevMonth = previousMonthOf(result.monthIndex, result.beYear);
649
+ const newBeYear = (result.monthIndex === MonthIndex.Pisakh) ? result.beYear - 1 : result.beYear;
650
+ const daysInPrevMonth = getNumberOfDaysInKhmerMonth(prevMonth, newBeYear);
651
+ const newDay = KhmerDate.fromDayNumber(daysInPrevMonth - 1);
652
+ result = new KhmerDate(newDay.day, newDay.moonPhase, prevMonth, newBeYear);
653
+ }
654
+ }
655
+ return result;
656
+ }
657
+ toString() {
658
+ return `${this.day}${MoonStatusNames[this.moonPhase]} ខែ${LunarMonthNames[this.monthIndex]} ព.ស.${this.beYear}`;
659
+ }
660
+ }
661
+ // ============================================================================
662
+ // Main Conversion Functions
663
+ // ============================================================================
664
+ // Helper function to get approximate BE year (like original getMaybeBEYear)
665
+ function getMaybeBEYear(year, month) {
666
+ // SolarMonth['មេសា'] = 3 (0-based), so month <= 4 (1-based)
667
+ if (month <= 4) {
668
+ return year + 543;
669
+ }
670
+ else {
671
+ return year + 544;
672
+ }
673
+ }
674
+ // Cache for Pisakha Bochea dates by year
675
+ const visakhaBocheaCache = {};
676
+ // Cache for New Year Full Info
677
+ const newYearInfoCache = {};
678
+ /**
679
+ * Find BE Year transition datetime for a given Gregorian year
680
+ * BE year increases on ១រោច ខែពិសាខ (1st waning day of Pisakh = dayNumber 15 of month 5)
681
+ * Returns timestamp in milliseconds at midnight of that day
682
+ */
683
+ function getPisakhaBochea(year, isSearching = false) {
684
+ if (visakhaBocheaCache[year]) {
685
+ return visakhaBocheaCache[year];
686
+ }
687
+ // Search for 1រោច Pisakh (when BE year changes) - start from April since it typically occurs then
688
+ for (let searchMonth = 4; searchMonth <= 6; searchMonth++) {
689
+ const daysInMonth = new Date(year, searchMonth, 0).getDate();
690
+ for (let searchDay = 1; searchDay <= daysInMonth; searchDay++) {
691
+ // Avoid infinite recursion by using simplified BE year during search
692
+ const result = gregorianToKhmerInternal(year, searchMonth, searchDay, 12, 0, 0, true);
693
+ if (result.khmer.monthIndex === MonthIndex.Pisakh && result._khmerDateObj.getDayNumber() === 15) {
694
+ // Found 1រោច Pisakh - return timestamp at midnight (start of BE year change day)
695
+ // BE year changes at 00:00 on this day
696
+ const timestamp = new Date(year, searchMonth - 1, searchDay, 0, 0, 0, 0).getTime();
697
+ visakhaBocheaCache[year] = timestamp;
698
+ return timestamp;
699
+ }
700
+ }
701
+ }
702
+ // Fallback if not found
703
+ const fallback = new Date(year, 3, 15, 0, 0, 0, 0).getTime();
704
+ visakhaBocheaCache[year] = fallback;
705
+ return fallback;
706
+ }
707
+ function gregorianToKhmerInternal(year, month, day, hour = 0, minute = 0, second = 0, isSearching = false) {
708
+ /**
709
+ * This follows the original momentkh algorithm exactly using JDN for tracking
710
+ */
711
+ // Epoch: January 1, 1900 = dayNumber 0 (១កើត), month index 1 (បុស្ស)
712
+ let epochJdn = gregorianToJulianDay(1900, 1, 1);
713
+ const targetJdn = gregorianToJulianDay(year, month, day);
714
+ let khmerMonth = 1; // បុស្ស
715
+ let khmerDayNumber = 0; // 0-29 format
716
+ let diffDays = targetJdn - epochJdn;
717
+ // Move epoch by full Khmer years
718
+ if (diffDays > 0) {
719
+ while (true) {
720
+ // Get Gregorian date of current epoch to calculate BE year
721
+ const epochGreg = julianDayToGregorian(epochJdn);
722
+ // Match original: use epochMoment.clone().add(1, 'year')
723
+ const nextYearBE = getMaybeBEYear(epochGreg.year + 1, epochGreg.month);
724
+ const daysInNextYear = getNumberOfDaysInKhmerYear(nextYearBE);
725
+ if (diffDays > daysInNextYear) {
726
+ diffDays -= daysInNextYear;
727
+ epochJdn += daysInNextYear;
728
+ }
729
+ else {
730
+ break;
731
+ }
732
+ }
733
+ }
734
+ else if (diffDays < 0) {
735
+ while (diffDays < 0) {
736
+ const epochGreg = julianDayToGregorian(epochJdn);
737
+ const currentYearBE = getMaybeBEYear(epochGreg.year, epochGreg.month);
738
+ const daysInCurrentYear = getNumberOfDaysInKhmerYear(currentYearBE);
739
+ diffDays += daysInCurrentYear;
740
+ epochJdn -= daysInCurrentYear;
741
+ }
742
+ }
743
+ // Move epoch by full Khmer months
744
+ while (diffDays > 0) {
745
+ const epochGreg = julianDayToGregorian(epochJdn);
746
+ const currentBE = getMaybeBEYear(epochGreg.year, epochGreg.month);
747
+ const daysInMonth = getNumberOfDaysInKhmerMonth(khmerMonth, currentBE);
748
+ if (diffDays > daysInMonth) {
749
+ diffDays -= daysInMonth;
750
+ epochJdn += daysInMonth;
751
+ khmerMonth = nextMonthOf(khmerMonth, currentBE);
752
+ }
753
+ else {
754
+ break;
755
+ }
756
+ }
757
+ // Add remaining days
758
+ khmerDayNumber = diffDays;
759
+ // Fix overflow (e.g., if month has only 29 days but we calculated 30)
760
+ const finalBE = getMaybeBEYear(year, month);
761
+ const totalDaysInMonth = getNumberOfDaysInKhmerMonth(khmerMonth, finalBE);
762
+ if (khmerDayNumber >= totalDaysInMonth) {
763
+ khmerDayNumber = khmerDayNumber % totalDaysInMonth;
764
+ khmerMonth = nextMonthOf(khmerMonth, finalBE);
765
+ }
766
+ // Convert dayNumber to day/moonPhase format
767
+ const khmerDayInfo = KhmerDate.fromDayNumber(khmerDayNumber);
768
+ // Calculate actual BE year
769
+ // The BE year changes on ១រោច ខែពិសាខ (1st waning day of Pisakh = dayNumber 15)
770
+ // Compare datetime (including hour/minute) against BE year transition datetime
771
+ let beYear;
772
+ if (isSearching) {
773
+ // During search, use simple approximation to avoid recursion
774
+ beYear = month <= 4 ? year + 543 : year + 544;
775
+ }
776
+ else {
777
+ // Normal mode: compare against exact BE year transition datetime (1រោច Pisakh at 00:00)
778
+ const inputTimestamp = new Date(year, month - 1, day, hour, minute, second).getTime();
779
+ const beYearTransitionTimestamp = getPisakhaBochea(year);
780
+ if (inputTimestamp >= beYearTransitionTimestamp) {
781
+ // On or after 1រោច Pisakh (new BE year)
782
+ beYear = year + 544;
783
+ }
784
+ else {
785
+ // Before 1រោច Pisakh (old BE year)
786
+ beYear = year + 543;
787
+ }
788
+ }
789
+ // Calculate additional info
790
+ let jsYear = beToJs(beYear);
791
+ let animalYearIndex = ((beYear + 4) % 12 + 12) % 12;
792
+ // Adjust Era and Animal Year based on Khmer New Year logic
793
+ // They should change at New Year, not wait for Pisakha Bochea (which changes BE)
794
+ if (!isSearching) {
795
+ const newYearInfo = getNewYearFullInfo(year);
796
+ const inputTimestamp = new Date(year, month - 1, day, hour, minute, second).getTime();
797
+ const visakhaBocheaTimestamp = getPisakhaBochea(year);
798
+ // Animal Year changes at Moha Songkran (exact New Year time)
799
+ // Only apply manual increment if we are in the gap between New Year and Pisakha Bochea
800
+ // (After Pisakha Bochea, the BE year increments, so the formula based on BE automatically gives the new Animal Year)
801
+ if (inputTimestamp >= newYearInfo.newYearMoment.getTime() && inputTimestamp <= visakhaBocheaTimestamp) {
802
+ animalYearIndex = (animalYearIndex + 1) % 12;
803
+ }
804
+ // Era changes at Midnight of Date Lerng Sak (3rd or 4th day of NY)
805
+ if (inputTimestamp >= newYearInfo.lerngSakMoment.getTime() && inputTimestamp <= visakhaBocheaTimestamp) {
806
+ jsYear++;
807
+ }
808
+ }
809
+ const eraYearIndex = ((jsYear % 10) + 10) % 10;
810
+ const dayOfWeek = getDayOfWeek(year, month, day);
811
+ const khmerDate = new KhmerDate(khmerDayInfo.day, khmerDayInfo.moonPhase, khmerMonth, beYear);
812
+ return {
813
+ gregorian: { year, month, day, hour, minute, second, dayOfWeek },
814
+ khmer: {
815
+ day: khmerDayInfo.day,
816
+ moonPhase: khmerDayInfo.moonPhase,
817
+ moonPhaseName: MoonStatusNames[khmerDayInfo.moonPhase],
818
+ monthIndex: khmerMonth,
819
+ monthName: LunarMonthNames[khmerMonth],
820
+ beYear: beYear,
821
+ jsYear: jsYear,
822
+ animalYear: animalYearIndex,
823
+ animalYearName: AnimalYearNames[animalYearIndex],
824
+ eraYear: eraYearIndex,
825
+ eraYearName: EraYearNames[eraYearIndex],
826
+ dayOfWeek: dayOfWeek,
827
+ dayOfWeekName: WeekdayNames[dayOfWeek]
828
+ },
829
+ _khmerDateObj: khmerDate
830
+ };
831
+ }
832
+ function khmerToGregorian(day, moonPhase, monthIndex, beYear) {
833
+ // Validate input parameters
834
+ validateKhmerDate(day, moonPhase, monthIndex, beYear);
835
+ // Convert enums to numbers if needed
836
+ const moonPhaseNum = typeof moonPhase === 'number' ? moonPhase : moonPhase;
837
+ const monthIndexNum = typeof monthIndex === 'number' ? monthIndex : monthIndex;
838
+ // Convert BE year to approximate Gregorian year
839
+ const approxYear = beYear - 544;
840
+ // Search within a range around the approximate year
841
+ // Start from 2 years before to 2 years after to account for calendar differences
842
+ const startYear = approxYear - 2;
843
+ const endYear = approxYear + 2;
844
+ let candidates = [];
845
+ // Iterate through Gregorian dates to find all matches
846
+ for (let year = startYear; year <= endYear; year++) {
847
+ for (let month = 1; month <= 12; month++) {
848
+ const daysInMonth = getDaysInGregorianMonth(year, month);
849
+ for (let gDay = 1; gDay <= daysInMonth; gDay++) {
850
+ // For BE year transition day (1រោច Pisakh) and the day before (15កើត Pisakh),
851
+ // check multiple times during the day because BE year can change during this period
852
+ const isAroundBEYearChange = monthIndexNum === MonthIndex.Pisakh &&
853
+ ((day === 15 && moonPhaseNum === MoonPhase.Waxing) || (day === 1 && moonPhaseNum === MoonPhase.Waning));
854
+ const timesToCheck = isAroundBEYearChange
855
+ ? [0, 6, 12, 18, 23] // Check at different hours
856
+ : [0]; // Normal case: just check at midnight
857
+ for (const hour of timesToCheck) {
858
+ const khmerResult = gregorianToKhmerInternal(year, month, gDay, hour, 0, 0, false);
859
+ // Check if it matches our target
860
+ if (khmerResult.khmer.beYear === beYear &&
861
+ khmerResult.khmer.monthIndex === monthIndexNum &&
862
+ khmerResult.khmer.day === day &&
863
+ khmerResult.khmer.moonPhase === moonPhaseNum) {
864
+ candidates.push({ year, month, day: gDay });
865
+ break; // Found a match for this date, no need to check other times
866
+ }
867
+ }
868
+ }
869
+ }
870
+ }
871
+ if (candidates.length === 0) {
872
+ throw new Error(`Could not find Gregorian date for Khmer date: ${day} ${moonPhaseNum === MoonPhase.Waxing ? 'កើត' : 'រោច'} month ${monthIndexNum} BE ${beYear}`);
873
+ }
874
+ // If multiple candidates found, prefer closest to approximate year
875
+ if (candidates.length > 1) {
876
+ // First, try to filter by year distance
877
+ const minDistance = Math.min(...candidates.map(c => Math.abs(c.year - approxYear)));
878
+ const closestCandidates = candidates.filter(c => Math.abs(c.year - approxYear) === minDistance);
879
+ // If we have a unique closest candidate, return it
880
+ if (closestCandidates.length === 1) {
881
+ return closestCandidates[0];
882
+ }
883
+ // If there are ties, prefer the one that matches at noon
884
+ const noonMatches = closestCandidates.filter(c => {
885
+ const noonCheck = gregorianToKhmerInternal(c.year, c.month, c.day, 12, 0, 0, false);
886
+ return noonCheck.khmer.beYear === beYear &&
887
+ noonCheck.khmer.monthIndex === monthIndexNum &&
888
+ noonCheck.khmer.day === day &&
889
+ noonCheck.khmer.moonPhase === moonPhaseNum;
890
+ });
891
+ if (noonMatches.length > 0) {
892
+ return noonMatches[0];
893
+ }
894
+ // Fall back to first closest candidate
895
+ return closestCandidates[0];
896
+ }
897
+ return candidates[0];
898
+ }
899
+ function getNewYearFullInfo(ceYear) {
900
+ if (newYearInfoCache[ceYear]) {
901
+ return newYearInfoCache[ceYear];
902
+ }
903
+ // Calculate using the standard algorithm first to get necessary info (like angsar for numberNewYearDay)
904
+ const jsYear = adToJs(ceYear);
905
+ let newYearInfo = getNewYearInfo(jsYear);
906
+ // Get Lerng Sak info
907
+ let bodithey = getBoditheyJs(jsYear);
908
+ const isAthikameasPrev = isAdhikameas(jsYear - 1);
909
+ const isChantrathimeasPrev = isChantrathimeas(jsYear - 1);
910
+ if (isAthikameasPrev && isChantrathimeasPrev) {
911
+ bodithey = (bodithey + 1) % 30;
912
+ }
913
+ // lunar DateLerngSak
914
+ const lunarDateLerngSak = {
915
+ day: bodithey >= 6 ? bodithey - 1 : bodithey,
916
+ month: bodithey >= 6 ? 4 : 5 // ចេត្រ or ពិសាខ
917
+ };
918
+ // Number of new year days
919
+ const numberNewYearDay = newYearInfo.newYearsDaySotins[0].angsar === 0 ? 4 : 3;
920
+ // Use April 17 as epoch and work backwards
921
+ const epochLerngSakGreg = { year: ceYear, month: 4, day: 17 };
922
+ // IMPORTANT: prevent recursion by passing isSearching=true (or any flag that skips Era check)
923
+ // gregorianToKhmerInternal(..., isSearching=true) uses simplified BE calc and skips Era check
924
+ const khEpoch = gregorianToKhmerInternal(ceYear, 4, 17, 12, 0, 0, true)._khmerDateObj;
925
+ // Calculate difference
926
+ const diffFromEpoch = ((khEpoch.monthIndex - 4) * 29 + khEpoch.getDayNumber()) -
927
+ ((lunarDateLerngSak.month - 4) * 29 + lunarDateLerngSak.day);
928
+ // Calculate days to subtract
929
+ const daysToSubtract = diffFromEpoch + numberNewYearDay - 1;
930
+ // Calculate new year date (Moha Songkran)
931
+ const epochJdn = gregorianToJulianDay(epochLerngSakGreg.year, epochLerngSakGreg.month, epochLerngSakGreg.day);
932
+ let newYearJdn = epochJdn - daysToSubtract;
933
+ // Override with cache if available
934
+ if (khNewYearMoments[ceYear]) {
935
+ const [datePart, timePart] = khNewYearMoments[ceYear].split(' ');
936
+ const [d, m, y] = datePart.split('-').map(Number);
937
+ const [hr, min] = timePart.split(':').map(Number);
938
+ // Update newYearInfo time
939
+ newYearInfo.timeOfNewYear = { hour: hr, minute: min };
940
+ // Update JDN based on cached date
941
+ newYearJdn = gregorianToJulianDay(y, m, d);
942
+ }
943
+ const newYearDate = julianDayToGregorian(newYearJdn);
944
+ const newYearMoment = new Date(newYearDate.year, newYearDate.month - 1, newYearDate.day, newYearInfo.timeOfNewYear.hour, newYearInfo.timeOfNewYear.minute);
945
+ // Calculate Lerng Sak Date (Midnight)
946
+ // Lerng Sak is the last day of NY celebration.
947
+ // Jdn = newYearJdn + (numberNewYearDay - 1)
948
+ const lerngSakJdn = newYearJdn + numberNewYearDay - 1;
949
+ const lerngSakDate = julianDayToGregorian(lerngSakJdn);
950
+ const lerngSakMoment = new Date(lerngSakDate.year, lerngSakDate.month - 1, lerngSakDate.day, 0, 0, 0); // Midnight
951
+ const result = {
952
+ newYearMoment,
953
+ lerngSakMoment,
954
+ newYearInfo: {
955
+ year: newYearDate.year,
956
+ month: newYearDate.month,
957
+ day: newYearDate.day,
958
+ hour: newYearInfo.timeOfNewYear.hour,
959
+ minute: newYearInfo.timeOfNewYear.minute
960
+ }
961
+ };
962
+ newYearInfoCache[ceYear] = result;
963
+ return result;
964
+ }
965
+ function getKhmerNewYear(ceYear) {
966
+ const info = getNewYearFullInfo(ceYear);
967
+ return info.newYearInfo;
968
+ }
969
+ // ============================================================================
970
+ // Formatting Functions
971
+ // ============================================================================
972
+ function formatKhmer(khmerData, formatString) {
973
+ if (!formatString) {
974
+ // Default format
975
+ const { khmer } = khmerData;
976
+ const moonDay = `${khmer.day}${khmer.moonPhaseName}`;
977
+ return toKhmerNumeral(`ថ្ងៃ${khmer.dayOfWeekName} ${moonDay} ខែ${khmer.monthName} ឆ្នាំ${khmer.animalYearName} ${khmer.eraYearName} ពុទ្ធសករាជ ${khmer.beYear}`);
978
+ }
979
+ // Custom format
980
+ const formatRules = {
981
+ 'W': () => khmerData.khmer.dayOfWeekName,
982
+ 'w': () => WeekdayNamesShort[khmerData.gregorian.dayOfWeek],
983
+ 'd': () => khmerData.khmer.day,
984
+ 'D': () => (khmerData.khmer.day < 10 ? '0' : '') + khmerData.khmer.day,
985
+ 'n': () => MoonStatusShort[khmerData.khmer.moonPhase],
986
+ 'N': () => khmerData.khmer.moonPhaseName,
987
+ 'o': () => MoonDaySymbols[khmerData._khmerDateObj.getDayNumber()],
988
+ 'm': () => khmerData.khmer.monthName,
989
+ 'M': () => SolarMonthNames[khmerData.gregorian.month - 1],
990
+ 'a': () => khmerData.khmer.animalYearName,
991
+ 'e': () => khmerData.khmer.eraYearName,
992
+ 'b': () => khmerData.khmer.beYear,
993
+ 'c': () => khmerData.gregorian.year,
994
+ 'j': () => khmerData.khmer.jsYear
995
+ };
996
+ const regex = new RegExp(Object.keys(formatRules).join('|'), 'g');
997
+ const result = formatString.replace(regex, match => {
998
+ const value = formatRules[match]();
999
+ return toKhmerNumeral(String(value));
1000
+ });
1001
+ return result;
1002
+ }
1003
+ // ============================================================================
1004
+ // Wrapper function for public API
1005
+ function gregorianToKhmer(year, month, day, hour = 0, minute = 0, second = 0) {
1006
+ // Validate input parameters
1007
+ validateGregorianDate(year, month, day, hour, minute, second);
1008
+ return gregorianToKhmerInternal(year, month, day, hour, minute, second, false);
1009
+ }
1010
+ // ============================================================================
1011
+ // Public API
1012
+ // ============================================================================
1013
+ // Conversion functions
1014
+ function fromGregorian(year, month, day, hour = 0, minute = 0, second = 0) {
1015
+ return gregorianToKhmer(year, month, day, hour, minute, second);
1016
+ }
1017
+ function fromKhmer(day, moonPhase, monthIndex, beYear) {
1018
+ return khmerToGregorian(day, moonPhase, monthIndex, beYear);
1019
+ }
1020
+ // New Year function
1021
+ function getNewYear(ceYear) {
1022
+ return getKhmerNewYear(ceYear);
1023
+ }
1024
+ // Format function
1025
+ function format(khmerData, formatString) {
1026
+ return formatKhmer(khmerData, formatString);
1027
+ }
1028
+ // Utility for creating date from Date object
1029
+ function fromDate(date) {
1030
+ // Validate Date object
1031
+ validateDateObject(date);
1032
+ return gregorianToKhmer(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
1033
+ }
1034
+ // Convert Khmer to Date object
1035
+ function toDate(day, moonPhase, monthIndex, beYear) {
1036
+ const greg = khmerToGregorian(day, moonPhase, monthIndex, beYear);
1037
+ return new Date(greg.year, greg.month - 1, greg.day);
1038
+ }
1039
+ // Constants export
1040
+ exports.constants = {
1041
+ LunarMonths,
1042
+ LunarMonthNames,
1043
+ SolarMonthNames,
1044
+ AnimalYearNames,
1045
+ EraYearNames,
1046
+ WeekdayNames,
1047
+ MoonStatusNames
1048
+ };
1049
+ // Default export - aggregate all exports for convenience
1050
+ exports.default = {
1051
+ fromGregorian,
1052
+ fromKhmer,
1053
+ getNewYear,
1054
+ format,
1055
+ fromDate,
1056
+ toDate,
1057
+ constants: exports.constants,
1058
+ MoonPhase,
1059
+ MonthIndex,
1060
+ AnimalYear,
1061
+ EraYear,
1062
+ DayOfWeek
1063
+ };