@formkit/tempo 1.0.0 → 1.1.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.
Files changed (52) hide show
  1. package/README.md +22 -1
  2. package/dist/add.d.ts +11 -0
  3. package/dist/add.mjs +50 -0
  4. package/dist/add.mjs.map +1 -0
  5. package/dist/addMonth.mjs +2 -11
  6. package/dist/addMonth.mjs.map +1 -1
  7. package/dist/addYear.mjs +6 -11
  8. package/dist/addYear.mjs.map +1 -1
  9. package/dist/bundle.d.ts +110 -1
  10. package/dist/bundle.mjs +219 -49
  11. package/dist/bundle.mjs.map +1 -1
  12. package/dist/common.mjs +4 -2
  13. package/dist/common.mjs.map +1 -1
  14. package/dist/diff.d.ts +38 -0
  15. package/dist/diff.mjs +86 -0
  16. package/dist/diff.mjs.map +1 -0
  17. package/dist/handleDateOverflow.d.ts +12 -0
  18. package/dist/handleDateOverflow.mjs +18 -0
  19. package/dist/handleDateOverflow.mjs.map +1 -0
  20. package/dist/index.cjs +228 -49
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +110 -1
  23. package/dist/index.d.ts +10 -1
  24. package/dist/index.mjs +18 -0
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/offset.mjs +14 -12
  27. package/dist/offset.mjs.map +1 -1
  28. package/dist/setDayOfMonth.d.ts +11 -0
  29. package/dist/setDayOfMonth.mjs +16 -0
  30. package/dist/setDayOfMonth.mjs.map +1 -0
  31. package/dist/setHour.d.ts +10 -0
  32. package/dist/setHour.mjs +11 -0
  33. package/dist/setHour.mjs.map +1 -0
  34. package/dist/setMilliseconds.d.ts +10 -0
  35. package/dist/setMilliseconds.mjs +11 -0
  36. package/dist/setMilliseconds.mjs.map +1 -0
  37. package/dist/setMinutes.d.ts +10 -0
  38. package/dist/setMinutes.mjs +11 -0
  39. package/dist/setMinutes.mjs.map +1 -0
  40. package/dist/setMonth.d.ts +11 -0
  41. package/dist/setMonth.mjs +9 -0
  42. package/dist/setMonth.mjs.map +1 -0
  43. package/dist/setSeconds.d.ts +10 -0
  44. package/dist/setSeconds.mjs +11 -0
  45. package/dist/setSeconds.mjs.map +1 -0
  46. package/dist/setYear.d.ts +11 -0
  47. package/dist/setYear.mjs +9 -0
  48. package/dist/setYear.mjs.map +1 -0
  49. package/dist/types.d.ts +15 -1
  50. package/dist/yearDays.mjs +1 -1
  51. package/dist/yearDays.mjs.map +1 -1
  52. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/common.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { ap } from \"./ap\"\nimport type {\n DateInput,\n NamedFormats,\n FormatPattern,\n FormatStyle,\n Part,\n FilledPart,\n Format,\n MaybeDateInput,\n ExtendedPartTypes,\n} from \"./types\"\n\n/**\n * A date to use for determining various spec details.\n */\nexport const specDate = \"1999-03-04T02:05:01.000Z\"\n\n/**\n * A cache of Intl tokens and their respective formats.\n */\nexport const memoParts: Map<string, NamedFormats> = new Map()\n\n/**\n * Clock agnostic time format patterns.\n */\nexport const clockAgnostic: FormatPattern[] = [\n [\"YYYY\", { year: \"numeric\" }],\n [\"YY\", { year: \"2-digit\" }],\n [\"MMMM\", { month: \"long\" }],\n [\"MMM\", { month: \"short\" }],\n [\"MM\", { month: \"2-digit\" }],\n [\"M\", { month: \"numeric\" }],\n [\"DD\", { day: \"2-digit\" }],\n [\"D\", { day: \"numeric\" }],\n [\"dddd\", { weekday: \"long\" }],\n [\"ddd\", { weekday: \"short\" }],\n [\"d\", { weekday: \"narrow\" }],\n [\"mm\", { minute: \"2-digit\" }],\n [\"m\", { minute: \"numeric\" }],\n [\"ss\", { second: \"2-digit\" }],\n [\"s\", { second: \"numeric\" }],\n [\"ZZ\", { timeZoneName: \"long\" }],\n [\"Z\", { timeZoneName: \"short\" }],\n]\n\n/**\n * Timezone tokens.\n */\nconst timeZoneTokens = [\"Z\", \"ZZ\"] as const\n\n/**\n * Timezone token type.\n */\nexport type TimezoneToken = (typeof timeZoneTokens)[number]\n\n/**\n * 24 hour click format patterns.\n */\nexport const clock24: FormatPattern[] = [\n [\"HH\", { hour: \"2-digit\" }],\n [\"H\", { hour: \"numeric\" }],\n]\n\n/**\n * 12 hour format patterns.\n */\nexport const clock12: FormatPattern[] = [\n [\"hh\", { hour: \"2-digit\" }],\n [\"h\", { hour: \"numeric\" }],\n [\"a\", { dayPeriod: \"narrow\" }],\n [\"A\", { dayPeriod: \"narrow\" }],\n]\n\n/**\n * Fractional seconds patterns.\n */\nexport const fractionalSeconds: FormatPattern[] = [\n [\"SSS\", { fractionalSecond: \"3-digit\" }],\n]\n\n/**\n * Tokens that have a fixed length.\n */\nexport const fixedLength = {\n DD: 2,\n HH: 2,\n MM: 2,\n YY: 2,\n YYYY: 4,\n hh: 2,\n mm: 2,\n ss: 2,\n}\n\n/**\n * Determines the length of a timezone offset string.\n * Supports offsets with optional seconds component.\n */\nexport function fixedLengthByOffset(offsetString: string): 9 | 8 | 6 | 5 {\n // starts with [+-]xx:xx:xx (9 chars, Z format with seconds)\n if (/^[+-]\\d{2}:\\d{2}:\\d{2}/.test(offsetString)) {\n return 9\n }\n\n // starts with [+-]xxxxxx (8 chars, ZZ format with seconds)\n if (/^[+-]\\d{6}/.test(offsetString)) {\n return 8\n }\n\n // starts with [+-]xx:xx (6 chars, Z format)\n if (/^[+-]\\d{2}:\\d{2}/.test(offsetString)) {\n return 6\n }\n\n // starts with [+-]xxxx (5 chars, ZZ format)\n if (/^[+-]\\d{4}/.test(offsetString)) {\n return 5\n }\n\n throw new Error(\"Invalid offset format\")\n}\n\n/**\n * Tokens that are genitive — in that they can have \"possession\" when used in\n * a date phrase, \"March’s 4th day\" (but not in english).\n *\n * When computing a range for these, the range can be either genitive or not.\n * The same is true for parsing dates containing these tokens.\n */\nexport const genitiveTokens = [\"MMMM\", \"MMM\", \"dddd\", \"ddd\"]\n\n/**\n * A map of FormatPattern tuples to their respective token.\n */\nexport const tokens = /* @__PURE__ */ new Map(\n /* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12, ...fractionalSeconds].map((format) => {\n return [format[0], format]\n })\n)\n\n/**\n * A map of locale’s am/pm.\n */\nexport const dayPeriodMap: Map<string, { am?: string; pm?: string }> = new Map()\n\n/**\n * An array of all available date styles.\n */\nexport const styles: ReadonlyArray<FormatStyle> = [\"full\", \"long\", \"medium\", \"short\"]\n\n/**\n * Creates a leading zero string of 2 digits.\n * @param n - A number.\n */\nexport const two = (n: number) => String(n).padStart(2, \"0\")\n/**\n * Creates a leading zero string of 4 digits.\n * @param n - A number.\n */\nexport const four = (n: number) => String(n).padStart(2, \"0\")\n\n/**\n * Normalizes a given part to NFKC.\n * @param part - The part to normalize.\n */\nexport function normStr(part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart {\n if (part.type === \"literal\") {\n part.value = part.value.normalize(\"NFKC\")\n }\n return part\n}\n\n/**\n * Returns the parts filled with pertinent values.\n * @param [inputDate] - The date to fill parts for\n * @param parts - An array of parts to fill\n * @param locale - The locale to fill with.\n * @param genitive - Whether to use genitive tokens values or not.\n * @param offset - The explicit offset to fill with (ignores the date’s true offset).\n */\nexport function fill(\n inputDate: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false,\n offset: string | null = null\n): FilledPart[] {\n const partMap = createPartMap(inputDate, parts, locale, genitive)\n const d = date(inputDate)\n\n /**\n * Not all values get returned \"properly\" as our tokens would suggest. For\n * example, at times Intl returns leading zeros when it shouldn't. This fn\n * is used to clean up those irregular values.\n * @param param - Part\n */\n function value({ partName, partValue, token }: Part) {\n if (partName === \"literal\") return partValue\n const value = partMap[partName]\n if (partName === \"hour\" && token === \"H\") {\n return value.replace(/^0/, \"\") || \"0\"\n }\n if ([\"mm\", \"ss\", \"MM\"].includes(token) && value.length === 1) {\n // Some tokens are supposed to have leading zeros, but Intl doesn't\n // always return them, depending on the locale and the format.\n return `0${value}`\n }\n if (partName === \"dayPeriod\") {\n const p = ap(d.getUTCHours() < 12 ? \"am\" : \"pm\", locale)\n return token === \"A\" ? p.toUpperCase() : p.toLowerCase()\n }\n if (partName === \"fractionalSecond\") {\n return String(d.getUTCMilliseconds()).padStart(3, \"0\")\n }\n if (partName === \"timeZoneName\") {\n return offset ?? minsToOffset(-1 * d.getTimezoneOffset(), token)\n }\n return value\n }\n\n return parts.map((part): FilledPart => {\n return {\n ...part,\n value: value(part),\n }\n })\n}\n\n/**\n * Creates a map of part names to their respective values.\n * @param [inputDate] - The date to format\n * @param parts - The individual parts the need to be formatted.\n * @param locale - The locale to format the parts with.\n * @param genitive - Whether to use genitive tokens values or not.\n */\nfunction createPartMap(\n inputDate: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false\n): Record<ExtendedPartTypes, string> {\n const d = date(inputDate)\n const hour12 = parts.filter((part) => part.hour12)\n const hour24 = parts.filter((part) => !part.hour12)\n const valueParts: Intl.DateTimeFormatPart[] = []\n const genitiveParts: Part[] = []\n\n function addValues(requestedParts: Part[], hour12 = false) {\n const preciseLocale = `${locale}-u-hc-${hour12 ? \"h12\" : \"h23\"}`\n valueParts.push(\n ...new Intl.DateTimeFormat(\n preciseLocale,\n requestedParts.reduce(\n (options, part) => {\n if (part.partName === \"literal\") return options\n // Side effect! Genitive parts get shoved into a separate array.\n if (genitive && genitiveTokens.includes(part.token)) {\n genitiveParts.push(part)\n }\n return Object.assign(options, part.option)\n },\n { timeZone: \"UTC\" } as Intl.DateTimeFormatOptions\n )\n )\n .formatToParts(d)\n .map(normStr)\n )\n if (genitive && genitiveParts.length) {\n for (const part of genitiveParts) {\n let formattedParts: Intl.DateTimeFormatPart[] = []\n switch (part.token) {\n case \"MMMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"long\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n case \"MMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"medium\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n }\n const genitiveFormattedPart = formattedParts.find((p) => p.type === part.partName)\n const index = valueParts.findIndex((p) => p.type === part.partName)\n if (genitiveFormattedPart && index > -1) {\n valueParts[index] = genitiveFormattedPart\n }\n }\n }\n }\n\n if (hour12.length) addValues(hour12, true)\n if (hour24.length) addValues(hour24)\n\n return valueParts.reduce((map, part) => {\n map[part.type as ExtendedPartTypes] = part.value\n return map\n }, {} as Record<ExtendedPartTypes, string>)\n}\n\n/**\n * Converts total seconds to an ISO8601 compatible offset (+04:00 or +0400).\n * Only includes seconds in output if they are non-zero.\n * @param totalSecs - The total offset in seconds (can be negative).\n * @param token - \"Z\" for +HH:mm[:ss] or \"ZZ\" for +HHmm[ss]\n */\nexport function secsToOffset(totalSecs: number, token: string = \"Z\"): string {\n const sign = totalSecs < 0 ? \"-\" : \"+\"\n const absSecs = Math.abs(totalSecs)\n const hours = String(Math.floor(absSecs / 3600)).padStart(2, \"0\")\n const mins = String(Math.floor((absSecs % 3600) / 60)).padStart(2, \"0\")\n const secs = Math.round(absSecs % 60)\n\n if (token === \"ZZ\") {\n return secs === 0\n ? `${sign}${hours}${mins}`\n : `${sign}${hours}${mins}${String(secs).padStart(2, \"0\")}`\n }\n return secs === 0\n ? `${sign}${hours}:${mins}`\n : `${sign}${hours}:${mins}:${String(secs).padStart(2, \"0\")}`\n}\n\n/**\n * Converts minutes (300) to an ISO8601 compatible offset (+0400 or +04:00).\n * @param timeDiffInMins - The difference in minutes between two timezones.\n * @returns\n */\nexport function minsToOffset(timeDiffInMins: number, token: string = \"Z\"): string {\n return secsToOffset(timeDiffInMins * 60, token)\n}\n\n/**\n * Converts an offset (-05:32:11 or -053211) to total seconds.\n * Supports offsets with optional seconds component.\n * @param offset - The offset to convert to seconds.\n * @param token - The timezone token format.\n */\nexport function offsetToSecs(offset: string, token: TimezoneToken): number {\n validOffset(offset, token)\n const match = offset.match(/([+-])([0-3][0-9]):?([0-5][0-9])(?::?([0-5][0-9]))?/)!\n const [_, sign, hours, mins, secs = \"0\"] = match\n const totalSecs = Number(hours) * 3600 + Number(mins) * 60 + Number(secs)\n return sign === \"+\" ? totalSecs : -totalSecs\n}\n\n/**\n * Converts an offset (-0500) to minutes (-300).\n * @param offset - The offset to convert to minutes.\n * @param token - The timezone token format.\n */\nexport function offsetToMins(offset: string, token: TimezoneToken): number {\n return Math.round(offsetToSecs(offset, token) / 60)\n}\n\n/**\n * Validates that an offset is valid according to the format:\n * [+-]HH:mm or [+-]HH:mm:ss (Z token)\n * [+-]HHmm or [+-]HHmmss (ZZ token)\n * @param offset - The offset to validate.\n * @param token - The timezone token format.\n */\nexport function validOffset(offset: string, token: TimezoneToken = \"Z\") {\n const valid = ((token: TimezoneToken): boolean => {\n switch (token) {\n case \"Z\":\n return /^([+-])[0-3][0-9]:[0-5][0-9](?::[0-5][0-9])?$/.test(offset)\n case \"ZZ\":\n return /^([+-])[0-3][0-9][0-5][0-9](?:[0-5][0-9])?$/.test(offset)\n }\n })(token)\n\n if (!valid) throw new Error(`Invalid offset: ${offset}`)\n return offset\n}\n\n/**\n * Given a string of tokens, escape any characters that are tokens.\n * @param str - The string to escape tokens in.\n * @returns The escaped string.\n */\nexport function escapeTokens(str: string): string {\n return clockAgnostic\n .concat(clock24)\n .concat(clock12)\n .concat(fractionalSeconds)\n .sort((a, b) => (a[0].length > b[0].length ? 1 : -1))\n .reduce((target, part) => {\n return target.replace(part[0], `\\\\${part[0]}`)\n }, str)\n}\n\n/**\n * Checks if a given part should have a numeric value.\n * @param part - A part to check\n */\nexport function isNumeric(part: Part) {\n return [\"numeric\", \"2-digit\"].includes(part.partValue)\n}\n\n/**\n * Validates that an array of Parts can be parsed.\n * @param parts - Parts to validate for parsing ability.\n */\nexport function validate(parts: Part[]): Part[] | never {\n let lastPart: Part | undefined = undefined\n for (const part of parts) {\n if (part.partName === \"literal\" && !isNaN(parseFloat(part.partValue))) {\n throw new Error(`Numbers in format (${part.partValue}).`)\n }\n if (lastPart && lastPart.partName !== \"literal\" && part.partName !== \"literal\") {\n if (\n !(lastPart.token in fixedLength) &&\n !(part.token in fixedLength) &&\n !(isNumeric(lastPart) && part.token.toLowerCase() === \"a\") &&\n lastPart.token !== \"SSS\" // SSS can be followed by anything (greedy digit consumer)\n ) {\n throw new Error(`Illegal adjacent tokens (${lastPart.token}, ${part.token})`)\n }\n }\n lastPart = part\n }\n return parts\n}\n\n/**\n * Returns the timezone token format from a given format.\n * @param format - The format to check.\n * @returns The timezone token format (\"Z\" or \"ZZ\").\n */\nexport function getOffsetFormat(format: Format): TimezoneToken {\n if (typeof format === \"string\") {\n return format.includes(\"ZZ\") ? \"ZZ\" : \"Z\"\n }\n return \"time\" in format && format.time === \"full\" ? \"Z\" : \"ZZ\"\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,UAAU;AAgBZ,IAAM,WAAW;AAKjB,IAAM,YAAuC,oBAAI,IAAI;AAKrD,IAAM,gBAAiC;AAAA,EAC5C,CAAC,QAAQ,EAAE,MAAM,UAAU,CAAC;AAAA,EAC5B,CAAC,MAAM,EAAE,MAAM,UAAU,CAAC;AAAA,EAC1B,CAAC,QAAQ,EAAE,OAAO,OAAO,CAAC;AAAA,EAC1B,CAAC,OAAO,EAAE,OAAO,QAAQ,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,OAAO,UAAU,CAAC;AAAA,EAC3B,CAAC,KAAK,EAAE,OAAO,UAAU,CAAC;AAAA,EAC1B,CAAC,MAAM,EAAE,KAAK,UAAU,CAAC;AAAA,EACzB,CAAC,KAAK,EAAE,KAAK,UAAU,CAAC;AAAA,EACxB,CAAC,QAAQ,EAAE,SAAS,OAAO,CAAC;AAAA,EAC5B,CAAC,OAAO,EAAE,SAAS,QAAQ,CAAC;AAAA,EAC5B,CAAC,KAAK,EAAE,SAAS,SAAS,CAAC;AAAA,EAC3B,CAAC,MAAM,EAAE,QAAQ,UAAU,CAAC;AAAA,EAC5B,CAAC,KAAK,EAAE,QAAQ,UAAU,CAAC;AAAA,EAC3B,CAAC,MAAM,E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AAS,CAAC,GAAG;AACrE,YAAM,IAAI,MAAM,sBAAsB,KAAK,SAAS,IAAI;AAAA,IAC1D;AACA,QAAI,YAAY,SAAS,aAAa,aAAa,KAAK,aAAa,WAAW;AAC9E,UACE,EAAE,SAAS,SAAS,gBACpB,EAAE,KAAK,SAAS,gBAChB,EAAE,UAAU,QAAQ,KAAK,KAAK,MAAM,YAAY,MAAM,QACtD,SAAS,UAAU,OACnB;AACA,cAAM,IAAI,MAAM,4BAA4B,SAAS,KAAK,KAAK,KAAK,KAAK,GAAG;AAAA,MAC9E;AAAA,IACF;AACA,eAAW;AAAA,EACb;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,QAA+B;AAC7D,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,OAAO,SAAS,IAAI,IAAI,OAAO;AAAA,EACxC;AACA,SAAO,UAAU,UAAU,OAAO,SAAS,SAAS,MAAM;AAC5D;","names":["value","hour12","token"]}
