UNPKG

@js-temporal/polyfill

Version:

Polyfill for Temporal (https://github.com/tc39/proposal-temporal), an ECMA TC39 Stage 3 proposal

1 lines 639 kB
{"version":3,"file":"index.cjs","sources":["../lib/bigintmath.ts","../lib/slots.ts","../lib/intrinsicclass.ts","../lib/math.ts","../lib/timeduration.ts","../lib/regex.ts","../lib/ecmascript.ts","../lib/calendar.ts","../lib/intl.ts","../lib/instant.ts","../lib/plaindate.ts","../lib/plaindatetime.ts","../lib/duration.ts","../lib/plainmonthday.ts","../lib/now.ts","../lib/plaintime.ts","../lib/plainyearmonth.ts","../lib/zoneddatetime.ts","../lib/legacydate.ts","../lib/index.ts"],"sourcesContent":["import JSBI from 'jsbi';\n\nexport const ZERO = JSBI.BigInt(0);\nexport const ONE = JSBI.BigInt(1);\nexport const TWO = JSBI.BigInt(2);\nexport const TEN = JSBI.BigInt(10);\nconst TWENTY_FOUR = JSBI.BigInt(24);\nconst SIXTY = JSBI.BigInt(60);\nexport const THOUSAND = JSBI.BigInt(1e3);\nexport const MILLION = JSBI.BigInt(1e6);\nexport const BILLION = JSBI.BigInt(1e9);\nconst HOUR_SECONDS = 3600;\nexport const HOUR_NANOS = JSBI.multiply(JSBI.BigInt(HOUR_SECONDS), BILLION);\nexport const MINUTE_NANOS_JSBI = JSBI.multiply(SIXTY, BILLION);\nexport const DAY_NANOS_JSBI = JSBI.multiply(HOUR_NANOS, TWENTY_FOUR);\n\n/** Handle a JSBI or native BigInt. For user input, use ES.ToBigInt instead */\nexport function ensureJSBI(value: JSBI | bigint) {\n return typeof value === 'bigint' ? JSBI.BigInt(value.toString(10)) : value;\n}\n\nexport function isEven(value: JSBI): boolean {\n return JSBI.equal(JSBI.remainder(value, TWO), ZERO);\n}\n\nexport function abs(x: JSBI): JSBI {\n if (JSBI.lessThan(x, ZERO)) return JSBI.unaryMinus(x);\n return x;\n}\n\nexport function compare(x: JSBI, y: JSBI): -1 | 0 | 1 {\n return JSBI.lessThan(x, y) ? -1 : JSBI.greaterThan(x, y) ? 1 : 0;\n}\n\nexport function divmod(x: JSBI, y: JSBI): { quotient: JSBI; remainder: JSBI } {\n const quotient = JSBI.divide(x, y);\n const remainder = JSBI.remainder(x, y);\n return { quotient, remainder };\n}\n","import type JSBI from 'jsbi';\nimport type { Temporal } from '..';\nimport type {\n BuiltinCalendarId,\n AnySlottedType,\n FormatterOrAmender,\n ISODate,\n ISODateTime,\n TimeRecord\n} from './internaltypes';\nimport type { DateTimeFormatImpl } from './intl';\n\n// Instant\nexport const EPOCHNANOSECONDS = 'slot-epochNanoSeconds';\n\n// DateTime, Date, Time, YearMonth, MonthDay\nexport const ISO_DATE = 'slot-iso-date';\nexport const ISO_DATE_TIME = 'slot-iso-date-time';\nexport const TIME = 'slot-time';\nexport const CALENDAR = 'slot-calendar';\n// Date, YearMonth, and MonthDay all have the same slots, disambiguation needed:\nexport const DATE_BRAND = 'slot-date-brand';\nexport const YEAR_MONTH_BRAND = 'slot-year-month-brand';\nexport const MONTH_DAY_BRAND = 'slot-month-day-brand';\n\n// ZonedDateTime\nexport const TIME_ZONE = 'slot-time-zone';\n\n// Duration\nexport const YEARS = 'slot-years';\nexport const MONTHS = 'slot-months';\nexport const WEEKS = 'slot-weeks';\nexport const DAYS = 'slot-days';\nexport const HOURS = 'slot-hours';\nexport const MINUTES = 'slot-minutes';\nexport const SECONDS = 'slot-seconds';\nexport const MILLISECONDS = 'slot-milliseconds';\nexport const MICROSECONDS = 'slot-microseconds';\nexport const NANOSECONDS = 'slot-nanoseconds';\n\n// DateTimeFormatImpl\nexport const DATE = 'date';\nexport const YM = 'ym';\nexport const MD = 'md';\nexport const TIME_FMT = 'time';\nexport const DATETIME = 'datetime';\nexport const INST = 'instant';\nexport const ORIGINAL = 'original';\nexport const TZ_CANONICAL = 'timezone-canonical';\nexport const TZ_ORIGINAL = 'timezone-original';\nexport const CAL_ID = 'calendar-id';\nexport const LOCALE = 'locale';\nexport const OPTIONS = 'options';\n\ninterface SlotInfo<ValueType, UsedByType extends AnySlottedType> {\n value: ValueType;\n usedBy: UsedByType;\n}\n\ninterface SlotInfoRecord {\n [k: string]: SlotInfo<unknown, AnySlottedType>;\n}\n\ninterface Slots extends SlotInfoRecord {\n // Instant\n [EPOCHNANOSECONDS]: SlotInfo<JSBI, Temporal.Instant | Temporal.ZonedDateTime>; // number? JSBI?\n\n // DateTime, Date, Time, YearMonth, MonthDay\n [ISO_DATE]: SlotInfo<ISODate, Temporal.PlainDate | Temporal.PlainMonthDay | Temporal.PlainYearMonth>;\n [ISO_DATE_TIME]: SlotInfo<ISODateTime, Temporal.PlainDateTime>;\n [TIME]: SlotInfo<TimeRecord, Temporal.PlainTime>;\n [CALENDAR]: SlotInfo<BuiltinCalendarId, TypesWithCalendarUnits>;\n\n // Date, YearMonth, MonthDay common slots\n [DATE_BRAND]: SlotInfo<true, Temporal.PlainDate>;\n [YEAR_MONTH_BRAND]: SlotInfo<true, Temporal.PlainYearMonth>;\n [MONTH_DAY_BRAND]: SlotInfo<true, Temporal.PlainMonthDay>;\n\n // ZonedDateTime\n [TIME_ZONE]: SlotInfo<string, Temporal.ZonedDateTime>;\n\n // Duration\n [YEARS]: SlotInfo<number, Temporal.Duration>;\n [MONTHS]: SlotInfo<number, Temporal.Duration>;\n [WEEKS]: SlotInfo<number, Temporal.Duration>;\n [DAYS]: SlotInfo<number, Temporal.Duration>;\n [HOURS]: SlotInfo<number, Temporal.Duration>;\n [MINUTES]: SlotInfo<number, Temporal.Duration>;\n [SECONDS]: SlotInfo<number, Temporal.Duration>;\n [MILLISECONDS]: SlotInfo<number, Temporal.Duration>;\n [MICROSECONDS]: SlotInfo<number, Temporal.Duration>;\n [NANOSECONDS]: SlotInfo<number, Temporal.Duration>;\n\n // DateTimeFormatImpl\n [DATE]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [YM]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [MD]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [TIME_FMT]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [DATETIME]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [INST]: SlotInfo<FormatterOrAmender, DateTimeFormatImpl>;\n [ORIGINAL]: SlotInfo<globalThis.Intl.DateTimeFormat, DateTimeFormatImpl>;\n [TZ_CANONICAL]: SlotInfo<string, DateTimeFormatImpl>;\n [TZ_ORIGINAL]: SlotInfo<string, DateTimeFormatImpl>;\n [CAL_ID]: SlotInfo<globalThis.Intl.ResolvedDateTimeFormatOptions['calendar'], DateTimeFormatImpl>;\n [LOCALE]: SlotInfo<globalThis.Intl.ResolvedDateTimeFormatOptions['locale'], DateTimeFormatImpl>;\n [OPTIONS]: SlotInfo<Intl.DateTimeFormatOptions, DateTimeFormatImpl>;\n}\n\ntype TypesWithCalendarUnits =\n | Temporal.PlainDateTime\n | Temporal.PlainDate\n | Temporal.PlainYearMonth\n | Temporal.PlainMonthDay\n | Temporal.ZonedDateTime;\n\ninterface SlotsToTypes {\n // Instant\n [EPOCHNANOSECONDS]: Temporal.Instant;\n\n // DateTime, Date, Time, YearMonth, MonthDay\n [ISO_DATE]: Temporal.PlainDate | Temporal.PlainYearMonth | Temporal.PlainMonthDay;\n [ISO_DATE_TIME]: Temporal.PlainDateTime;\n [TIME]: Temporal.PlainTime;\n [CALENDAR]: TypesWithCalendarUnits;\n\n // Date, YearMonth, MonthDay common slots\n [DATE_BRAND]: Temporal.PlainDate;\n [YEAR_MONTH_BRAND]: Temporal.PlainYearMonth;\n [MONTH_DAY_BRAND]: Temporal.PlainMonthDay;\n\n // ZonedDateTime\n [TIME_ZONE]: Temporal.ZonedDateTime;\n\n // Duration\n [YEARS]: Temporal.Duration;\n [MONTHS]: Temporal.Duration;\n [WEEKS]: Temporal.Duration;\n [DAYS]: Temporal.Duration;\n [HOURS]: Temporal.Duration;\n [MINUTES]: Temporal.Duration;\n [SECONDS]: Temporal.Duration;\n [MILLISECONDS]: Temporal.Duration;\n [MICROSECONDS]: Temporal.Duration;\n [NANOSECONDS]: Temporal.Duration;\n\n // DateTimeFormatImpl\n [DATE]: DateTimeFormatImpl;\n [YM]: DateTimeFormatImpl;\n [MD]: DateTimeFormatImpl;\n [TIME_FMT]: DateTimeFormatImpl;\n [DATETIME]: DateTimeFormatImpl;\n [INST]: DateTimeFormatImpl;\n [ORIGINAL]: DateTimeFormatImpl;\n [TZ_CANONICAL]: DateTimeFormatImpl;\n [TZ_ORIGINAL]: DateTimeFormatImpl;\n [CAL_ID]: DateTimeFormatImpl;\n [LOCALE]: DateTimeFormatImpl;\n [OPTIONS]: DateTimeFormatImpl;\n}\n\ntype SlotKey = keyof SlotsToTypes;\n\nconst globalSlots = new WeakMap<Slots[keyof Slots]['usedBy'], Record<keyof Slots, Slots[keyof Slots]['value']>>();\n\nfunction _GetSlots(container: Slots[keyof Slots]['usedBy']) {\n return globalSlots.get(container);\n}\n\nconst GetSlotsSymbol = Symbol.for('@@Temporal__GetSlots');\n\n// expose GetSlots to avoid dual package hazards\n(globalThis as any)[GetSlotsSymbol] ||= _GetSlots;\n\nconst GetSlots = (globalThis as any)[GetSlotsSymbol] as typeof _GetSlots;\n\nfunction _CreateSlots(container: Slots[keyof Slots]['usedBy']): void {\n globalSlots.set(container, Object.create(null));\n}\n\nconst CreateSlotsSymbol = Symbol.for('@@Temporal__CreateSlots');\n\n// expose CreateSlots to avoid dual package hazards\n(globalThis as any)[CreateSlotsSymbol] ||= _CreateSlots;\n\nexport const CreateSlots = (globalThis as any)[CreateSlotsSymbol] as typeof _CreateSlots;\n\n// TODO: is there a better way than 9 overloads to make HasSlot into a type\n// guard that takes a variable number of parameters?\nexport function HasSlot<ID1 extends SlotKey>(container: unknown, id1: ID1): container is Slots[ID1]['usedBy'];\nexport function HasSlot<ID1 extends SlotKey, ID2 extends SlotKey>(\n container: unknown,\n id1: ID1,\n id2: ID2\n): container is Slots[ID1]['usedBy'] | Slots[ID2]['usedBy'];\nexport function HasSlot<ID1 extends SlotKey, ID2 extends SlotKey, ID3 extends SlotKey>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3\n): container is Slots[ID1]['usedBy'] | Slots[ID2]['usedBy'] | Slots[ID3]['usedBy'];\nexport function HasSlot<ID1 extends SlotKey, ID2 extends SlotKey, ID3 extends SlotKey, ID4 extends SlotKey>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4\n): container is Slots[ID1 | ID2 | ID3 | ID4]['usedBy'];\nexport function HasSlot<\n ID1 extends SlotKey,\n ID2 extends SlotKey,\n ID3 extends SlotKey,\n ID4 extends SlotKey,\n ID5 extends SlotKey\n>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4,\n id5: ID5\n): container is Slots[ID1 | ID2 | ID3 | ID4 | ID5]['usedBy'];\nexport function HasSlot<\n ID1 extends SlotKey,\n ID2 extends SlotKey,\n ID3 extends SlotKey,\n ID4 extends SlotKey,\n ID5 extends SlotKey,\n ID6 extends SlotKey\n>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4,\n id5: ID5,\n id6: ID6\n): container is Slots[ID1 | ID2 | ID3 | ID4 | ID5 | ID6]['usedBy'];\nexport function HasSlot<\n ID1 extends SlotKey,\n ID2 extends SlotKey,\n ID3 extends SlotKey,\n ID4 extends SlotKey,\n ID5 extends SlotKey,\n ID6 extends SlotKey,\n ID7 extends SlotKey\n>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4,\n id5: ID5,\n id6: ID6,\n id7: ID7\n): container is Slots[ID1 | ID2 | ID3 | ID4 | ID5 | ID6 | ID7]['usedBy'];\nexport function HasSlot<\n ID1 extends SlotKey,\n ID2 extends SlotKey,\n ID3 extends SlotKey,\n ID4 extends SlotKey,\n ID5 extends SlotKey,\n ID6 extends SlotKey,\n ID7 extends SlotKey,\n ID8 extends SlotKey\n>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4,\n id5: ID5,\n id6: ID6,\n id7: ID7,\n id8: ID8\n): container is Slots[ID1 | ID2 | ID3 | ID4 | ID5 | ID6 | ID7 | ID8]['usedBy'];\nexport function HasSlot<\n ID1 extends SlotKey,\n ID2 extends SlotKey,\n ID3 extends SlotKey,\n ID4 extends SlotKey,\n ID5 extends SlotKey,\n ID6 extends SlotKey,\n ID7 extends SlotKey,\n ID8 extends SlotKey,\n ID9 extends SlotKey\n>(\n container: unknown,\n id1: ID1,\n id2: ID2,\n id3: ID3,\n id4: ID4,\n id5: ID5,\n id6: ID6,\n id7: ID7,\n id8: ID8,\n id9: ID9\n): container is Slots[ID1 | ID2 | ID3 | ID4 | ID5 | ID6 | ID7 | ID8 | ID9]['usedBy'];\nexport function HasSlot(container: unknown, ...ids: (keyof Slots)[]): boolean {\n if (!container || 'object' !== typeof container) return false;\n const myslots = GetSlots(container as AnySlottedType);\n return !!myslots && ids.every((id) => id in myslots);\n}\nexport function GetSlot<KeyT extends keyof Slots>(\n container: Slots[typeof id]['usedBy'],\n id: KeyT\n): Slots[KeyT]['value'] {\n const value = GetSlots(container)?.[id];\n if (value === undefined) throw new TypeError(`Missing internal slot ${id}`);\n return value;\n}\nexport function SetSlot<KeyT extends SlotKey>(\n container: Slots[KeyT]['usedBy'],\n id: KeyT,\n value: Slots[KeyT]['value']\n): void {\n const slots = GetSlots(container);\n\n if (slots === undefined) throw new TypeError('Missing slots for the given container');\n\n const existingSlot = slots[id];\n\n if (existingSlot) throw new TypeError(`${id} already has set`);\n\n slots[id] = value;\n}\n\nexport function ResetSlot<KeyT extends SlotKey>(\n container: DateTimeFormatImpl,\n id: KeyT,\n value: Slots[KeyT]['value']\n): void {\n const slots = GetSlots(container);\n\n if (slots === undefined) throw new TypeError('Missing slots for the given container');\n\n const existingSlot = slots[id];\n\n if (existingSlot === undefined) throw new TypeError(`tried to reset ${id} which was not set`);\n\n slots[id] = value;\n}\n","import type JSBI from 'jsbi';\nimport type { Temporal } from '..';\nimport type { CalendarImpl } from './calendar';\nimport type { BuiltinCalendarId } from './internaltypes';\nimport type { DateTimeFormatImpl } from './intl';\n\nimport { DEBUG } from './debug';\nimport { GetSlot, ORIGINAL } from './slots';\n\ntype OmitConstructor<T> = { [P in keyof T as T[P] extends new (...args: any[]) => any ? P : never]: T[P] };\n\ntype TemporalIntrinsics = {\n ['Intl.DateTimeFormat']: typeof globalThis.Intl.DateTimeFormat;\n ['Temporal.Duration']: typeof Temporal.Duration;\n ['Temporal.Instant']: OmitConstructor<Temporal.Instant> &\n (new (epochNanoseconds: JSBI) => Temporal.Instant) & { prototype: typeof Temporal.Instant.prototype };\n ['Temporal.PlainDate']: typeof Temporal.PlainDate;\n ['Temporal.PlainDateTime']: typeof Temporal.PlainDateTime;\n ['Temporal.PlainMonthDay']: typeof Temporal.PlainMonthDay;\n ['Temporal.PlainTime']: typeof Temporal.PlainTime;\n ['Temporal.PlainYearMonth']: typeof Temporal.PlainYearMonth;\n ['Temporal.ZonedDateTime']: OmitConstructor<Temporal.ZonedDateTime> &\n (new (epochNanoseconds: JSBI, timeZone: string, calendar?: string) => Temporal.ZonedDateTime) & {\n prototype: typeof Temporal.ZonedDateTime.prototype;\n from: typeof Temporal.ZonedDateTime.from;\n compare: typeof Temporal.ZonedDateTime.compare;\n };\n};\ntype TemporalIntrinsicRegistrations = {\n [key in keyof TemporalIntrinsics]: TemporalIntrinsics[key];\n};\ntype TemporalIntrinsicPrototypeRegistrations = {\n [key in keyof TemporalIntrinsics as `${key}.prototype`]: TemporalIntrinsics[key]['prototype'];\n};\ntype TemporalIntrinsicRegisteredKeys = {\n [key in keyof TemporalIntrinsicRegistrations as `%${key}%`]: TemporalIntrinsicRegistrations[key];\n};\ntype TemporalIntrinsicPrototypeRegisteredKeys = {\n [key in keyof TemporalIntrinsicPrototypeRegistrations as `%${key}%`]: TemporalIntrinsicPrototypeRegistrations[key];\n};\n\ntype OtherIntrinsics = {\n calendarImpl: (id: BuiltinCalendarId) => CalendarImpl;\n};\ntype OtherIntrinsicKeys = { [key in keyof OtherIntrinsics as `%${key}%`]: OtherIntrinsics[key] };\n\nconst INTRINSICS = {} as TemporalIntrinsicRegisteredKeys &\n TemporalIntrinsicPrototypeRegisteredKeys &\n OtherIntrinsicKeys;\n\ntype StylizeOption = (value: unknown, type: 'number' | 'special') => string;\n\ntype customFormatFunction<T> = (\n this: T & { _repr_: string }, // _repr_ is present if DEBUG\n depth: number,\n options: { stylize: StylizeOption },\n inspect: (object: T, options?: { depth: number; stylize: StylizeOption }) => string\n) => string;\nconst customUtilInspectFormatters: Partial<{\n [key in keyof TemporalIntrinsicRegistrations]: customFormatFunction<\n InstanceType<TemporalIntrinsicRegistrations[key]>\n >;\n}> = {\n ['Intl.DateTimeFormat'](depth, options, inspect) {\n return inspect(GetSlot(this as DateTimeFormatImpl, ORIGINAL), { depth, ...options });\n },\n ['Temporal.Duration'](depth, options) {\n const descr = options.stylize(this._repr_, 'special');\n if (depth < 1) return descr;\n const entries: string[] = [];\n const props = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds'\n ] as const;\n for (let i = 0; i < props.length; i++) {\n const prop = props[i];\n if (this[prop] !== 0) {\n entries.push(` ${prop}: ${options.stylize(this[prop], 'number')}`);\n }\n }\n return descr + ' {\\n' + entries.join(',\\n') + '\\n}';\n }\n};\n\ntype InspectFormatterOptions = { stylize: (str: string, styleType: string) => string };\nfunction defaultUtilInspectFormatter(this: any, depth: number, options: InspectFormatterOptions) {\n return options.stylize(this._repr_, 'special');\n}\n\nexport function MakeIntrinsicClass(\n Class: TemporalIntrinsicRegistrations[typeof name],\n name: keyof TemporalIntrinsicRegistrations\n) {\n Object.defineProperty(Class.prototype, Symbol.toStringTag, {\n value: name,\n writable: false,\n enumerable: false,\n configurable: true\n });\n if (DEBUG) {\n Object.defineProperty(Class.prototype, Symbol.for('nodejs.util.inspect.custom'), {\n value: customUtilInspectFormatters[name] || defaultUtilInspectFormatter,\n writable: false,\n enumerable: false,\n configurable: true\n });\n }\n const staticNames = Object.getOwnPropertyNames(Class);\n for (let i = 0; i < staticNames.length; i++) {\n const prop = staticNames[i];\n // we know that `prop` is present, so the descriptor is never undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const desc = Object.getOwnPropertyDescriptor(Class, prop)!;\n if (!desc.configurable || !desc.enumerable) continue;\n desc.enumerable = false;\n Object.defineProperty(Class, prop, desc);\n }\n const protoNames = Object.getOwnPropertyNames(Class.prototype);\n for (let i = 0; i < protoNames.length; i++) {\n const prop = protoNames[i];\n // we know that `prop` is present, so the descriptor is never undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const desc = Object.getOwnPropertyDescriptor(Class.prototype, prop)!;\n if (!desc.configurable || !desc.enumerable) continue;\n desc.enumerable = false;\n Object.defineProperty(Class.prototype, prop, desc);\n }\n\n DefineIntrinsic(name, Class);\n DefineIntrinsic(`${name}.prototype`, Class.prototype);\n}\n\ntype IntrinsicDefinitionKeys =\n | keyof TemporalIntrinsicRegistrations\n | keyof TemporalIntrinsicPrototypeRegistrations\n | keyof OtherIntrinsics;\nexport function DefineIntrinsic<KeyT extends keyof TemporalIntrinsicRegistrations>(\n name: KeyT,\n value: TemporalIntrinsicRegistrations[KeyT]\n): void;\nexport function DefineIntrinsic<KeyT extends keyof TemporalIntrinsicPrototypeRegistrations>(\n name: KeyT,\n value: TemporalIntrinsicPrototypeRegistrations[KeyT]\n): void;\nexport function DefineIntrinsic<KeyT extends keyof OtherIntrinsics>(name: KeyT, value: OtherIntrinsics[KeyT]): void;\nexport function DefineIntrinsic<KeyT>(name: KeyT, value: never): void;\nexport function DefineIntrinsic<KeyT extends IntrinsicDefinitionKeys>(name: KeyT, value: unknown): void {\n const key: `%${IntrinsicDefinitionKeys}%` = `%${name}%`;\n if (INTRINSICS[key] !== undefined) throw new Error(`intrinsic ${name} already exists`);\n INTRINSICS[key] = value;\n}\nexport function GetIntrinsic<KeyT extends keyof typeof INTRINSICS>(intrinsic: KeyT): (typeof INTRINSICS)[KeyT] {\n return INTRINSICS[intrinsic];\n}\n","import type JSBI from 'jsbi';\nimport type { Temporal } from '..';\n\n// Computes trunc(x / 10**p) and x % 10**p, returning { div, mod }, with\n// precision loss only once in the quotient, by string manipulation. If the\n// quotient and remainder are safe integers, then they are exact. x must be an\n// integer. p must be a non-negative integer. Both div and mod have the sign of\n// x.\nexport function TruncatingDivModByPowerOf10(xParam: number, p: number) {\n let x = xParam;\n if (x === 0) return { div: x, mod: x }; // preserves signed zero\n\n const sign = Math.sign(x);\n x = Math.abs(x);\n\n const xDigits = Math.trunc(1 + Math.log10(x));\n if (p >= xDigits) return { div: sign * 0, mod: sign * x };\n if (p === 0) return { div: sign * x, mod: sign * 0 };\n\n // would perform nearest rounding if x was not an integer:\n const xStr = x.toPrecision(xDigits);\n const div = sign * Number.parseInt(xStr.slice(0, xDigits - p), 10);\n const mod = sign * Number.parseInt(xStr.slice(xDigits - p), 10);\n\n return { div, mod };\n}\n\n// Computes x * 10**p + z with precision loss only at the end, by string\n// manipulation. If the result is a safe integer, then it is exact. x must be\n// an integer. p must be a non-negative integer. z must have the same sign as\n// x and be less than 10**p.\nexport function FMAPowerOf10(xParam: number, p: number, zParam: number) {\n let x = xParam;\n let z = zParam;\n if (x === 0) return z;\n\n const sign = Math.sign(x) || Math.sign(z);\n x = Math.abs(x);\n z = Math.abs(z);\n\n const xStr = x.toPrecision(Math.trunc(1 + Math.log10(x)));\n\n if (z === 0) return sign * Number.parseInt(xStr + '0'.repeat(p), 10);\n\n const zStr = z.toPrecision(Math.trunc(1 + Math.log10(z)));\n\n const resStr = xStr + zStr.padStart(p, '0');\n return sign * Number.parseInt(resStr, 10);\n}\n\ntype UnsignedRoundingMode = 'half-even' | 'half-infinity' | 'half-zero' | 'infinity' | 'zero';\n\nexport function GetUnsignedRoundingMode(\n mode: Temporal.RoundingMode,\n sign: 'positive' | 'negative'\n): UnsignedRoundingMode {\n const isNegative = sign === 'negative';\n switch (mode) {\n case 'ceil':\n return isNegative ? 'zero' : 'infinity';\n case 'floor':\n return isNegative ? 'infinity' : 'zero';\n case 'expand':\n return 'infinity';\n case 'trunc':\n return 'zero';\n case 'halfCeil':\n return isNegative ? 'half-zero' : 'half-infinity';\n case 'halfFloor':\n return isNegative ? 'half-infinity' : 'half-zero';\n case 'halfExpand':\n return 'half-infinity';\n case 'halfTrunc':\n return 'half-zero';\n case 'halfEven':\n return 'half-even';\n }\n}\n\n// Omits first step from spec algorithm so that it can be used both for\n// RoundNumberToIncrement and RoundTimeDurationToIncrement\nexport function ApplyUnsignedRoundingMode<T extends number | JSBI>(\n r1: T,\n r2: T,\n cmp: -1 | 0 | 1,\n evenCardinality: boolean,\n unsignedRoundingMode: UnsignedRoundingMode\n) {\n if (unsignedRoundingMode === 'zero') return r1;\n if (unsignedRoundingMode === 'infinity') return r2;\n if (cmp < 0) return r1;\n if (cmp > 0) return r2;\n if (unsignedRoundingMode === 'half-zero') return r1;\n if (unsignedRoundingMode === 'half-infinity') return r2;\n return evenCardinality ? r1 : r2;\n}\n","import JSBI from 'jsbi';\n\nimport { assert } from './assert';\nimport {\n abs,\n BILLION,\n compare,\n DAY_NANOS_JSBI,\n divmod,\n ensureJSBI,\n HOUR_NANOS,\n isEven,\n MILLION,\n MINUTE_NANOS_JSBI,\n ONE,\n TEN,\n THOUSAND,\n TWO,\n ZERO\n} from './bigintmath';\nimport { ApplyUnsignedRoundingMode, GetUnsignedRoundingMode } from './math';\nimport type { Temporal } from '..';\n\nexport class TimeDuration {\n static MAX = JSBI.BigInt('9007199254740991999999999');\n static ZERO = new TimeDuration(ZERO);\n\n totalNs: JSBI;\n sec: number;\n subsec: number;\n\n constructor(totalNs: bigint | JSBI) {\n assert(typeof totalNs !== 'number', 'big integer required');\n this.totalNs = ensureJSBI(totalNs);\n assert(JSBI.lessThanOrEqual(abs(this.totalNs), TimeDuration.MAX), 'integer too big');\n\n this.sec = JSBI.toNumber(JSBI.divide(this.totalNs, BILLION));\n this.subsec = JSBI.toNumber(JSBI.remainder(this.totalNs, BILLION));\n assert(Number.isSafeInteger(this.sec), 'seconds too big');\n assert(Math.abs(this.subsec) <= 999_999_999, 'subseconds too big');\n }\n\n static validateNew(totalNs: JSBI, operation: string) {\n if (JSBI.greaterThan(abs(totalNs), TimeDuration.MAX)) {\n throw new RangeError(`${operation} of duration time units cannot exceed ${TimeDuration.MAX} s`);\n }\n return new TimeDuration(totalNs);\n }\n\n static fromEpochNsDiff(epochNs1: JSBI | bigint, epochNs2: JSBI | bigint) {\n const diff = JSBI.subtract(ensureJSBI(epochNs1), ensureJSBI(epochNs2));\n // No extra validate step. Should instead fail assertion if too big\n return new TimeDuration(diff);\n }\n\n static fromComponents(h: number, min: number, s: number, ms: number, µs: number, ns: number) {\n const totalNs = JSBI.add(\n JSBI.add(\n JSBI.add(\n JSBI.add(\n JSBI.add(JSBI.BigInt(ns), JSBI.multiply(JSBI.BigInt(µs), THOUSAND)),\n JSBI.multiply(JSBI.BigInt(ms), MILLION)\n ),\n JSBI.multiply(JSBI.BigInt(s), BILLION)\n ),\n JSBI.multiply(JSBI.BigInt(min), MINUTE_NANOS_JSBI)\n ),\n JSBI.multiply(JSBI.BigInt(h), HOUR_NANOS)\n );\n return TimeDuration.validateNew(totalNs, 'total');\n }\n\n abs() {\n return new TimeDuration(abs(this.totalNs));\n }\n\n add(other: TimeDuration) {\n return TimeDuration.validateNew(JSBI.add(this.totalNs, other.totalNs), 'sum');\n }\n\n add24HourDays(days: number) {\n assert(Number.isInteger(days), 'days must be an integer');\n return TimeDuration.validateNew(JSBI.add(this.totalNs, JSBI.multiply(JSBI.BigInt(days), DAY_NANOS_JSBI)), 'sum');\n }\n\n addToEpochNs(epochNs: JSBI | bigint) {\n return JSBI.add(ensureJSBI(epochNs), this.totalNs);\n }\n\n cmp(other: TimeDuration) {\n return compare(this.totalNs, other.totalNs);\n }\n\n divmod(n: number) {\n assert(n !== 0, 'division by zero');\n const { quotient, remainder } = divmod(this.totalNs, JSBI.BigInt(n));\n const q = JSBI.toNumber(quotient);\n const r = new TimeDuration(remainder);\n return { quotient: q, remainder: r };\n }\n\n fdiv(nParam: JSBI | bigint) {\n const n = ensureJSBI(nParam);\n assert(!JSBI.equal(n, ZERO), 'division by zero');\n const nBigInt = JSBI.BigInt(n);\n let { quotient, remainder } = divmod(this.totalNs, nBigInt);\n\n // Perform long division to calculate the fractional part of the quotient\n // remainder / n with more accuracy than 64-bit floating point division\n const precision = 50;\n const decimalDigits: number[] = [];\n let digit;\n const sign = (JSBI.lessThan(this.totalNs, ZERO) ? -1 : 1) * Math.sign(JSBI.toNumber(n));\n while (!JSBI.equal(remainder, ZERO) && decimalDigits.length < precision) {\n remainder = JSBI.multiply(remainder, TEN);\n ({ quotient: digit, remainder } = divmod(remainder, nBigInt));\n decimalDigits.push(Math.abs(JSBI.toNumber(digit)));\n }\n return sign * Number(abs(quotient).toString() + '.' + decimalDigits.join(''));\n }\n\n isZero() {\n return JSBI.equal(this.totalNs, ZERO);\n }\n\n round(incrementParam: JSBI | bigint, mode: Temporal.RoundingMode) {\n const increment = ensureJSBI(incrementParam);\n if (JSBI.equal(increment, ONE)) return this;\n const { quotient, remainder } = divmod(this.totalNs, increment);\n const sign = JSBI.lessThan(this.totalNs, ZERO) ? 'negative' : 'positive';\n const r1 = JSBI.multiply(abs(quotient), increment);\n const r2 = JSBI.add(r1, increment);\n const cmp = compare(abs(JSBI.multiply(remainder, TWO)), increment);\n const unsignedRoundingMode = GetUnsignedRoundingMode(mode, sign);\n const rounded = JSBI.equal(abs(this.totalNs), r1)\n ? r1\n : ApplyUnsignedRoundingMode(r1, r2, cmp, isEven(quotient), unsignedRoundingMode);\n const result = sign === 'positive' ? rounded : JSBI.unaryMinus(rounded);\n return TimeDuration.validateNew(result, 'rounding');\n }\n\n sign() {\n return this.cmp(new TimeDuration(ZERO));\n }\n\n subtract(other: TimeDuration) {\n return TimeDuration.validateNew(JSBI.subtract(this.totalNs, other.totalNs), 'difference');\n }\n}\n","const offsetIdentifierNoCapture = /(?:[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)/;\nconst tzComponent = /[A-Za-z._][A-Za-z._0-9+-]*/;\nexport const timeZoneID = new RegExp(\n `(?:${offsetIdentifierNoCapture.source}|(?:${tzComponent.source})(?:\\\\/(?:${tzComponent.source}))*)`\n);\n\nconst yearpart = /(?:[+-]\\d{6}|\\d{4})/;\nconst monthpart = /(?:0[1-9]|1[0-2])/;\nconst daypart = /(?:0[1-9]|[12]\\d|3[01])/;\nconst datesplit = new RegExp(\n `(${yearpart.source})(?:-(${monthpart.source})-(${daypart.source})|(${monthpart.source})(${daypart.source}))`\n);\nconst timesplit = /(\\d{2})(?::(\\d{2})(?::(\\d{2})(?:[.,](\\d{1,9}))?)?|(\\d{2})(?:(\\d{2})(?:[.,](\\d{1,9}))?)?)?/;\nexport const offsetWithParts = /([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])(?::?([0-5][0-9])(?:[.,](\\d{1,9}))?)?)?/;\nexport const offset = /((?:[+-])(?:[01][0-9]|2[0-3])(?::?(?:[0-5][0-9])(?::?(?:[0-5][0-9])(?:[.,](?:\\d{1,9}))?)?)?)/;\nconst offsetpart = new RegExp(`([zZ])|${offset.source}?`);\nexport const offsetIdentifier = /([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])?)?/;\nexport const annotation = /\\[(!)?([a-z_][a-z0-9_-]*)=([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)\\]/g;\n\nexport const zoneddatetime = new RegExp(\n [\n `^${datesplit.source}`,\n `(?:(?:[tT]|\\\\s+)${timesplit.source}(?:${offsetpart.source})?)?`,\n `(?:\\\\[!?(${timeZoneID.source})\\\\])?`,\n `((?:${annotation.source})*)$`\n ].join('')\n);\n\nexport const time = new RegExp(\n [\n `^[tT]?${timesplit.source}`,\n `(?:${offsetpart.source})?`,\n `(?:\\\\[!?${timeZoneID.source}\\\\])?`,\n `((?:${annotation.source})*)$`\n ].join('')\n);\n\n// The short forms of YearMonth and MonthDay are only for the ISO calendar, but\n// annotations are still allowed, and will throw if the calendar annotation is\n// not ISO.\n// Non-ISO calendar YearMonth and MonthDay have to parse as a Temporal.PlainDate,\n// with the reference fields.\n// YYYYMM forbidden by ISO 8601 because ambiguous with YYMMDD, but allowed by\n// RFC 3339 and we don't allow 2-digit years, so we allow it.\n// Not ambiguous with HHMMSS because that requires a 'T' prefix\n// UTC offsets are not allowed, because they are not allowed with any date-only\n// format; also, YYYY-MM-UU is ambiguous with YYYY-MM-DD\nexport const yearmonth = new RegExp(\n `^(${yearpart.source})-?(${monthpart.source})(?:\\\\[!?${timeZoneID.source}\\\\])?((?:${annotation.source})*)$`\n);\nexport const monthday = new RegExp(\n `^(?:--)?(${monthpart.source})-?(${daypart.source})(?:\\\\[!?${timeZoneID.source}\\\\])?((?:${annotation.source})*)$`\n);\n\nconst fraction = /(\\d+)(?:[.,](\\d{1,9}))?/;\n\nconst durationDate = /(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?/;\nconst durationTime = new RegExp(`(?:${fraction.source}H)?(?:${fraction.source}M)?(?:${fraction.source}S)?`);\nexport const duration = new RegExp(`^([+-])?P${durationDate.source}(?:T(?!$)${durationTime.source})?$`, 'i');\n","import { DEBUG, ENABLE_ASSERTS } from './debug';\nimport JSBI from 'jsbi';\n\nimport type { Temporal } from '..';\nimport { assert, assertNotReached } from './assert';\nimport { abs, compare, DAY_NANOS_JSBI, divmod, ensureJSBI, isEven, MILLION, ONE, TWO, ZERO } from './bigintmath';\nimport type { CalendarImpl } from './calendar';\nimport type {\n AnyTemporalLikeType,\n UnitSmallerThanOrEqualTo,\n InstantParams,\n PlainMonthDayParams,\n ZonedDateTimeParams,\n PlainDateParams,\n PlainTimeParams,\n DurationParams,\n PlainDateTimeParams,\n PlainYearMonthParams,\n BuiltinCalendarId,\n Keys,\n AnyTemporalKey,\n FieldKey,\n InternalDuration,\n ISODateTime,\n ISODate,\n TimeRecord,\n ISODateToFieldsType,\n DateDuration,\n CalendarFieldsRecord,\n MonthDayFromFieldsObject,\n Overflow,\n Resolve,\n AnySlottedType\n} from './internaltypes';\nimport { GetIntrinsic } from './intrinsicclass';\nimport { ApplyUnsignedRoundingMode, FMAPowerOf10, GetUnsignedRoundingMode, TruncatingDivModByPowerOf10 } from './math';\nimport { TimeDuration } from './timeduration';\nimport {\n CreateSlots,\n GetSlot,\n HasSlot,\n SetSlot,\n EPOCHNANOSECONDS,\n ISO_DATE,\n ISO_DATE_TIME,\n TIME,\n DATE_BRAND,\n YEAR_MONTH_BRAND,\n MONTH_DAY_BRAND,\n TIME_ZONE,\n CALENDAR,\n YEARS,\n MONTHS,\n WEEKS,\n DAYS,\n HOURS,\n MINUTES,\n SECONDS,\n MILLISECONDS,\n MICROSECONDS,\n NANOSECONDS\n} from './slots';\n\nconst DAY_MS = 86400_000;\nexport const DAY_NANOS = DAY_MS * 1e6;\nconst MINUTE_NANOS = 60e9;\n// Instant range is 100 million days (inclusive) before or after epoch.\nconst MS_MAX = DAY_MS * 1e8;\nconst NS_MAX = epochMsToNs(MS_MAX);\nconst NS_MIN = JSBI.unaryMinus(NS_MAX);\n// PlainDateTime range is 24 hours wider (exclusive) than the Instant range on\n// both ends, to allow for valid Instant=>PlainDateTime conversion for all\n// built-in time zones (whose offsets must have a magnitude less than 24 hours).\nconst DATETIME_NS_MIN = JSBI.add(JSBI.subtract(NS_MIN, DAY_NANOS_JSBI), ONE);\nconst DATETIME_NS_MAX = JSBI.subtract(JSBI.add(NS_MAX, DAY_NANOS_JSBI), ONE);\n// The pattern of leap years in the ISO 8601 calendar repeats every 400 years.\n// The constant below is the number of nanoseconds in 400 years. It is used to\n// avoid overflows when dealing with values at the edge legacy Date's range.\nconst MS_IN_400_YEAR_CYCLE = (400 * 365 + 97) * DAY_MS;\nconst YEAR_MIN = -271821;\nconst YEAR_MAX = 275760;\nconst BEFORE_FIRST_DST = Date.UTC(1847, 0, 1); // 1847-01-01T00:00:00Z\n\nconst BUILTIN_CALENDAR_IDS = [\n 'iso8601',\n 'hebrew',\n 'islamic',\n 'islamic-umalqura',\n 'islamic-tbla',\n 'islamic-civil',\n 'islamic-rgsa',\n 'islamicc',\n 'persian',\n 'ethiopic',\n 'ethioaa',\n 'ethiopic-amete-alem',\n 'coptic',\n 'chinese',\n 'dangi',\n 'roc',\n 'indian',\n 'buddhist',\n 'japanese',\n 'gregory'\n];\n\nconst ICU_LEGACY_TIME_ZONE_IDS = new Set([\n 'ACT',\n 'AET',\n 'AGT',\n 'ART',\n 'AST',\n 'BET',\n 'BST',\n 'CAT',\n 'CNT',\n 'CST',\n 'CTT',\n 'EAT',\n 'ECT',\n 'IET',\n 'IST',\n 'JST',\n 'MIT',\n 'NET',\n 'NST',\n 'PLT',\n 'PNT',\n 'PRT',\n 'PST',\n 'SST',\n 'VST'\n]);\n\n/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function */\n/**\n * uncheckedAssertNarrowedType forces TypeScript to change the type of the argument to the one given in\n * the type parameter. This should only be used to help TS understand when variables change types,\n * but TS can't or won't infer this automatically. They should be used sparingly, because\n * if used incorrectly can lead to difficult-to-diagnose problems.\n * */\nexport function uncheckedAssertNarrowedType<T = unknown>(\n arg: unknown,\n justification: string\n): asserts arg is T extends typeof arg ? T : never {}\n/* eslint-enable */\n\n/**\n * In debug builds, this function verifies that the given argument \"exists\" (is not\n * null or undefined). This function becomes a no-op in the final bundles distributed via NPM.\n * @param arg\n */\nexport function assertExists<A>(arg: A): asserts arg is NonNullable<A> {\n if (ENABLE_ASSERTS) {\n if (arg == null) {\n throw new Error('Expected arg to be set.');\n }\n }\n}\n\n/** Similar to assertExists, but returns the argument. */\nfunction castExists<A>(arg: A): NonNullable<A> {\n assertExists(arg);\n return arg;\n}\n\n// For unknown values, this narrows the result to a Record. But for union types\n// like `Temporal.DurationLike | string`, it'll strip the primitive types while\n// leaving the object type(s) unchanged.\nexport function IsObject<T>(\n value: T\n): value is Exclude<T, string | null | undefined | number | bigint | symbol | boolean>;\nexport function IsObject(value: unknown): value is Record<string | number | symbol, unknown> {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n}\n\nexport function ToNumber(value: unknown): number {\n // ES 2022's es-abstract made minor changes to ToNumber, but polyfilling these\n // changes adds zero benefit to Temporal and brings in a lot of extra code. So\n // we'll leave ToNumber as-is.\n // See https://github.com/ljharb/es-abstract/blob/main/2022/ToNumber.js\n if (typeof value === 'bigint') throw new TypeError('Cannot convert BigInt to number');\n return Number(value);\n}\n\nfunction IsIntegralNumber(argument: unknown) {\n if (typeof argument !== 'number' || Number.isNaN(argument) || argument === Infinity || argument === -Infinity) {\n return false;\n }\n const absValue = Math.abs(argument);\n return Math.floor(absValue) === absValue;\n}\n\nexport function ToString(value: unknown): string {\n if (typeof value === 'symbol') {\n throw new TypeError('Cannot convert a Symbol value to a String');\n }\n return String(value);\n}\n\nexport function ToIntegerWithTruncation(value: unknown): number {\n const number = ToNumber(value);\n if (number === 0) return 0;\n if (Number.isNaN(number) || number === Infinity || number === -Infinity) {\n throw new RangeError('invalid number value');\n }\n const integer = Math.trunc(number);\n if (integer === 0) return 0; // ℝ(value) in spec text; converts -0 to 0\n return integer;\n}\n\nfunction ToPositiveIntegerWithTruncation(valueParam: unknown, property?: string): number {\n const integer = ToIntegerWithTruncation(valueParam);\n if (integer <= 0) {\n if (property !== undefined) {\n throw new RangeError(`property '${property}' cannot be a a number less than one`);\n }\n throw new RangeError('Cannot convert a number less than one to a positive integer');\n }\n return integer;\n}\n\nexport function ToIntegerIfIntegral(valueParam: unknown): number {\n const number = ToNumber(valueParam);\n if (Number.isNaN(number)) throw new RangeError('not a number');\n if (number === Infinity || number === -Infinity) throw new RangeError('infinity is out of range');\n if (!IsIntegralNumber(number)) throw new RangeError(`unsupported fractional value ${valueParam}`);\n if (number === 0) return 0; // ℝ(value) in spec text; converts -0 to 0\n return number;\n}\n\nfunction ToZeroPaddedDecimalString(n: number, minLength: number) {\n if (DEBUG) {\n if (!IsIntegralNumber(n) || n < 0) {\n throw new RangeError('Assertion failed: `${n}` must be a non-negative integer');\n }\n }\n const s = String(n);\n return s.padStart(minLength, '0');\n}\n\n// This convenience function isn't in the spec, but is useful in the polyfill\n// for DRY and better error messages.\nexport function RequireString(value: unknown): string {\n if (typeof value !== 'string') {\n // Use String() to ensure that Symbols won't throw\n throw new TypeError(`expected a string, not ${String(value)}`);\n }\n return value;\n}\n\nfunction ToSyntacticallyValidMonthCode(valueParam: unknown) {\n const value = RequireString(ToPrimitive(valueParam, String));\n if (\n value.length < 3 ||\n value.length > 4 ||\n value[0] !== 'M' ||\n '0123456789'.indexOf(value[1]) === -1 ||\n '0123456789'.indexOf(value[2]) === -1 ||\n (value[1] + value[2] === '00' && value[3] !== 'L') ||\n (value[3] !== 'L' && value[3] !== undefined)\n ) {\n throw new RangeError(`bad month code ${value}; must match M01-M99 or M00L-M99L`);\n }\n return value;\n}\n\nfunction ToOffsetString(valueParam: unknown) {\n const value = RequireString(ToPrimitive(valueParam, String));\n ParseDateTimeUTCOffset(value);\n return value;\n}\n\n// Limited implementation of ToPrimitive that only handles the string case,\n// because that's all that's used in this polyfill.\nfunction ToPrimitive(value: unknown, preferredType: typeof String): string | number {\n assertExists(preferredType === String);\n if (IsObject(value)) {\n const result = value?.toString();\n if (typeof result === 'string' || typeof result === 'number') return result;\n throw new TypeError('Cannot convert object to primitive value');\n }\n return value;\n}\n\nconst CALENDAR_FIELD_KEYS: readonly FieldKey[] = [\n 'era',\n 'eraYear',\n 'year',\n 'month',\n 'monthCode',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'millisecond',\n 'microsecond',\n 'nanosecond',\n 'offset',\n 'timeZone'\n] as const;\n\ntype BuiltinCastFunction = (v: unknown) => string | number;\nconst BUILTIN_CASTS: Partial<Record<FieldKey, BuiltinCastFunction>> = {\n era: ToString,\n eraYear: ToIntegerWithTruncation,\n year: ToIntegerWithTruncation,\n month: ToPositiveIntegerWithTruncation,\n monthCode: ToSyntacticallyValidMonthCode,\n day: ToPositiveIntegerWithTruncation,\n hour: ToIntegerWithTruncation,\n minute: ToIntegerWithTruncation,\n second: ToIntegerWithTruncation,\n millisecond: ToIntegerWithTruncation,\n microsecond: ToIntegerWithTruncation,\n nanosecond: ToIntegerWithTruncation,\n offset: ToOffsetString,\n timeZone: ToTemporalTimeZoneIdentifier\n};\n\nconst BUILTIN_DEFAULTS: Partial<Record<FieldKey, number>> = {\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n microsecond: 0,\n nanosecond: 0\n};\n\n// each item is [plural, singular, category, (length in ns)]\nconst TEMPORAL_UNITS = [\n ['years', 'year', 'date'],\n ['months', 'month', 'date'],\n ['weeks', 'week', 'date'],\n ['days', 'day', 'date'],\n ['hours', 'hour', 'time'],\n ['minutes', 'minute', 'time'],\n ['seconds', 'second', 'time'],\n ['milliseconds', 'millisecond', 'time'],\n ['microseconds', 'microsecond', 'time'],\n ['nanoseconds', 'nanosecond', 'time']\n] as const;\nconst SINGULAR_FOR = Object.fromEntries(TEMPORAL_UNITS.map((e) => [e[0], e[1]] as const));\nconst PLURAL_FOR = Object.fromEntries(TEMPORAL_UNITS.map(([p, s]) => [s, p] as const));\nconst UNITS_DESCENDING = TEMPORAL_UNITS.map(([, s]) => s);\ntype TimeUnitOrDay = Temporal.TimeUnit | 'day';\nconst NS_PER_TIME_UNIT = {\n day: DAY_NANOS,\n hour: 3600e9,\n minute: 60e9,\n second: 1e9,\n millisecond: 1e6,\n microsecond: 1e3,\n nanosecond: 1\n};\n\nconst DURATION_FIELDS = [\n 'days',\n 'hours',\n 'microseconds',\n 'milliseconds',\n 'minutes',\n 'months',\n 'nanoseconds',\n 'seconds',\n 'weeks',\n 'years'\n] as const;\n\nimport * as PARSE from './regex';\n\n// Save the original Intl.DateTimeFormat, it will likely be overwritten with the\n// one from this polyfill. Caching the formatter below may be reentrant, so we\n// need to use the original one\nconst OriginalIntlDateTimeFormat = Intl.DateTimeFormat;\nconst IntlDateTimeFormatEnUsCache = new Map<string, Intl.DateTimeFormat>();\n\nfunction getIntlDateTimeFormatEnUsForTimeZone(timeZoneIdentifier: string) {\n const lowercaseIdentifier = ASCIILowercase(timeZoneIdentifier);\n let instance = IntlDateTimeFormatEnUsCache.get(lowercaseIdentifier);\n if (instance === undefined) {\n instance = new OriginalIntlDateTimeFormat('en-us', {\n timeZone: lowercaseIdentifier,\n hour12: false,\n era: 'short',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric'\n });\n IntlDateTimeFormatEnUsCache.set(lowercaseIdentifier, instance);\n }\n return instance;\n}\n\nexport function ToObject<T>(value: T): T extends Record<string, unknown> ? T : Record<PropertyKey, unknown> {\n if (typeof value === 'undefined' || value === null) {\n throw new TypeError(`Expected object not ${value}`);\n }\n return Object(value);\n}\n\n// Adapted from https://github.com/ljharb/es-abstract/blob/main/2022/CopyDataProperties.js\n// but simplified (e.g. removed assertions) for this polyfill to reduce bundle size.\nexport function CopyDataProperties<K extends PropertyKey, T extends Record<K, unknown>>(\n target: T,\n source: T | undefined,\n excludedKeys: K[],\n excludedValues?: unknown[]\n) {\n if (typeof source === 'undefined' || source === null) return;\n\n const keys = Reflect.ownKeys(source) as (keyof T)[];\n for (let index = 0; index < keys.length; index++) {\n const nextKey = keys[index];\n if (excludedKeys.some((e) => Object.is(e, nextKey))) continue;\n if (Object.prototype.propertyIsEnumerable.call(source, nextKey)) {\n const propValue = source[nextKey];\n if (excludedValues && excludedValues.some((e) => Object.is(e, propValue))) continue;\n\n target[nextKey] = propValue;\n }\n }\n}\n\nexport function IsTemporalInstant(item: unknown): item is Temporal.Instant {\n return HasSlot(item, EPOCHNANOSECONDS) && !HasSlot(item, TIME_ZONE, CALENDAR);\n}\n\nexport function IsTemporalDuration(item: unknown): item is Temporal.Duration {\n return HasSlot(item, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS);\n}\nexport function IsTemporalDate(item: unknown): item is Temporal.PlainDate {\n return HasSlot(item, DATE_BRAND);\n}\n\nexport function IsTemporalTime(item: unknown): item is Temporal.PlainTime {\n return HasSlot(item, TIME);\n}\n\nexport function IsTemporalDateTime(item: unknown): item is Temporal.PlainDateTime {\n return HasSlot(item, ISO_DATE_TIME);\n}\n\nexport function IsTemporalYearMonth(item: unknown): item is Temporal.PlainYearMonth {\n return HasSlot(item, YEAR_MONTH_BRAND);\n}\nexport function IsTemporalMonthDay(item: unknown): item is Temporal.PlainMonthDay {\n return HasSlot(item, MONTH_DAY_BRAND);\n}\nexport function IsTemporalZonedDateTime(item: unknown): item is Temporal.ZonedDateTime {\n return HasSlot(item, EPOCHNANOSECONDS, TIME_ZONE, CALENDAR);\n}\n\nexport function CheckReceiver<T extends AnySlottedType>(\n item: unknown,\n test: (item: unknown) => item is T\n): asserts item is T {\n if (!test(item)) throw new TypeError('invalid receiver: method called with the wrong type of this-object');\n}\n\nexport function RejectTemporalLikeObject(item: AnyTemporalLikeType) {\n if (HasSlot(item, CALENDAR) || HasSlot(item, TIME_ZONE)) {\n throw new TypeError('with() does not support a calendar or timeZone property');\n }\n if (IsTemporalTime(item)) {\n throw new TypeError('with() does not accept Temporal.PlainTime, use withPlainTime() instead');\n }\n if ((item as { calendar: unknown }).calendar !== undefined) {\n throw new TypeError('with() does not support a calendar property');\n }\n if ((item as { timeZone: unknown }).timeZone !== undefined) {\n throw new TypeError('with() does not support a timeZone property');\n }\n}\n\nfunction FormatCalendarAnnotation(id: BuiltinCalendarId, showCalendar: Temporal.ShowCalendarOption['calendarName']) {\n if (showCalendar === 'never') return '';\n if (showCalendar === 'auto' && id === 'iso8601') return '';\n const flag = showCalendar === 'critical' ? '!' : '';\n return `[${flag}u-ca=${id}]`;\n}\n\n// Not a separate abstract operation in the spec, because it only occurs in one\n// place: ParseISODateTime. In the code it's more convenient to split up\n// ParseISODateTime for the YYYY-MM, MM-DD, and THH:MM:SS parse goals, so it's\n// repeated four times.\nfunction processAnnotations(annotations: string) {\n let calendar;\n let calendarWasCritical = false;\n // Avoid the user code minefield of matchAll.\n let match;\n PARSE.annotation.lastIndex = 0;\n while ((match = PARSE.annotation.exec(annotations))) {\n const { 1: critical, 2: key, 3: value } = match;\n if (key === 'u-ca') {\n if (calendar === undefined) {\n calendar = value;\n calendarWasCritical = critical === '!';\n } else if (critical === '!' || calendarWasCritical) {\n throw new RangeError(`Invalid annotations in ${annotations}: more than one u-ca present with critical flag`);\n }\n } else if (critical === '!') {\n throw new RangeError(`Unrecognized annotation: !${key}=${value}`);\n }\n }\n return calendar;\n}\n\nfunction ParseISODateTime(isoString: string) {\n // ZDT is the superset of fields for every other Temporal type\n const match = PARSE.zoneddatetime.exec(isoString);\n if (!match) throw new RangeError(`invalid RFC 9557 string: ${isoString}`);\n const calendar = processAnnotations(match[16]);\n let yearString = match[1];\n if (yearString === '-000000') throw new RangeError(`invalid RFC 9557 string: ${isoString}`);\n const year = +yearString;\n const month = +(match[2] ?? match[4] ?? 1);\n const day = +(match[3] ?? match[5] ?? 1);\n const hasTime = match[6] !== undefined;\n const hour = +(match[6] ?? 0);\n const minute = +(match[7] ?? match[10] ?? 0);\n let second = +(match[8] ?? match[11] ?? 0);\n if (second === 60) second = 59;\n const fraction = (match[9] ?? match[12] ?? '') + '000000000';\n const millisecond = +fraction.slice(0, 3);\n const microsecond = +fraction.slice(3, 6);\n const nanosecond = +fraction.slice(6, 9);\n let offset;\n let z = false;\n if (match[13]) {\n offset = undefined;\n z = true;\n } else if (match[14]) {\n offset = match[14];\n }\n const tzAnnotation = match[15];\n RejectDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);\n return {\n year,\n month,\n day,\n time: hasTime ? { hour, minute, second, millisecond, microsecond, nanosecond } : ('start-of-day' as const),\n tzAnnotation,\n offset,\n z,\n calendar\n };\n}\n\n// ts-prune-ignore-next TODO: remove if test/validStrings is converted to TS.\nexport function ParseTemporalInstantString(isoString: string) {\n const result = ParseISODateTime(isoString);\n if (!result.z && !result.offset) throw new RangeError('Temporal.Instant requires a time zone offset');\n return result;\n}\n\n// ts-prune-ignore-next TODO: remove if test/validStrings is converted to TS.\nexport function ParseTemporalZonedDateTimeString(isoString: string) {\n const result = ParseISODateTime(isoString);\n if (!result.tzAnnotation) throw new RangeError('Temporal.ZonedDateTime requires a time zone ID in brackets');\n return result;\n}\n\n// ts-prune-ignore-next TODO: remove if test/validStrings is converted to TS.\nexport function ParseTemporalDateTimeString(isoString: string) {\n return ParseISODateTime(isoString);\n}\n\n// ts-prune-ignore-next TODO: remove if test/validStrings is converted to TS.\nexport function ParseTemporalDateString(isoString: string) {\n return ParseISODateTime(isoString);\n}\n\n// ts