File size: 4,895 Bytes
5241269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
 * Fusion shows and takes dates in the signed-in user's own format (their preferences): one pod's user types
 * 14.11.2026, another's 11/14/26. Nothing may assume one. A date is written in the format this run has learned,
 * FUSION_DATE_FORMAT when the pod registration sets it, else dd.MM.yyyy until the page shows otherwise.
 * When Fusion refuses a date, the format is read from the field's own hint ("Example: 11/16/26"), then from the dates
 * Fusion shows on the page (Terms Date and the like), and else the common formats are tried in turn; the first one
 * Fusion accepts is kept for the rest of the run (ui.ts put()).
 */

export const DATE_FORMATS = ['dd.MM.yyyy', 'M/d/yy', 'MM/dd/yyyy', 'M/d/yyyy', 'dd/MM/yyyy', 'd/M/yy', 'dd-MMM-yyyy',
  'dd-MMM-yy', 'yyyy-MM-dd', 'dd-MM-yyyy', 'yyyy/MM/dd'] as const;
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

let current: string = process.env.FUSION_DATE_FORMAT || 'dd.MM.yyyy';
export const dateFormat = () => current;
export const setDateFormat = (f: string) => { current = f; };

const pad = (n: number) => String(n).padStart(2, '0');

/** The UTC calendar day of `d` in `fmt` (tokens yyyy yy MMM MM M dd d). */
export function formatDate(d: Date, fmt = current): string {
  return fmt.replace(/yyyy|yy|MMM|MM|M|dd|d/g, (t) => ({
    yyyy: String(d.getUTCFullYear()), yy: pad(d.getUTCFullYear() % 100), MMM: MON[d.getUTCMonth()], MM: pad(d.getUTCMonth() + 1),
    M: String(d.getUTCMonth() + 1), dd: pad(d.getUTCDate()), d: String(d.getUTCDate()),
  }[t] as string));
}

/** `s` read in `fmt` as a UTC date, or null when it does not fit. */
export function parseDate(s: string, fmt: string): Date | null {
  const order: string[] = [];
  const re = new RegExp('^' + fmt.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&').replace(/yyyy|yy|MMM|MM|M|dd|d/g, (t) => {
    order.push(t);
    return t === 'MMM' ? '([A-Za-z]{3})' : t === 'yyyy' ? '(\\d{4})' : t.length === 2 ? '(\\d{2})' : '(\\d{1,2})';
  }) + '$');
  const m = re.exec(s.trim());
  if (!m) return null;
  let y = 0, mo = 0, day = 0;
  order.forEach((t, i) => {
    const v = m[i + 1];
    if (t === 'yyyy') y = Number(v);
    else if (t === 'yy') y = 2000 + Number(v);
    else if (t === 'MMM') mo = MON.findIndex((x) => x.toLowerCase() === v.toLowerCase()) + 1;
    else if (t === 'MM' || t === 'M') mo = Number(v);
    else day = Number(v);
  });
  if (mo < 1 || mo > 12 || day < 1 || day > 31) return null;
  const d = new Date(Date.UTC(y, mo - 1, day));
  return d.getUTCDate() === day ? d : null;
}

/** The format of dates Fusion shows (`seen`): the one that reads every value as a real date, and when several do
 *  (11/10/26 fits M/d/yy and d/M/yy), the one whose dates lie closest to `today`. Null when nothing looks like a date. */
export function inferDateFormat(seen: string[], today = new Date()): string | null {
  const vals = seen.map((s) => s.trim()).filter((s) => /^[\dA-Za-z]{1,4}[./-][\dA-Za-z]{1,4}[./-][\d]{2,4}$/.test(s));
  if (!vals.length) return null;
  let best: { f: string; dist: number } | null = null;
  for (const f of DATE_FORMATS) {
    const ds = vals.map((v) => parseDate(v, f));
    if (ds.some((d) => !d)) continue;
    const dist = Math.min(...ds.map((d) => Math.abs((d as Date).getTime() - today.getTime())));
    if (!best || dist < best.dist) best = { f, dist };
  }
  return best?.f ?? null;
}

/** The format a date field tells the user it wants, from its hint text: an example date ("Example: 11/16/26") or a
 *  pattern ("m/d/yy", "dd-mmm-yyyy"). Null when the hint shows neither. */
export function formatFromHint(hint: string, today = new Date()): string | null {
  const text = (hint || '').trim();
  if (!text) return null;
  const examples = text.match(/\b[\dA-Za-z]{1,4}[./-][\dA-Za-z]{1,4}[./-]\d{2,4}\b/g) || [];
  const fromExample = inferDateFormat(examples.filter((s) => /\d/.test(s.slice(0, 2)) || /^[A-Za-z]{3}/.test(s.split(/[./-]/)[1] || '')), today);
  if (fromExample) return fromExample;
  const pattern = (text.match(/\b(?:d{1,2}|m{1,3}|y{2,4})[./-](?:d{1,2}|m{1,3}|y{2,4})[./-](?:d{1,2}|m{1,3}|y{2,4})\b/i) || [])[0];
  if (!pattern) return null;
  const norm = pattern.toLowerCase().replace(/mmm|mm|m/g, (t) => t.toUpperCase());
  return (DATE_FORMATS as readonly string[]).find((f) => f === norm) ?? null;
}

/** The formats to try, in order, when Fusion refused a date and nothing on the page says which one it wants: the
 *  common Fusion user preferences first. */
export const FALLBACK_FORMATS = ['M/d/yy', 'MM/dd/yyyy', 'dd-MMM-yyyy', 'dd/MM/yyyy', 'yyyy-MM-dd', 'dd.MM.yyyy', 'M/d/yyyy', 'dd-MMM-yy'];

/** `value` (written in `from`) rewritten in `to`; unchanged when it is not a date in `from`. */
export function reformat(value: string, from: string, to: string): string {
  const d = parseDate(value, from);
  return d ? formatDate(d, to) : value;
}