lecodes-cli 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,331 @@
1
+ // Locale-aware dates, dayjs-style: `date(value).format(...)`. Pure JS (no `Intl` — QuickJS hosts
2
+ // don't ship it reliably), so output is byte-identical on every platform. Two locales: English and
3
+ // Russian.
4
+ //
5
+ // ── Designed for chisel fusion ──────────────────────────────────────────────────────────────────
6
+ // A date is a *single-scalar* value (epoch milliseconds), which is the 1-component analog of a Vec3
7
+ // chain. The wrapper is written so a future chisel date-fuser can lower `date(root).<chain>()` to
8
+ // scalar ms arithmetic and drop the wrapper allocation, the same way Vec3 chains fuse:
9
+ // • IMMUTABLE — every method returns a NEW `DateValue`, never mutates `t` (aliasing safety).
10
+ // • ONE canonical scalar — `t` (epoch ms), also reachable via `valueOf()`; that's the "component".
11
+ // • Terminals DELEGATE to the module-private free functions `formatImpl` / `timeAgoImpl`, taking
12
+ // `(ms, …)`. So `date(x).format(p)` can fuse to `formatImpl(toMs(x), p)` with no wrapper.
13
+ // • Linear-unit arithmetic (ms…week) is closed-form scalar math → fusable; calendar units
14
+ // (month/year) and local-tz `startOf`/`endOf` use `Date` and are left to the real method.
15
+ // Even before that pass lands, each method is a class method, so chisel's method-granular DCE drops
16
+ // whichever ones a project doesn't use.
17
+
18
+ export type Locale = "en" | "ru"
19
+ export type DateInput = Date | number | string | DateValue
20
+ export type Unit = "ms" | "second" | "minute" | "hour" | "day" | "week" | "month" | "year"
21
+
22
+ // ---- locale data -------------------------------------------------------------------------------
23
+ // Russian needs the month in two grammatical cases: genitive ("5 сентября") when a day number is
24
+ // present, nominative ("Сентябрь 2024") when it stands alone. `format` picks by whether the pattern
25
+ // contains a day (`D`) token — the same rule day.js's ru locale uses.
26
+
27
+ type LocaleData = {
28
+ months: readonly string[]
29
+ monthsGenitive: readonly string[]
30
+ monthsShort: readonly string[]
31
+ weekdays: readonly string[] // Sunday..Saturday (JS getDay() order)
32
+ weekdaysShort: readonly string[]
33
+ am: string
34
+ pm: string
35
+ }
36
+
37
+ const EN: LocaleData = {
38
+ months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
39
+ monthsGenitive: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
40
+ monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
41
+ weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
42
+ weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
43
+ am: "AM",
44
+ pm: "PM",
45
+ }
46
+
47
+ const RU: LocaleData = {
48
+ months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
49
+ monthsGenitive: ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"],
50
+ monthsShort: ["янв", "фев", "мар", "апр", "мая", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"],
51
+ weekdays: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"],
52
+ weekdaysShort: ["вс", "пн", "вт", "ср", "чт", "пт", "сб"],
53
+ am: "AM",
54
+ pm: "PM",
55
+ }
56
+
57
+ const DATA: Record<Locale, LocaleData> = { en: EN, ru: RU }
58
+
59
+ const resolveLocale = (locale?: Locale): Locale => {
60
+ if (locale) return locale === "ru" ? "ru" : "en"
61
+ const lang = typeof _creatorUtils !== "undefined" ? _creatorUtils.language : ""
62
+ return lang && lang.toLowerCase().indexOf("ru") === 0 ? "ru" : "en"
63
+ }
64
+
65
+ // Milliseconds per linear unit. Absent keys (month/year) mark the non-fusable calendar units.
66
+ const MS: Partial<Record<Unit, number>> = {
67
+ ms: 1,
68
+ second: 1000,
69
+ minute: 60_000,
70
+ hour: 3_600_000,
71
+ day: 86_400_000,
72
+ week: 604_800_000,
73
+ }
74
+
75
+ const toMs = (value: DateInput): number => {
76
+ if (value instanceof DateValue) return value.t
77
+ if (value instanceof Date) return value.getTime()
78
+ if (typeof value === "number") return value
79
+ return new Date(value).getTime()
80
+ }
81
+
82
+ // ---- formatting (the fusion escape target: takes a scalar ms, holds the heavy tables) -----------
83
+
84
+ const pad2 = (n: number): string => (n < 10 ? "0" + n : "" + n)
85
+
86
+ // Longest tokens first so `MMMM` matches before `MM`, `YYYY` before `YY`, etc.
87
+ const TOKEN = /YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|A|a/g
88
+
89
+ const formatImpl = (ms: number, pattern: string, locale?: Locale): string => {
90
+ const d = new Date(ms)
91
+ const L = DATA[resolveLocale(locale)]
92
+ const hasDay = /D/.test(pattern) // genitive month only when a day number accompanies it
93
+ const months = hasDay ? L.monthsGenitive : L.months
94
+
95
+ const year = d.getFullYear()
96
+ const month = d.getMonth()
97
+ const day = d.getDate()
98
+ const weekday = d.getDay()
99
+ const hours = d.getHours()
100
+ const hour12 = hours % 12 || 12
101
+ const minutes = d.getMinutes()
102
+ const seconds = d.getSeconds()
103
+
104
+ return pattern.replace(TOKEN, (t) => {
105
+ switch (t) {
106
+ case "YYYY": return "" + year
107
+ case "YY": return pad2(year % 100)
108
+ case "MMMM": return months[month]
109
+ case "MMM": return L.monthsShort[month]
110
+ case "MM": return pad2(month + 1)
111
+ case "M": return "" + (month + 1)
112
+ case "DD": return pad2(day)
113
+ case "D": return "" + day
114
+ case "dddd": return L.weekdays[weekday]
115
+ case "ddd": return L.weekdaysShort[weekday]
116
+ case "HH": return pad2(hours)
117
+ case "H": return "" + hours
118
+ case "hh": return pad2(hour12)
119
+ case "h": return "" + hour12
120
+ case "mm": return pad2(minutes)
121
+ case "m": return "" + minutes
122
+ case "ss": return pad2(seconds)
123
+ case "s": return "" + seconds
124
+ case "A": return hours < 12 ? L.am : L.pm
125
+ case "a": return (hours < 12 ? L.am : L.pm).toLowerCase()
126
+ default: return t
127
+ }
128
+ })
129
+ }
130
+
131
+ // Russian plural picks one of three forms by the number: 1 минута / 2 минуты / 5 минут.
132
+ const ruPlural = (n: number, one: string, few: string, many: string): string => {
133
+ const mod10 = n % 10
134
+ const mod100 = n % 100
135
+ if (mod10 === 1 && mod100 !== 11) return one
136
+ if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return few
137
+ return many
138
+ }
139
+
140
+ type RelUnit = { limit: number; secs: number; en: [string, string]; ru: [string, string, string] }
141
+
142
+ // Ordered thresholds. `limit` is the upper bound (in seconds) this unit covers; `secs` is the unit's
143
+ // length used to compute the count.
144
+ const REL_UNITS: readonly RelUnit[] = [
145
+ { limit: 60, secs: 1, en: ["second", "seconds"], ru: ["секунду", "секунды", "секунд"] },
146
+ { limit: 3600, secs: 60, en: ["minute", "minutes"], ru: ["минуту", "минуты", "минут"] },
147
+ { limit: 86400, secs: 3600, en: ["hour", "hours"], ru: ["час", "часа", "часов"] },
148
+ { limit: 2592000, secs: 86400, en: ["day", "days"], ru: ["день", "дня", "дней"] },
149
+ { limit: 31536000, secs: 2592000, en: ["month", "months"], ru: ["месяц", "месяца", "месяцев"] },
150
+ { limit: Infinity, secs: 31536000, en: ["year", "years"], ru: ["год", "года", "лет"] },
151
+ ]
152
+
153
+ const timeAgoImpl = (ms: number, locale: Locale | undefined, nowMs: number): string => {
154
+ const loc = resolveLocale(locale)
155
+ const diffSecs = (nowMs - ms) / 1000
156
+ const future = diffSecs < 0
157
+ const abs = Math.abs(diffSecs)
158
+
159
+ if (abs < 45) return loc === "ru" ? "только что" : "just now"
160
+
161
+ let count = 1
162
+ let unit = REL_UNITS[REL_UNITS.length - 1]
163
+ for (const u of REL_UNITS) {
164
+ if (abs < u.limit) { unit = u; count = Math.max(1, Math.round(abs / u.secs)); break }
165
+ }
166
+
167
+ if (loc === "ru") {
168
+ const word = ruPlural(count, unit.ru[0], unit.ru[1], unit.ru[2])
169
+ return future ? `через ${count} ${word}` : `${count} ${word} назад`
170
+ }
171
+ const word = count === 1 ? unit.en[0] : unit.en[1]
172
+ return future ? `in ${count} ${word}` : `${count} ${word} ago`
173
+ }
174
+
175
+ // ---- the immutable wrapper ---------------------------------------------------------------------
176
+
177
+ /**
178
+ * An immutable moment in time — the value returned by [`date()`]. Wraps a single epoch-millisecond
179
+ * scalar (`t`); every method returns a new `DateValue` or a plain scalar, never mutating. Construct
180
+ * it with `date(...)`, not `new`.
181
+ */
182
+ export class DateValue {
183
+ /** Epoch milliseconds — the one canonical scalar. Prefer `valueOf()`; this is public so `date(a)`
184
+ * can read it back cheaply and so tooling can treat it as the value's single component. */
185
+ readonly t: number
186
+
187
+ constructor(ms: number) {
188
+ this.t = ms
189
+ }
190
+
191
+ // -- materialize (delegate to the free functions; the fuser can inline these to `*Impl(t, …)`) --
192
+
193
+ /**
194
+ * Format against a `day.js`-style token pattern (default `"D MMMM YYYY"`). Locale defaults to the
195
+ * current device language.
196
+ *
197
+ * Tokens: `YYYY`/`YY` year · `MMMM`/`MMM`/`MM`/`M` month · `DD`/`D` day · `dddd`/`ddd` weekday ·
198
+ * `HH`/`H` 24-hour · `hh`/`h` 12-hour · `mm`/`m` minute · `ss`/`s` second · `A`/`a` AM/PM.
199
+ *
200
+ * ```ts
201
+ * date().format() // "10 July 2026" / "10 июля 2026"
202
+ * date(ts).format("DD.MM.YYYY HH:mm") // "10.07.2026 14:05"
203
+ * date(ts).format("MMMM YYYY", "ru") // "Июль 2026" (nominative — no day token)
204
+ * ```
205
+ */
206
+ format(pattern = "D MMMM YYYY", locale?: Locale): string {
207
+ return formatImpl(this.t, pattern, locale)
208
+ }
209
+
210
+ /**
211
+ * Human relative time vs `now` (default: the current time) — "5 minutes ago", "in 2 days",
212
+ * "5 минут назад", "через 2 дня". Reads as "just now" under ~45 seconds; handles Russian number
213
+ * agreement (`1 минуту` / `2 минуты` / `5 минут`). Locale defaults to the device language.
214
+ */
215
+ timeAgo(locale?: Locale, now: DateInput = Date.now()): string {
216
+ return timeAgoImpl(this.t, locale, toMs(now))
217
+ }
218
+
219
+ // -- arithmetic (pure, chainable; linear units are closed-form scalar math → fusable) -----------
220
+
221
+ /** Add `n` of a unit, returning a new value. Linear units (`ms`…`week`) are scalar ms math;
222
+ * `month`/`year` are calendar-aware (clamp on short months, like day.js). */
223
+ add(n: number, unit: Unit): DateValue {
224
+ const ms = MS[unit]
225
+ if (ms !== undefined) return new DateValue(this.t + n * ms)
226
+ // Calendar units: shift month/year but clamp the day so Jan 31 + 1 month → Feb 28 (not Mar 3).
227
+ const d = new Date(this.t)
228
+ const day = d.getDate()
229
+ d.setDate(1)
230
+ if (unit === "year") d.setFullYear(d.getFullYear() + n)
231
+ else d.setMonth(d.getMonth() + n) // "month"
232
+ const daysInMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()
233
+ d.setDate(Math.min(day, daysInMonth))
234
+ return new DateValue(d.getTime())
235
+ }
236
+
237
+ /** Subtract `n` of a unit. Equivalent to `add(-n, unit)`. */
238
+ subtract(n: number, unit: Unit): DateValue {
239
+ return this.add(-n, unit)
240
+ }
241
+
242
+ /** Snap down to the start of a unit (local time): start of day/hour/month/year, etc. */
243
+ startOf(unit: Unit): DateValue {
244
+ const d = new Date(this.t)
245
+ switch (unit) {
246
+ case "year": d.setMonth(0)
247
+ // falls through
248
+ case "month": d.setDate(1)
249
+ // falls through
250
+ case "day": d.setHours(0, 0, 0, 0); break
251
+ case "hour": d.setMinutes(0, 0, 0); break
252
+ case "minute": d.setSeconds(0, 0); break
253
+ case "second": d.setMilliseconds(0); break
254
+ case "week": {
255
+ d.setHours(0, 0, 0, 0)
256
+ d.setDate(d.getDate() - d.getDay()) // week starts Sunday
257
+ break
258
+ }
259
+ }
260
+ return new DateValue(d.getTime())
261
+ }
262
+
263
+ /** Snap up to the end of a unit (local time): the last millisecond of the day/hour/month/… */
264
+ endOf(unit: Unit): DateValue {
265
+ return this.startOf(unit).add(1, unit).add(-1, "ms")
266
+ }
267
+
268
+ // -- scalar terminals (bare number / boolean → allocate nothing when fused) ---------------------
269
+
270
+ /** Epoch milliseconds. Enables `+date(x)`, `date(a) < date(b)`, `date(a) - date(b)` via coercion. */
271
+ valueOf(): number {
272
+ return this.t
273
+ }
274
+
275
+ /** Whole seconds since the epoch (Unix time). */
276
+ unix(): number {
277
+ return Math.floor(this.t / 1000)
278
+ }
279
+
280
+ /** Signed difference to `other`, in whole `unit`s (default `ms`), truncated toward zero. */
281
+ diff(other: DateInput, unit: Unit = "ms"): number {
282
+ const raw = this.t - toMs(other)
283
+ const per = MS[unit]
284
+ if (per !== undefined) return Math.trunc(raw / per)
285
+ // month/year: count calendar steps.
286
+ const a = new Date(this.t)
287
+ const b = new Date(toMs(other))
288
+ let months = (a.getFullYear() - b.getFullYear()) * 12 + (a.getMonth() - b.getMonth())
289
+ if (a.getDate() < b.getDate()) months -= Math.sign(months) || 0
290
+ return unit === "year" ? Math.trunc(months / 12) : months
291
+ }
292
+
293
+ isBefore(other: DateInput): boolean { return this.t < toMs(other) }
294
+ isAfter(other: DateInput): boolean { return this.t > toMs(other) }
295
+ isSame(other: DateInput): boolean { return this.t === toMs(other) }
296
+
297
+ // -- field accessors (scalar terminals) ---------------------------------------------------------
298
+
299
+ year(): number { return new Date(this.t).getFullYear() }
300
+ /** 0-based month (0 = January), matching `Date.getMonth`. */
301
+ month(): number { return new Date(this.t).getMonth() }
302
+ /** Day of the month, 1–31. */
303
+ day(): number { return new Date(this.t).getDate() }
304
+ /** Day of the week, 0 (Sunday)–6 (Saturday), matching `Date.getDay`. */
305
+ weekday(): number { return new Date(this.t).getDay() }
306
+ hour(): number { return new Date(this.t).getHours() }
307
+ minute(): number { return new Date(this.t).getMinutes() }
308
+ second(): number { return new Date(this.t).getSeconds() }
309
+
310
+ /** A native `Date` snapshot of this value. */
311
+ toDate(): Date {
312
+ return new Date(this.t)
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Create a `DateValue` — a locale-aware, immutable moment, dayjs-style. Accepts a `Date`, a
318
+ * millisecond timestamp (`Date.now()`), a parseable string, or another `DateValue`; with no argument
319
+ * it's the current time. Chain arithmetic and finish with `format` / `timeAgo`, both of which
320
+ * understand **English** and **Russian** and default to the current device language
321
+ * ([`device.language`](../runtime/device.ts)).
322
+ *
323
+ * ```ts
324
+ * date().format("dddd, D MMMM") // "Friday, 10 July" / "пятница, 10 июля"
325
+ * date(ts).timeAgo() // "5 minutes ago" / "5 минут назад"
326
+ * date().add(3, "day").startOf("day").format("D MMMM")
327
+ * date(a).diff(b, "hour") // signed whole hours
328
+ * date(a).isBefore(b) // boolean
329
+ * ```
330
+ */
331
+ export const date = (value: DateInput = Date.now()): DateValue => new DateValue(toMs(value))