1
+ {"version":3,"sources":["../src/common.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { ap } from \"./ap\"\nimport type {\n DateInput,\n NamedFormats,\n FormatPattern,\n FormatStyle,\n Part,\n FilledPart,\n Format,\n MaybeDateInput,\n ExtendedPartTypes,\n} from \"./types\"\n\n/**\n * A date to use for determining various spec details.\n */\nexport const specDate = \"1999-03-04T02:05:01.000Z\"\n\n/**\n * A cache of Intl tokens and their respective formats.\n */\nexport const memoParts: Map<string, NamedFormats> = new Map()\n\n/**\n * Clock agnostic time format patterns.\n */\nexport const clockAgnostic: FormatPattern[] = [\n [\"YYYY\", { year: \"numeric\" }],\n [\"YY\", { year: \"2-digit\" }],\n [\"MMMM\", { month: \"long\" }],\n [\"MMM\", { month: \"short\" }],\n [\"MM\", { month: \"2-digit\" }],\n [\"M\", { month: \"numeric\" }],\n [\"DD\", { day: \"2-digit\" }],\n [\"D\", { day: \"numeric\" }],\n [\"dddd\", { weekday: \"long\" }],\n [\"ddd\", { weekday: \"short\" }],\n [\"d\", { weekday: \"narrow\" }],\n [\"mm\", { minute: \"2-digit\" }],\n [\"m\", { minute: \"numeric\" }],\n [\"ss\", { second: \"2-digit\" }],\n [\"s\", { second: \"numeric\" }],\n [\"ZZ\", { timeZoneName: \"long\" }],\n [\"Z\", { timeZoneName: \"short\" }],\n]\n\n/**\n * Timezone tokens.\n */\nconst timeZoneTokens = [\"Z\", \"ZZ\"] as const\n\n/**\n * Timezone token type.\n */\nexport type TimezoneToken = (typeof timeZoneTokens)[number]\n\n/**\n * 24 hour click format patterns.\n */\nexport const clock24: FormatPattern[] = [\n [\"HH\", { hour: \"2-digit\" }],\n [\"H\", { hour: \"numeric\" }],\n]\n\n/**\n * 12 hour format patterns.\n */\nexport const clock12: FormatPattern[] = [\n [\"hh\", { hour: \"2-digit\" }],\n [\"h\", { hour: \"numeric\" }],\n [\"a\", { dayPeriod: \"narrow\" }],\n [\"A\", { dayPeriod: \"narrow\" }],\n]\n\n/**\n * Fractional seconds patterns.\n */\nexport const fractionalSeconds: FormatPattern[] = [\n [\"SSS\", { fractionalSecond: \"3-digit\" }],\n]\n\n/**\n * Tokens that have a fixed length.\n */\nexport const fixedLength = {\n DD: 2,\n HH: 2,\n MM: 2,\n YY: 2,\n YYYY: 4,\n hh: 2,\n mm: 2,\n ss: 2,\n}\n\n/**\n * Determines the length of a timezone offset string.\n * Supports offsets with optional seconds component.\n */\nexport function fixedLengthByOffset(offsetString: string): 9 | 8 | 6 | 5 {\n // starts with [+-]xx:xx:xx (9 chars, Z format with seconds)\n if (/^[+-]\\d{2}:\\d{2}:\\d{2}/.test(offsetString)) {\n return 9\n }\n\n // starts with [+-]xxxxxx (8 chars, ZZ format with seconds)\n if (/^[+-]\\d{6}/.test(offsetString)) {\n return 8\n }\n\n // starts with [+-]xx:xx (6 chars, Z format)\n if (/^[+-]\\d{2}:\\d{2}/.test(offsetString)) {\n return 6\n }\n\n // starts with [+-]xxxx (5 chars, ZZ format)\n if (/^[+-]\\d{4}/.test(offsetString)) {\n return 5\n }\n\n throw new Error(\"Invalid offset format\")\n}\n\n/**\n * Tokens that are genitive — in that they can have \"possession\" when used in\n * a date phrase, \"March’s 4th day\" (but not in english).\n *\n * When computing a range for these, the range can be either genitive or not.\n * The same is true for parsing dates containing these tokens.\n */\nexport const genitiveTokens = [\"MMMM\", \"MMM\", \"dddd\", \"ddd\"]\n\n/**\n * A map of FormatPattern tuples to their respective token.\n */\nexport const tokens = /* @__PURE__ */ new Map(\n /* @__PURE__ */ [...clockAgnostic, ...clock24, ...clock12, ...fractionalSeconds].map((format) => {\n return [format[0], format]\n })\n)\n\n/**\n * A map of locale’s am/pm.\n */\nexport const dayPeriodMap: Map<string, { am?: string; pm?: string }> = new Map()\n\n/**\n * An array of all available date styles.\n */\nexport const styles: ReadonlyArray<FormatStyle> = [\"full\", \"long\", \"medium\", \"short\"]\n\n/**\n * Creates a leading zero string of 2 digits.\n * @param n - A number.\n */\nexport const two = (n: number) => String(n).padStart(2, \"0\")\n/**\n * Creates a leading zero string of 4 digits.\n * @param n - A number.\n */\nexport const four = (n: number) => String(n).padStart(4, \"0\")\n\n/**\n * Normalizes a given part to NFKC.\n * @param part - The part to normalize.\n */\nexport function normStr(part: Intl.DateTimeFormatPart): Intl.DateTimeFormatPart {\n if (part.type === \"literal\") {\n part.value = part.value.normalize(\"NFKC\")\n }\n return part\n}\n\n/**\n * Returns the parts filled with pertinent values.\n * @param [inputDate] - The date to fill parts for\n * @param parts - An array of parts to fill\n * @param locale - The locale to fill with.\n * @param genitive - Whether to use genitive tokens values or not.\n * @param offset - The explicit offset to fill with (ignores the date’s true offset).\n */\nexport function fill(\n inputDate: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false,\n offset: string | null = null\n): FilledPart[] {\n const partMap = createPartMap(inputDate, parts, locale, genitive)\n const d = date(inputDate)\n\n /**\n * Not all values get returned \"properly\" as our tokens would suggest. For\n * example, at times Intl returns leading zeros when it shouldn't. This fn\n * is used to clean up those irregular values.\n * @param param - Part\n */\n function value({ partName, partValue, token }: Part) {\n if (partName === \"literal\") return partValue\n const value = partMap[partName]\n if (partName === \"hour\" && token === \"H\") {\n return value.replace(/^0/, \"\") || \"0\"\n }\n if ([\"mm\", \"ss\", \"MM\"].includes(token) && value.length === 1) {\n // Some tokens are supposed to have leading zeros, but Intl doesn't\n // always return them, depending on the locale and the format.\n return `0${value}`\n }\n if (partName === \"dayPeriod\") {\n const p = ap(d.getUTCHours() < 12 ? \"am\" : \"pm\", locale)\n return token === \"A\" ? p.toUpperCase() : p.toLowerCase()\n }\n if (partName === \"fractionalSecond\") {\n return String(d.getUTCMilliseconds()).padStart(3, \"0\")\n }\n if (partName === \"timeZoneName\") {\n return offset ?? minsToOffset(-1 * d.getTimezoneOffset(), token)\n }\n return value\n }\n\n return parts.map((part): FilledPart => {\n return {\n ...part,\n value: value(part),\n }\n })\n}\n\n/**\n * Creates a map of part names to their respective values.\n * @param [inputDate] - The date to format\n * @param parts - The individual parts the need to be formatted.\n * @param locale - The locale to format the parts with.\n * @param genitive - Whether to use genitive tokens values or not.\n */\nfunction createPartMap(\n inputDate: MaybeDateInput,\n parts: Part[],\n locale: string,\n genitive = false\n): Record<ExtendedPartTypes, string> {\n const d = date(inputDate)\n const hour12 = parts.filter((part) => part.hour12)\n const hour24 = parts.filter((part) => !part.hour12)\n const valueParts: Intl.DateTimeFormatPart[] = []\n const genitiveParts: Part[] = []\n\n function addValues(requestedParts: Part[], hour12 = false) {\n // Use Intl.Locale to merge the hourCycle extension into the locale tag.\n // Plain string concatenation (e.g. `${locale}-u-hc-h23`) produces an\n // invalid BCP 47 tag when the locale already contains a Unicode extension\n // block (e.g. \"ar-u-nu-arab\"), because a tag may only have one \"-u-\" block.\n // Intl.Locale merges extensions correctly into a single \"-u-\" subtag.\n const preciseLocale = new Intl.Locale(locale, {\n hourCycle: hour12 ? \"h12\" : \"h23\",\n }).toString()\n valueParts.push(\n ...new Intl.DateTimeFormat(\n preciseLocale,\n requestedParts.reduce(\n (options, part) => {\n if (part.partName === \"literal\") return options\n // Side effect! Genitive parts get shoved into a separate array.\n if (genitive && genitiveTokens.includes(part.token)) {\n genitiveParts.push(part)\n }\n return Object.assign(options, part.option)\n },\n { timeZone: \"UTC\" } as Intl.DateTimeFormatOptions\n )\n )\n .formatToParts(d)\n .map(normStr)\n )\n if (genitive && genitiveParts.length) {\n for (const part of genitiveParts) {\n let formattedParts: Intl.DateTimeFormatPart[] = []\n switch (part.token) {\n case \"MMMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"long\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n case \"MMM\":\n formattedParts = new Intl.DateTimeFormat(preciseLocale, {\n dateStyle: \"medium\",\n timeZone: \"UTC\",\n })\n .formatToParts(d)\n .map(normStr)\n break\n }\n const genitiveFormattedPart = formattedParts.find((p) => p.type === part.partName)\n const index = valueParts.findIndex((p) => p.type === part.partName)\n if (genitiveFormattedPart && index > -1) {\n valueParts[index] = genitiveFormattedPart\n }\n }\n }\n }\n\n if (hour12.length) addValues(hour12, true)\n if (hour24.length) addValues(hour24)\n\n return valueParts.reduce((map, part) => {\n map[part.type as ExtendedPartTypes] = part.value\n return map\n }, {} as Record<ExtendedPartTypes, string>)\n}\n\n/**\n * Converts total seconds to an ISO8601 compatible offset (+04:00 or +0400).\n * Only includes seconds in output if they are non-zero.\n * @param totalSecs - The total offset in seconds (can be negative).\n * @param token - \"Z\" for +HH:mm[:ss] or \"ZZ\" for +HHmm[ss]\n */\nexport function secsToOffset(totalSecs: number, token: string = \"Z\"): string {\n const sign = totalSecs < 0 ? \"-\" : \"+\"\n const absSecs = Math.abs(totalSecs)\n const hours = String(Math.floor(absSecs / 3600)).padStart(2, \"0\")\n const mins = String(Math.floor((absSecs % 3600) / 60)).padStart(2, \"0\")\n const secs = Math.round(absSecs % 60)\n\n if (token === \"ZZ\") {\n return secs === 0\n ? `${sign}${hours}${mins}`\n : `${sign}${hours}${mins}${String(secs).padStart(2, \"0\")}`\n }\n return secs === 0\n ? `${sign}${hours}:${mins}`\n : `${sign}${hours}:${mins}:${String(secs).padStart(2, \"0\")}`\n}\n\n/**\n * Converts minutes (300) to an ISO8601 compatible offset (+0400 or +04:00).\n * @param timeDiffInMins - The difference in minutes between two timezones.\n * @returns\n */\nexport function minsToOffset(timeDiffInMins: number, token: string = \"Z\"): string {\n return secsToOffset(timeDiffInMins * 60, token)\n}\n\n/**\n * Converts an offset (-05:32:11 or -053211) to total seconds.\n * Supports offsets with optional seconds component.\n * @param offset - The offset to convert to seconds.\n * @param token - The timezone token format.\n */\nexport function offsetToSecs(offset: string, token: TimezoneToken): number {\n validOffset(offset, token)\n const match = offset.match(/([+-])([0-3][0-9]):?([0-5][0-9])(?::?([0-5][0-9]))?/)!\n const [_, sign, hours, mins, secs = \"0\"] = match\n const totalSecs = Number(hours) * 3600 + Number(mins) * 60 + Number(secs)\n return sign === \"+\" ? totalSecs : -totalSecs\n}\n\n/**\n * Converts an offset (-0500) to minutes (-300).\n * @param offset - The offset to convert to minutes.\n * @param token - The timezone token format.\n */\nexport function offsetToMins(offset: string, token: TimezoneToken): number {\n return Math.round(offsetToSecs(offset, token) / 60)\n}\n\n/**\n * Validates that an offset is valid according to the format:\n * [+-]HH:mm or [+-]HH:mm:ss (Z token)\n * [+-]HHmm or [+-]HHmmss (ZZ token)\n * @param offset - The offset to validate.\n * @param token - The timezone token format.\n */\nexport function validOffset(offset: string, token: TimezoneToken = \"Z\") {\n const valid = ((token: TimezoneToken): boolean => {\n switch (token) {\n case \"Z\":\n return /^([+-])[0-3][0-9]:[0-5][0-9](?::[0-5][0-9])?$/.test(offset)\n case \"ZZ\":\n return /^([+-])[0-3][0-9][0-5][0-9](?:[0-5][0-9])?$/.test(offset)\n }\n })(token)\n\n if (!valid) throw new Error(`Invalid offset: ${offset}`)\n return offset\n}\n\n/**\n * Given a string of tokens, escape any characters that are tokens.\n * @param str - The string to escape tokens in.\n * @returns The escaped string.\n */\nexport function escapeTokens(str: string): string {\n return clockAgnostic\n .concat(clock24)\n .concat(clock12)\n .concat(fractionalSeconds)\n .sort((a, b) => (a[0].length > b[0].length ? 1 : -1))\n .reduce((target, part) => {\n return target.replace(part[0], `\\\\${part[0]}`)\n }, str)\n}\n\n/**\n * Checks if a given part should have a numeric value.\n * @param part - A part to check\n */\nexport function isNumeric(part: Part) {\n return [\"numeric\", \"2-digit\"].includes(part.partValue)\n}\n\n/**\n * Validates that an array of Parts can be parsed.\n * @param parts - Parts to validate for parsing ability.\n */\nexport function validate(parts: Part[]): Part[] | never {\n let lastPart: Part | undefined = undefined\n for (const part of parts) {\n if (part.partName === \"literal\" && !isNaN(parseFloat(part.partValue))) {\n throw new Error(`Numbers in format (${part.partValue}).`)\n }\n if (lastPart && lastPart.partName !== \"literal\" && part.partName !== \"literal\") {\n if (\n !(lastPart.token in fixedLength) &&\n !(part.token in fixedLength) &&\n !(isNumeric(lastPart) && part.token.toLowerCase() === \"a\") &&\n lastPart.token !== \"SSS\" // SSS can be followed by anything (greedy digit consumer)\n ) {\n throw new Error(`Illegal adjacent tokens (${lastPart.token}, ${part.token})`)\n }\n }\n lastPart = part\n }\n return parts\n}\n\n/**\n * Returns the timezone token format from a given format.\n * @param format - The format to check.\n * @returns The timezone token format (\"Z\" or \"ZZ\").\n */\nexport function getOffsetFormat(format: Format): TimezoneToken {\n if (typeof format === \"string\") {\n return format.includes(\"ZZ\") ? \"ZZ\" : \"Z\"\n }\n return \"time\" in format && format.time === \"full\" ? \"Z\" : \"ZZ\"\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,UAAU;AAgBZ,IAAM,WAAW;AAKjB,IAAM,YAAuC,oBAAI,IAAI;AAKrD,IAAM,gBAAiC;AAAA,EAC5C,CAAC,QAAQ,EAAE,MAAM,UAAU,CAAC;AAAA,EAC5B,CAAC,MAAM,EAAE,MAAM,UAAU,CAAC;AAAA,EAC1B,CAAC,QAAQ,EAAE,OAAO,OAAO,CAAC;AAAA,EAC1B,CAAC,OAAO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AM,EAAE;AACvD,SAAO;AACT;AAOO,SAAS,aAAa,KAAqB;AAChD,SAAO,cACJ,OAAO,OAAO,EACd,OAAO,OAAO,EACd,OAAO,iBAAiB,EACxB,KAAK,CAAC,GAAG,MAAO,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS,IAAI,EAAG,EACnD,OAAO,CAAC,QAAQ,SAAS;AACxB,WAAO,OAAO,QAAQ,KAAK,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,EAAE;AAAA,EAC/C,GAAG,GAAG;AACV;AAMO,SAAS,UAAU,MAAY;AACpC,SAAO,CAAC,WAAW,SAAS,EAAE,SAAS,KAAK,SAAS;AACvD;AAMO,SAAS,SAAS,OAA+B;AACtD,MAAI,WAA6B;AACjC,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,aAAa,aAAa,CAAC,MAAM,WAAW,KAAK,SAAS,CAAC,GAAG;AACrE,YAAM,IAAI,MAAM,sBAAsB,KAAK,SAAS,IAAI;AAAA,IAC1D;AACA,QAAI,YAAY,SAAS,aAAa,aAAa,KAAK,aAAa,WAAW;AAC9E,UACE,EAAE,SAAS,SAAS,gBACpB,EAAE,KAAK,SAAS,gBAChB,EAAE,UAAU,QAAQ,KAAK,KAAK,MAAM,YAAY,MAAM,QACtD,SAAS,UAAU,OACnB;AACA,cAAM,IAAI,MAAM,4BAA4B,SAAS,KAAK,KAAK,KAAK,KAAK,GAAG;AAAA,MAC9E;AAAA,IACF;AACA,eAAW;AAAA,EACb;AACA,SAAO;AACT;AAOO,SAAS,gBAAgB,QAA+B;AAC7D,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,OAAO,SAAS,IAAI,IAAI,OAAO;AAAA,EACxC;AACA,SAAO,UAAU,UAAU,OAAO,SAAS,SAAS,MAAM;AAC5D;","names":["value","hour12","token"]}
package/dist/diff.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { Duration, DateInput, MaybeDateInput } from './types.js';
2
+
3
+ type DurationKey = keyof Duration;
4
+ /**
5
+ * Options for `diff` function
6
+ */
7
+ interface DiffOptions {
8
+ /**
9
+ * whether the difference should be absolute (not negative)
10
+ */
11
+ abs?: boolean;
12
+ /**
13
+ * units you want to skip, for example weeks
14
+ */
15
+ skip?: DurationKey[] | Set<DurationKey>;
16
+ }
17
+ /**
18
+ * Returns the difference between 2 dates in an object
19
+ * @param dateA - A date to compare with the right date
20
+ * @param [dateB] - A date to compare with the left date or nothing to compare with the current time
21
+ * @param [options] additional options
22
+ * @param [options.skip] units you want skip
23
+ * @param [options.abs] whether the difference should be absolute
24
+ * @returns an object which could be used with `Intl.DurationFormat.format'`
25
+ */
26
+ declare function diff(dateA: DateInput, dateB?: MaybeDateInput, options?: DiffOptions): Duration;
27
+ /**
28
+ * Returns the difference between 2 dates in an object
29
+ * @param [dateA] - A date to compare with the right date or null to compare with the current time
30
+ * @param dateB - A date to compare with the left date
31
+ * @param [options] additional options
32
+ * @param [options.skip] units you want skip
33
+ * @param [options.abs] whether the difference should be absolute
34
+ * @returns an object which could be used with `Intl.DurationFormat.format'`
35
+ */
36
+ declare function diff(dateA: MaybeDateInput, dateB: DateInput, options?: DiffOptions): Duration;
37
+
38
+ export { type DiffOptions, diff };
package/dist/diff.mjs ADDED
@@ -0,0 +1,86 @@
1
+ // src/diff.ts
2
+ import { addDay } from "./addDay.mjs";
3
+ import { addHour } from "./addHour.mjs";
4
+ import { addMinute } from "./addMinute.mjs";
5
+ import { addMonth } from "./addMonth.mjs";
6
+ import { addSecond } from "./addSecond.mjs";
7
+ import { addYear } from "./addYear.mjs";
8
+ import { date } from "./date.mjs";
9
+ import { diffDays } from "./diffDays.mjs";
10
+ import { diffHours } from "./diffHours.mjs";
11
+ import { diffMilliseconds } from "./diffMilliseconds.mjs";
12
+ import { diffMinutes } from "./diffMinutes.mjs";
13
+ import { diffMonths } from "./diffMonths.mjs";
14
+ import { diffSeconds } from "./diffSeconds.mjs";
15
+ import { diffWeeks } from "./diffWeeks.mjs";
16
+ import { diffYears } from "./diffYears.mjs";
17
+ function negateDuration(duration) {
18
+ const negated = {};
19
+ for (const unit of Object.keys(duration)) {
20
+ negated[unit] = -duration[unit];
21
+ }
22
+ return negated;
23
+ }
24
+ function calendarDiff(current, target, diffUnit, addUnit) {
25
+ let amount = diffUnit(current, target);
26
+ let next = addUnit(current, -amount);
27
+ while (amount > 0 && next < target) {
28
+ amount--;
29
+ next = addUnit(current, -amount);
30
+ }
31
+ return [amount, next];
32
+ }
33
+ function diff(dateA, dateB, options) {
34
+ let a = date(dateA);
35
+ let b = date(dateB);
36
+ if (a < b) {
37
+ const duration2 = diff(b, a, options);
38
+ return (options == null ? void 0 : options.abs) ? duration2 : negateDuration(duration2);
39
+ }
40
+ const skip = new Set(options == null ? void 0 : options.skip);
41
+ const duration = {};
42
+ if (!skip.has("years")) {
43
+ const [years, next] = calendarDiff(a, b, diffYears, addYear);
44
+ a = next;
45
+ if (years) duration.years = years;
46
+ }
47
+ if (!skip.has("months")) {
48
+ const [months, next] = calendarDiff(a, b, diffMonths, addMonth);
49
+ a = next;
50
+ if (months) duration.months = months;
51
+ }
52
+ if (!skip.has("weeks")) {
53
+ const weeks = diffWeeks(a, b);
54
+ a = addDay(a, -(weeks * 7));
55
+ if (weeks) duration.weeks = weeks;
56
+ }
57
+ if (!skip.has("days")) {
58
+ const days = diffDays(a, b);
59
+ a = addDay(a, -days);
60
+ if (days) duration.days = days;
61
+ }
62
+ if (!skip.has("hours")) {
63
+ const hours = diffHours(a, b);
64
+ a = addHour(a, -hours);
65
+ if (hours) duration.hours = hours;
66
+ }
67
+ if (!skip.has("minutes")) {
68
+ const minutes = diffMinutes(a, b);
69
+ a = addMinute(a, -minutes);
70
+ if (minutes) duration.minutes = minutes;
71
+ }
72
+ if (!skip.has("seconds")) {
73
+ const seconds = diffSeconds(a, b);
74
+ a = addSecond(a, -seconds);
75
+ if (seconds) duration.seconds = seconds;
76
+ }
77
+ if (!skip.has("milliseconds")) {
78
+ const ms = diffMilliseconds(a, b);
79
+ if (ms) duration.milliseconds = ms;
80
+ }
81
+ return duration;
82
+ }
83
+ export {
84
+ diff
85
+ };
86
+ //# sourceMappingURL=diff.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/diff.ts"],"sourcesContent":["import { addDay } from \"./addDay\"\nimport { addHour } from \"./addHour\"\nimport { addMinute } from \"./addMinute\"\nimport { addMonth } from \"./addMonth\"\nimport { addSecond } from \"./addSecond\"\nimport { addYear } from \"./addYear\"\nimport { date } from \"./date\"\nimport { diffDays } from \"./diffDays\"\nimport { diffHours } from \"./diffHours\"\nimport { diffMilliseconds } from \"./diffMilliseconds\"\nimport { diffMinutes } from \"./diffMinutes\"\nimport { diffMonths } from \"./diffMonths\"\nimport { diffSeconds } from \"./diffSeconds\"\nimport { diffWeeks } from \"./diffWeeks\"\nimport { diffYears } from \"./diffYears\"\nimport type { DateInput, Duration, MaybeDateInput } from \"./types\"\n\ntype DurationKey = keyof Duration\n\nfunction negateDuration(duration: Duration): Duration {\n const negated: Duration = {}\n for (const unit of Object.keys(duration) as DurationKey[]) {\n negated[unit] = -duration[unit]!\n }\n return negated\n}\n\nfunction calendarDiff(\n current: Date,\n target: Date,\n diffUnit: (dateA: Date, dateB: Date) => number,\n addUnit: (date: Date, count: number) => Date\n): [number, Date] {\n let amount = diffUnit(current, target)\n let next = addUnit(current, -amount)\n while (amount > 0 && next < target) {\n amount--\n next = addUnit(current, -amount)\n }\n return [amount, next]\n}\n\n/**\n * Options for `diff` function\n */\nexport interface DiffOptions {\n /**\n * whether the difference should be absolute (not negative)\n */\n abs?: boolean\n /**\n * units you want to skip, for example weeks\n */\n skip?: DurationKey[] | Set<DurationKey>\n}\n\n/**\n * Returns the difference between 2 dates in an object\n * @param dateA - A date to compare with the right date\n * @param [dateB] - A date to compare with the left date or nothing to compare with the current time\n * @param [options] additional options\n * @param [options.skip] units you want skip\n * @param [options.abs] whether the difference should be absolute\n * @returns an object which could be used with `Intl.DurationFormat.format'`\n */\nexport function diff(\n dateA: DateInput,\n dateB?: MaybeDateInput,\n options?: DiffOptions\n): Duration\n\n/**\n * Returns the difference between 2 dates in an object\n * @param [dateA] - A date to compare with the right date or null to compare with the current time\n * @param dateB - A date to compare with the left date\n * @param [options] additional options\n * @param [options.skip] units you want skip\n * @param [options.abs] whether the difference should be absolute\n * @returns an object which could be used with `Intl.DurationFormat.format'`\n */\nexport function diff(\n dateA: MaybeDateInput,\n dateB: DateInput,\n options?: DiffOptions\n): Duration\n\nexport function diff(\n dateA: MaybeDateInput,\n dateB?: MaybeDateInput,\n options?: DiffOptions\n): Duration {\n let a = date(dateA)\n let b = date(dateB)\n\n if (a < b) {\n const duration = diff(b, a, options)\n return options?.abs ? duration : negateDuration(duration)\n }\n\n const skip = new Set(options?.skip)\n const duration: Duration = {}\n\n if (!skip.has(\"years\")) {\n const [years, next] = calendarDiff(a, b, diffYears, addYear)\n a = next\n if (years) duration.years = years\n }\n\n if (!skip.has(\"months\")) {\n const [months, next] = calendarDiff(a, b, diffMonths, addMonth)\n a = next\n if (months) duration.months = months\n }\n\n if (!skip.has(\"weeks\")) {\n const weeks = diffWeeks(a, b)\n a = addDay(a, -(weeks * 7))\n if (weeks) duration.weeks = weeks\n }\n\n if (!skip.has(\"days\")) {\n const days = diffDays(a, b)\n a = addDay(a, -days)\n if (days) duration.days = days\n }\n\n if (!skip.has(\"hours\")) {\n const hours = diffHours(a, b)\n a = addHour(a, -hours)\n if (hours) duration.hours = hours\n }\n\n if (!skip.has(\"minutes\")) {\n const minutes = diffMinutes(a, b)\n a = addMinute(a, -minutes)\n if (minutes) duration.minutes = minutes\n }\n\n if (!skip.has(\"seconds\")) {\n const seconds = diffSeconds(a, b)\n a = addSecond(a, -seconds)\n if (seconds) duration.seconds = seconds\n }\n\n if (!skip.has(\"milliseconds\")) {\n const ms = diffMilliseconds(a, b)\n // removing ms isn't needed as it's the last\n if (ms) duration.milliseconds = ms\n }\n return duration\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAC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,aAAa,GAAG,GAAG,YAAY,QAAQ;AAC9D,QAAI;AACJ,QAAI,OAAQ,UAAS,SAAS;AAAA,EAChC;AAEA,MAAI,CAAC,KAAK,IAAI,OAAO,GAAG;AACtB,UAAM,QAAQ,UAAU,GAAG,CAAC;AAC5B,QAAI,OAAO,GAAG,EAAE,QAAQ,EAAE;AAC1B,QAAI,MAAO,UAAS,QAAQ;AAAA,EAC9B;AAEA,MAAI,CAAC,KAAK,IAAI,MAAM,GAAG;AACrB,UAAM,OAAO,SAAS,GAAG,CAAC;AAC1B,QAAI,OAAO,GAAG,CAAC,IAAI;AACnB,QAAI,KAAM,UAAS,OAAO;AAAA,EAC5B;AAEA,MAAI,CAAC,KAAK,IAAI,OAAO,GAAG;AACtB,UAAM,QAAQ,UAAU,GAAG,CAAC;AAC5B,QAAI,QAAQ,GAAG,CAAC,KAAK;AACrB,QAAI,MAAO,UAAS,QAAQ;AAAA,EAC9B;AAEA,MAAI,CAAC,KAAK,IAAI,SAAS,GAAG;AACxB,UAAM,UAAU,YAAY,GAAG,CAAC;AAChC,QAAI,UAAU,GAAG,CAAC,OAAO;AACzB,QAAI,QAAS,UAAS,UAAU;AAAA,EAClC;AAEA,MAAI,CAAC,KAAK,IAAI,SAAS,GAAG;AACxB,UAAM,UAAU,YAAY,GAAG,CAAC;AAChC,QAAI,UAAU,GAAG,CAAC,OAAO;AACzB,QAAI,QAAS,UAAS,UAAU;AAAA,EAClC;AAEA,MAAI,CAAC,KAAK,IAAI,cAAc,GAAG;AAC7B,UAAM,KAAK,iBAAiB,GAAG,CAAC;AAEhC,QAAI,GAAI,UAAS,eAAe;AAAA,EAClC;AACA,SAAO;AACT;","names":["duration"]}
@@ -0,0 +1,12 @@
1
+ import { MaybeDateInput } from './types.js';
2
+
3
+ /**
4
+ * Handles date overflow when changing month or year.
5
+ * @param [inputDate] - A string, Date object or null for the current time
6
+ * @param action - The action that changes the month/year
7
+ * @param [dateOverflow] - Whether to allow the date to overflow into another month.
8
+ * @returns A new Date object with the month/year change applied.
9
+ */
10
+ declare function handleOverflow(inputDate: MaybeDateInput | undefined, action: (d: Date) => void, dateOverflow?: boolean): Date;
11
+
12
+ export { handleOverflow };
@@ -0,0 +1,18 @@
1
+ // src/handleDateOverflow.ts
2
+ import { date } from "./date.mjs";
3
+ import { monthDays } from "./monthDays.mjs";
4
+ function handleOverflow(inputDate, action, dateOverflow = false) {
5
+ const d = date(inputDate);
6
+ const dayOfMonth = d.getDate();
7
+ if (!dateOverflow) d.setDate(1);
8
+ action(d);
9
+ if (!dateOverflow) {
10
+ const daysInMonth = monthDays(d);
11
+ d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth);
12
+ }
13
+ return d;
14
+ }
15
+ export {
16
+ handleOverflow
17
+ };
18
+ //# sourceMappingURL=handleDateOverflow.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handleDateOverflow.ts"],"sourcesContent":["import { date } from \"./date\"\nimport { monthDays } from \"./monthDays\"\nimport type { MaybeDateInput } from \"./types\"\n\n/**\n * Handles date overflow when changing month or year.\n * @param [inputDate] - A string, Date object or null for the current time\n * @param action - The action that changes the month/year\n * @param [dateOverflow] - Whether to allow the date to overflow into another month.\n * @returns A new Date object with the month/year change applied.\n */\nexport function handleOverflow(\n inputDate: MaybeDateInput | undefined,\n action: (d: Date) => void,\n dateOverflow = false\n): Date {\n const d = date(inputDate)\n const dayOfMonth = d.getDate()\n // If overflowing is disallowed, set the date back to the first of the month\n if (!dateOverflow) d.setDate(1)\n\n action(d)\n // If overflowing is disallowed, we need to set the date back to the proper\n // day or the last day of the month.\n if (!dateOverflow) {\n const daysInMonth = monthDays(d)\n d.setDate(daysInMonth < dayOfMonth ? daysInMonth : dayOfMonth)\n }\n return d\n}\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAUnB,SAAS,eACd,WACA,QACA,eAAe,OACT;AACN,QAAM,IAAI,KAAK,SAAS;AACxB,QAAM,aAAa,EAAE,QAAQ;AAE7B,MAAI,CAAC,aAAc,GAAE,QAAQ,CAAC;AAE9B,SAAO,CAAC;AAGR,MAAI,CAAC,cAAc;AACjB,UAAM,cAAc,UAAU,CAAC;AAC/B,MAAE,QAAQ,cAAc,aAAa,cAAc,UAAU;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}