@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
469 lines (467 loc) • 14.1 kB
JavaScript
import { resolveLocale } from "./resolveLocale.js";
import { twoDigitYear } from "./twoDigitYear.js";
import { readYearWindowStart } from "./yearWindowStart.js";
import { getLocaleEraNames } from "../plain/locale/getLocaleEraNames.js";
import { getLocaleMeridiems } from "../plain/locale/getLocaleMeridiems.js";
import { localeMonthNames } from "./localeMonthNames.js";
import { getLocaleWeekdayNames } from "../plain/locale/getLocaleWeekdayNames.js";
// src/internal/patternToken.ts
/** Fields accepted by `parseDateWithPattern` — date-shaped tokens only. */
const DATE_PATTERN_FIELDS = /* @__PURE__ */ new Set([
"year",
"month",
"day",
"weekday",
"era"
]);
/** Fields accepted by `parseTimeWithPattern` — time-shaped tokens only. */
const TIME_PATTERN_FIELDS = /* @__PURE__ */ new Set([
"hour",
"minute",
"second",
"millisecond",
"meridiem"
]);
/** Fields accepted by `parseDateTimeWithPattern` — the full combined set. */
const DATE_TIME_PATTERN_FIELDS = /* @__PURE__ */ new Set([...DATE_PATTERN_FIELDS, ...TIME_PATTERN_FIELDS]);
/**
* Fields accepted by `parseMonthDayWithPattern`: the month and the day.
*
* There is no year, weekday or era. A weekday and an era have no meaning without a year
* (Temporal `PlainMonthDay` keeps only a month, a day and a calendar), and a time field has
* no place in a month-day.
*/
const MONTH_DAY_PATTERN_FIELDS = /* @__PURE__ */ new Set(["month", "day"]);
/**
* Fields accepted by `parseYearMonthWithPattern`: the year, the month and the era.
*
* No day, weekday or time: Temporal `PlainYearMonth` keeps a year, a month and a calendar. An era
* is kept because it qualifies the year (`GG` with BC gives year `1 - y`, as the date parser does).
*/
const YEAR_MONTH_PATTERN_FIELDS = /* @__PURE__ */ new Set([
"year",
"month",
"era"
]);
const TOKEN_TABLE = {
y4: {
field: "year",
kind: "yearFull",
regexSource: "\\d{4}"
},
y2: {
field: "year",
kind: "yearShort",
regexSource: "\\d{2}"
},
M2: {
field: "month",
kind: "monthNumber",
regexSource: "(?:0[1-9]|1[0-2])"
},
M1: {
field: "month",
kind: "monthNumber",
regexSource: "(?:0?[1-9]|1[0-2])"
},
M3: {
field: "month",
kind: "monthNameShort"
},
M4: {
field: "month",
kind: "monthNameLong"
},
L2: {
field: "month",
kind: "monthNumber",
regexSource: "(?:0[1-9]|1[0-2])"
},
L1: {
field: "month",
kind: "monthNumber",
regexSource: "(?:0?[1-9]|1[0-2])"
},
L3: {
field: "month",
kind: "monthNameShort"
},
L4: {
field: "month",
kind: "monthNameLong"
},
d2: {
field: "day",
kind: "day",
regexSource: "(?:0[1-9]|[12]\\d|3[01])"
},
d1: {
field: "day",
kind: "day",
regexSource: "(?:0?[1-9]|[12]\\d|3[01])"
},
H2: {
field: "hour",
kind: "hour24",
regexSource: "(?:[01]\\d|2[0-3])"
},
H1: {
field: "hour",
kind: "hour24",
regexSource: "(?:[01]?\\d|2[0-3])"
},
h2: {
field: "hour",
kind: "hour12",
regexSource: "(?:0[1-9]|1[0-2])"
},
h1: {
field: "hour",
kind: "hour12",
regexSource: "(?:0?[1-9]|1[0-2])"
},
m2: {
field: "minute",
kind: "minute",
regexSource: "[0-5]\\d"
},
m1: {
field: "minute",
kind: "minute",
regexSource: "(?:[0-5]?\\d)"
},
s2: {
field: "second",
kind: "second",
regexSource: "[0-5]\\d"
},
s1: {
field: "second",
kind: "second",
regexSource: "(?:[0-5]?\\d)"
},
S3: {
field: "millisecond",
kind: "millisecond",
regexSource: "\\d{3}"
},
E3: {
field: "weekday",
kind: "weekdayShort"
},
E4: {
field: "weekday",
kind: "weekdayLong"
},
a1: {
field: "meridiem",
kind: "meridiem"
},
G2: {
field: "era",
kind: "eraShort"
},
G4: {
field: "era",
kind: "eraLong"
}
};
const VOCABULARY_LETTERS = "yMLdHhmsSEaG";
/**
* Split a pattern string into literal and letter-run parts.
*
* Literal text follows UTS #35 Part 4, Date Format Patterns
* (https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns):
* - "Any characters other than A..Z and a..z, including spaces and
* punctuation" are literals with no quoting.
* - "Any text between single vertical quotes ('xxxx'), which may include
* A..Z and a..z as literal text."
* - "Two adjacent single vertical quotes (''), which represent a literal
* single quote, either inside or outside quoted text."
*
* The pattern is read left to right, so a `''` pair is taken before a
* lone `'` is read as opening or closing quoted text: `''''` is two
* literal quotes, and `'''T'` is a literal quote followed by the quoted
* text `T`. UTS #35 defines quoted text only as text *between* two
* quotes, so a quote that never closes has no defined meaning and the
* pattern is malformed (`null`).
*/
function tokenizePattern(pattern) {
const parts = [];
let i = 0;
while (i < pattern.length) {
const ch = pattern[i];
if (ch === "'") {
if (pattern[i + 1] === "'") {
parts.push({
type: "literal",
text: "'"
});
i += 2;
continue;
}
let j = i + 1;
let text = "";
let closed = false;
while (j < pattern.length) {
if (pattern[j] === "'") {
if (pattern[j + 1] === "'") {
text += "'";
j += 2;
continue;
}
j += 1;
closed = true;
break;
}
text += pattern[j];
j += 1;
}
if (!closed) return null;
parts.push({
type: "literal",
text
});
i = j;
continue;
}
if (/[a-zA-Z]/.test(ch)) {
let j = i;
while (j < pattern.length && pattern[j] === ch) j++;
parts.push({
type: "token",
letter: ch,
length: j - i
});
i = j;
continue;
}
parts.push({
type: "literal",
text: ch
});
i++;
}
return parts;
}
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Build a case-insensitive alternation from a locale's name list.
*
* Names are sorted by descending length before joining with `|` so a
* longer name is tried before a shorter one that happens to be its
* prefix (e.g. a locale where a short-form weekday name is a strict
* prefix of a longer name) — otherwise the regex engine's left-to-right
* alternation would greedily commit to the shorter match and never
* backtrack into the longer one.
*/
function buildNameAlternation(names) {
return [...names].sort((a, b) => b.length - a.length).map((name) => escapeRegExp(name)).join("|");
}
/**
* Compile a token pattern into an anchored `RegExp` plus the metadata
* needed to resolve each capture back to a field value.
*
* Returns `null` for any malformed pattern: an unquoted letter outside
* the recognized vocabulary, a recognized letter repeated to an
* unsupported width, a field appearing more than once, a field outside
* `allowedFields` (e.g. a time token handed to the date-only parser), an
* unterminated quote, or (for a locale-aware token) a locale that
* `Intl.Locale` cannot resolve.
*/
function compilePattern(pattern, allowedFields, locale) {
const parts = tokenizePattern(pattern);
if (parts === null) return null;
const usedFields = /* @__PURE__ */ new Set();
const tokens = [];
const regexPieces = [];
let groupCounter = 0;
for (const part of parts) {
if (part.type === "literal") {
regexPieces.push(escapeRegExp(part.text ?? ""));
continue;
}
const letter = part.letter;
const length = part.length;
if (!VOCABULARY_LETTERS.includes(letter)) return null;
const spec = TOKEN_TABLE[`${letter}${length}`];
if (!spec) return null;
if (!allowedFields.has(spec.field)) return null;
if (usedFields.has(spec.field)) return null;
usedFields.add(spec.field);
const groupName = `g${groupCounter++}`;
if (spec.regexSource) {
regexPieces.push(`(?<${groupName}>${spec.regexSource})`);
tokens.push({
groupName,
field: spec.field,
kind: spec.kind
});
continue;
}
if (spec.kind === "monthNameShort" || spec.kind === "monthNameLong") {
const lists = localeMonthNames(locale, spec.kind === "monthNameLong" ? "long" : "short");
if (lists === null) return null;
const names = [...lists.format, ...lists.standAlone];
const union = [...new Set(names)];
regexPieces.push(`(?<${groupName}>${buildNameAlternation(union)})`);
tokens.push({
groupName,
field: spec.field,
kind: spec.kind,
monthNames: lists.format,
standAloneMonthNames: lists.standAlone
});
continue;
}
if (spec.kind === "weekdayShort" || spec.kind === "weekdayLong") {
const names = getLocaleWeekdayNames(locale, spec.kind === "weekdayLong" ? "long" : "short");
if (names.length !== 7) return null;
regexPieces.push(`(?:${buildNameAlternation(names)})`);
continue;
}
if (spec.kind === "meridiem") {
const meridiems = getLocaleMeridiems(locale);
if (meridiems.length !== 2) return null;
regexPieces.push(`(?<${groupName}>${buildNameAlternation(meridiems)})`);
tokens.push({
groupName,
field: spec.field,
kind: spec.kind,
meridiems
});
continue;
}
const eras = getLocaleEraNames(locale, spec.kind === "eraLong" ? "long" : "short");
if (eras.length !== 2) return null;
regexPieces.push(`(?<${groupName}>${buildNameAlternation(eras)})`);
tokens.push({
groupName,
field: spec.field,
kind: spec.kind,
eras
});
}
return {
regex: new RegExp(`^${regexPieces.join("")}$`, "i"),
tokens
};
}
/**
* Resolve a successful regex match's captures back into date/time field
* values, resolving a two-digit year in the caller's window, converting
* 12-hour to 24-hour (via a matched meridiem), and adjusting a BCE year.
*
* This step only ever produces a *candidate* fields object — it does not
* itself prove the fields form a real date/time. The caller is
* responsible for handing the result to `Temporal.*.from(fields, {
* overflow: "reject" })`, which is what actually validates it.
*
* `options` is the caller's `TwoDigitYearOptions` bag, unread. It is read
* only when a `yy` token matched, once (`readYearWindowStart`): a pattern
* with no `yy` never reads `yearWindow`, and so never reads the clock a
* `"rolling"` window needs. Returns `null` when a `yy` token matched and
* the bag names no valid window: no standard says which century a
* two-digit year belongs to, so without the caller's window the value
* cannot be read. Reading a hostile bag throws; the public function's
* `try` turns that into its sentinel.
*/
function resolvePatternFields(match, tokens, options) {
const groups = match.groups ?? {};
const fields = {};
let hourIsTwelveHour = false;
let meridiemIsPM = false;
let eraIsBCE = false;
for (const token of tokens) {
const raw = groups[token.groupName];
if (raw === void 0) continue;
switch (token.kind) {
case "yearFull":
fields.year = Number.parseInt(raw, 10);
break;
case "yearShort": {
const yearWindowStart = readYearWindowStart(options);
if (yearWindowStart === null) return null;
fields.year = twoDigitYear(Number.parseInt(raw, 10), yearWindowStart);
break;
}
case "monthNumber":
fields.month = Number.parseInt(raw, 10);
break;
case "monthNameShort":
case "monthNameLong": {
const wanted = raw.toLowerCase();
const matches = (name) => name.toLowerCase() === wanted;
let index = (token.monthNames ?? []).findIndex(matches);
if (index === -1) index = (token.standAloneMonthNames ?? []).findIndex(matches);
fields.month = index + 1;
break;
}
case "day":
fields.day = Number.parseInt(raw, 10);
break;
case "hour24":
fields.hour = Number.parseInt(raw, 10);
break;
case "hour12":
hourIsTwelveHour = true;
fields.hour = Number.parseInt(raw, 10);
break;
case "minute":
fields.minute = Number.parseInt(raw, 10);
break;
case "second":
fields.second = Number.parseInt(raw, 10);
break;
case "millisecond":
fields.millisecond = Number.parseInt(raw, 10);
break;
case "meridiem": {
const [amLabel, pmLabel] = token.meridiems ?? ["", ""];
meridiemIsPM = raw.toLowerCase() === (pmLabel ?? "").toLowerCase() && (pmLabel ?? "").toLowerCase() !== (amLabel ?? "").toLowerCase();
break;
}
case "eraShort":
case "eraLong": {
const [bceLabel, ceLabel] = token.eras ?? ["", ""];
eraIsBCE = raw.toLowerCase() === (bceLabel ?? "").toLowerCase() && (bceLabel ?? "").toLowerCase() !== (ceLabel ?? "").toLowerCase();
break;
}
}
}
if (hourIsTwelveHour && fields.hour !== void 0) {
if (meridiemIsPM && fields.hour !== 12) fields.hour += 12;
if (!meridiemIsPM && fields.hour === 12) fields.hour = 0;
}
if (eraIsBCE && fields.year !== void 0) fields.year = 1 - fields.year;
return fields;
}
/**
* Parse `value` against `pattern` and return the resolved candidate
* fields, or `null` on malformed pattern / no match / invalid input.
*
* `null` here always means "return the sentinel" to the caller — it
* never distinguishes malformed-pattern from no-match from invalid-input
* from a `yy` token with no window, matching the shared never-throw /
* sentinel-return contract.
*
* `options` is the caller's `TwoDigitYearOptions` bag, already accepted
* by `isOptionsArgument`. It is read lazily: only a matched `yy` token
* reads `yearWindow`, once, so a pattern without `yy` reads neither the
* option nor the clock. A bag that throws when read makes this function
* throw; every caller runs it inside `try`.
*/
function parseValueWithPattern(value, pattern, locale, allowedFields, options) {
if (typeof value !== "string" || value.length === 0) return null;
if (typeof pattern !== "string" || pattern.length === 0) return null;
const resolvedLocale = locale === void 0 || Array.isArray(locale) && locale.length === 0 ? "en" : resolveLocale(locale);
if (resolvedLocale === null) return null;
const compiled = compilePattern(pattern, allowedFields, resolvedLocale);
if (compiled === null) return null;
const match = value.match(compiled.regex);
if (match === null) return null;
return resolvePatternFields(match, compiled.tokens, options);
}
export { DATE_PATTERN_FIELDS, DATE_TIME_PATTERN_FIELDS, MONTH_DAY_PATTERN_FIELDS, TIME_PATTERN_FIELDS, YEAR_MONTH_PATTERN_FIELDS, parseValueWithPattern };