@thyrith/momentkh 3.0.0 → 3.0.2

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