Tempo Terms
Overview
The Terms system is Tempo's extensible plugin mechanism for attaching business-logic to a date-time instance, without adding to the profile (memory footprint) of a Tempo object.
Because a Tempo instance is designed to be as lean as possible, term properties are lazy-loaded: their lookup function is not executed until the property is first accessed. Once evaluated, the result is memoised — subsequent reads of the same property return the cached value directly, with no further computation.
new Tempo('25-Dec-2024').term.season // ← computed on first access, cached thereafterTIP
Transparent Discovery: As of v2.0.1, all Term properties are enumerable. While modern console.log environments (like Node.js) will typically display these as [Getter] to preserve laziness, they are visible to property-scanning tools. This means a serializer (like JSON.stringify) or a deep-clone utility will trigger the eager evaluation of every registered Term at once. To prevent terminal noise during these events (e.g., for invalid dates), initialize Tempo with silent: true.
What a Term Does
A Term plugin answers a single question:
"Where does this
Tempoinstance sit within a pre-defined date-time range?"
Each plugin holds a static list of range boundaries (e.g. the start of each meteorological season) and a define function that is called — with the Tempo instance as its this context — to determine into which boundary the instance falls.
Each Term plugin exposes two views of that result via the tempo.term object:
| Property | Returns |
|---|---|
tempo.term.<key> | A short identifier string (e.g. 'Q1', 'Summer', 'Morning') |
tempo.term.<scope> | The full matching range object, with all metadata fields (e.g. key, keys, span, etc.) |
The <key> and <scope> names are defined by the plugin author, where <key> (e.g. qtr, szn) returns a concise identifier value and <scope> (e.g. quarter, season) returns the full matching range object.
Provided Plugins
INFO
Meteorological Seasons require an explicit sphere configuration (sphere: 'north', 'south', or 'equator'). Calendar Quarters are strictly decoupled from hemisphere.
qtr / quarter — Calendar Quarters (ISO 8601-2)
Divides the Gregorian calendar year into four standard quarters aligned with ISO 8601-2 and ISO 17369: Q1 (Jan 1), Q2 (Apr 1), Q3 (Jul 1), and Q4 (Oct 1). It is strictly calendar-based and completely independent of geographic hemisphere.
const t = new Tempo('15-Feb-2025');
t.term.qtr // → 'Q1'
t.term.quarter // → { key: 'Q1', keys: ['Q1', 'Q2', 'Q3', 'Q4'], span: { ... } }
t.term.quarter.keys // → ['Q1', 'Q2', 'Q3', 'Q4']
t.term.quarter.span.start // → Tempo('2025-01-01T00:00:00')
t.term.quarter.span.end // → Tempo('2025-04-01T00:00:00')
t.term.quarter.span.progress // → 0.5055 (normalized 0.0 .. 1.0)fqtr / fiscal — Fiscal Quarters
Divides corporate or governmental financial cycles into four fiscal quarters (FQ1–FQ4) with a numeric year for direct financial arithmetic. Configure your default jurisdiction or custom cycle once at activation time via Tempo.use(FiscalTerm({ ... })) (e.g. country: 'AU' for July 1, 'GB'/'IN' for April 1, 'US_FED' for October 1, or custom startMonth / startDay such as { startMonth: 4, startDay: 6 } for the UK personal tax year):
import { Tempo } from 'tempo-kit';
import { FiscalTerm } from 'tempo-kit/terms';
// Configure default fiscal cycle at activation time
Tempo.use(FiscalTerm({ country: 'AU' }));
const t = new Tempo('15-Feb-2026');
t.term.fqtr // → 'FQ3'
t.term.fiscal.year // → 2026
t.term.fiscal.span.start // → Tempo('2026-01-01T00:00:00')
// Override per instance when needed (via pluginOptions or geo.country)
const tUK = new Tempo('15-Feb-2026', { pluginOptions: { fiscal: { country: 'GB' } } });
tUK.term.fiscal.key // → 'FQ4' (April 1 start)szn / season — Meteorological Seasons
Maps the current date to the appropriate meteorological season. Supports Northern Hemisphere ('north'), Southern Hemisphere ('south'), and equatorial tropical cycles ('equator': Wet and Dry seasons).
const t = new Tempo('01-Jul-2025', { sphere: 'north' });
t.term.szn // → 'Summer' (Northern Hemisphere)
t.term.season.keys // → ['Spring', 'Summer', 'Autumn', 'Winter', 'Dry', 'Wet']
t.term.season.span.start // → Tempo('2025-06-01T00:00:00')const tSouth = new Tempo('01-Jul-2025', { sphere: 'south' });
tSouth.term.szn // → 'Winter' (southern hemisphere)
const tTropics = new Tempo('15-Apr-2025', { sphere: 'equator' });
tTropics.term.szn // → 'Wet' (equatorial bimodal cycle)
tTropics.term.season.label // → 'Long Wet' ('Long Wet', 'Long Dry', 'Short Wet', 'Short Dry')tod / timeOfDay — Daily Time Periods
Classifies the time of day into a named period based on a pre-defined range.
| Key | Starts at |
|---|---|
Midnight | 00:00 |
Early | 04:00 |
Morning | 08:00 |
Midmorning | 10:00 |
Midday | 12:00 |
Afternoon | 15:30 |
Evening | 18:00 |
Night | 20:00 |
const t = new Tempo('1pm');
t.term.tod // → 'Midday'
t.term.timeOfDay // → { key: 'Midday', group: 'standard', keys: [...], span: { ... } }
t.term.timeOfDay.keys // → ['Midnight', 'Early', 'Morning', 'Midmorning', 'Midday', 'Afternoon', 'Evening', 'Night']Inspecting Registered Terms
The static Tempo.terms getter returns a read-only list of all registered plugins:
Tempo.terms
// → [
// { key: 'qtr', scope: 'quarter', description: 'Calendar Quarter' },
// { key: 'szn', scope: 'season', description: 'Meteorological season' },
// { key: 'tod', scope: 'timeOfDay', description: 'Daily time period' },
// ]Activating Terms
In Tempo Full (tempo-kit), Civic Terms (#quarter, #season, #timeOfDay) are enabled by default. In Tempo Core (tempo-kit/core), you can opt-in explicitly:
1. Civic Terms Bundle (tempo-kit/terms)
Enables standard Civic Terms (#quarter, #season, #timeOfDay) without loading Full Tempo's optional modules (FormatModule, DurationModule, etc.):
import { Tempo } from 'tempo-kit/core';
import { CivicTerms } from 'tempo-kit/terms';
Tempo.use(CivicTerms);(For cultural and traditional calendar Terms such as Western and East Asian Zodiac signs, see the standalone @tempo-kit/plugin-cultural plugin documentation.)
3. Surgical Opt-in (Individual Terms)
Best for maximum bundle-size optimization—import only the specific term you use from tempo-kit/terms/*:
import { Tempo } from 'tempo-kit/core';
import { QuarterTerm } from 'tempo-kit/terms/quarter';
Tempo.use(QuarterTerm);How to Define a Term Plugin
A Term plugin is created using the defineTerm factory function provided by the library (tempo-kit/plugin/sdk). This ensures correct type-inference and automatically handles registration during the discovery phase.
Plugin Definition
import { defineTerm, defineRange, getTermRange, resolveCycleWindow } from 'tempo-kit/plugin/sdk';
import { enums, type Tempo } from 'tempo-kit/core';
/** 1. The range boundaries (grouped by sphere) */
const ranges = defineRange([
{ key: 'Spring', month: 3, sphere: enums.COMPASS.North },
{ key: 'Summer', month: 6, sphere: enums.COMPASS.North },
{ key: 'Autumn', month: 9, sphere: enums.COMPASS.North },
{ key: 'Winter', month: 12, sphere: enums.COMPASS.North },
{ key: 'Spring', month: 9, sphere: enums.COMPASS.South },
{ key: 'Summer', month: 12, sphere: enums.COMPASS.South },
{ key: 'Autumn', month: 3, sphere: enums.COMPASS.South },
{ key: 'Winter', month: 6, sphere: enums.COMPASS.South },
], 'sphere');
/** 2. Resolve the candidate list for the current anchor/context */
function resolve(t: Tempo, anchor?: any): any[] {
const source = anchor ?? t;
const sphere = source.sphere ?? t.sphere;
const template = ranges[sphere] ?? [];
// resolveCycleWindow handle the ±1 year shifting for boundaries
return resolveCycleWindow(t, template, anchor);
}
/** 3. The Plugin Object */
export const MyRetailSeasonTerm = defineTerm({
key: 'rsn',
scope: 'retailSeason',
description: 'Custom retail seasonal range',
ranges,
/** Optional: Used for multi-cycle discovery & traversals */
resolve(this: Tempo, anchor?: any) {
return resolve(this, anchor);
},
/**
* Determine the current range.
* @param keyOnly - if true, return only the identifier string
* @param anchor - the specific date-time we are calculating for
*/
define(this: Tempo, keyOnly?: boolean, anchor?: any) {
const list = resolve(this, anchor);
return getTermRange(this, list, keyOnly, anchor);
}
});Range fields
A Range object must include a key and any subset of the date-time fields below. getTermRange sorts ranges in descending chronological order and returns the first range whose boundary the instance has reached or passed.
🔄 Sync to Alias Engine
When a Term plugin defines ranges with string-based key values, Tempo automatically synchronizes these keys with the internal Alias Engine.
- Period Scopes: Ranges defined in a
periodscope (likemidnightormorning) are registered as Period Aliases. - Event Scopes: Ranges defined in an
eventscope are registered as Event Aliases.
This synchronization happens during Tempo.use() and Tempo.init(), ensuring that any named range boundaries are immediately available for use in the natural-language parsing engine. For example, if you define a custom Term with a range key "bedtime", you can immediately create a new instance using new Tempo('bedtime').
type Range = {
key: PropertyKey; // identifier returned when keyOnly = true
year?: number;
month?: number;
day?: number;
hour?: number;
minute?: number;
second?: number;
group?: string; // categorization marker (e.g. 'fiscal', 'western')
[extra: PropertyKey]: any; // any additional term-dependent metadata (e.g. 'sphere')
}Registering the plugin
Use the static Tempo.use() method. This allows you to add Terms dynamically without modifying the library source.
import { Tempo } from 'tempo-kit/core';
import { MyRetailSeasonTerm } from './term.myretailseason.js';
// Register the term plugin
Tempo.use(MyRetailSeasonTerm);Every Tempo instance created after that point will have the custom Term available.
Using Custom Configuration in Terms
Since Tempo preserves non-standard configuration options in its internal config object, you can use Tempo.init() to provide values that your custom Term plugin can later reference.
// 1. Initialize with a custom domain config option
Tempo.init({
academicYearStart: 9 // e.g., September
});
// 2. Define a custom Term that reads this config property
Tempo.use({
key: 'acad',
scope: 'academicYear',
description: 'Custom Academic Year',
define: function(this: Tempo, keyOnly?: boolean) {
const startMonth = (this.config as any).academicYearStart ?? 9;
const startYear = this.mm >= startMonth ? this.yy : this.yy - 1;
const label = `AY${startYear}-${String(startYear + 1).slice(-2)}`;
return keyOnly
? label
: { key: label, startYear, startMonth };
}
});
const t = new Tempo('2025-02-15');
console.log(t.term.acad); // → "AY2024-25" (before September 2025)🧭 Writing Math-Aware Terms
To unlock Tempo's advanced Term Traversal (e.g., t.add({ '#quarter': 1 })) and Ticker Syncing, a plugin provides semantic boundaries and duration metrics via span: TermSpan (span.start, span.end, span.total, span.elapsed, span.remaining, span.progress).
NOTE
span.progress Precision & Bounds: span.progress is clamped to [0, 1] and rounded to 4 decimal places (0.0001 steps). Both endpoints are reachable: 0 at span.start (and within the first 0.005% of the span), and 1 within the final 0.005% before span.end (even on half-open [start, end) ranges, e.g., the final ~6.5 minutes of a 90-day quarter) or when evaluated against an anchor >= span.end.
The getTermRange Helper
The library provides a specialized helper that calculates these boundaries and progress metrics automatically based on your ranges array.
import { getTermRange } from 'tempo-kit/plugin/sdk';
export function define(this: Tempo, keyOnly?: boolean) {
// Finds the current range, then encapsulates temporal boundaries and progress into 'span'
// (with start, end, total, elapsed, remaining, progress) before returning it to the user.
return getTermRange(this, ranges, keyOnly);
}Manual Boundaries and Progress Spans
For procedural terms that compute custom start/end dates instead of calling getTermRange, use the defineSpan(this, start, end) helper from tempo-kit/plugin/sdk:
import { defineSpan } from 'tempo-kit/plugin/sdk';
export function define(this: Tempo, keyOnly?: boolean) {
const start = this.set({ hour: 0, minute: 0, second: 0, millisecond: 0 });
const end = start.add({ days: 1 });
return keyOnly ? 'MyTerm' : {
key: 'MyTerm',
span: defineSpan(this, start, end)
};
}Multi-Cycle Discovery & Traversals (The resolve method)
The define method only returns a single boundary (the one the instance currently falls into). But what happens if a user wants to traverse forward by three boundaries (t.add({ '#rsn': 3 }))? Or what if the Ticker engine needs to discover virtual deadlines across multiple years?
To enable this, your plugin can optionally provide a resolve(anchor) method. This method should return the complete array of boundaries for a given cycle (e.g., all the retail seasons in a given year).
When the core engine needs to mathematically "step" through boundaries across multiple years, it repeatedly calls your resolve method with different anchor dates (e.g., shifting the year forward) to discover future/past boundaries seamlessly!
🪝 Term Lifecycle Hooks Protocol
Starting in v4.6.0, Term plugins can participate directly in Tempo's core parsing, arithmetic, boundary snapping, difference calculation, and formatting pipelines via well-known symbols.
Instead of overriding core methods or monkey-patching regex tables, term plugins implement protocol hooks using well-known symbols (Symbol.for), exported under TermHook:
import { TermHook, type TermParseContext, type Tempo } from 'tempo-kit';
import { defineTerm } from 'tempo-kit/plugin/sdk';The 6 Lifecycle Hooks
| Hook Symbol | Method Signature | Engine Trigger |
|---|---|---|
[TermHook.parse] | (input: string, context?: TermParseContext) => Tempo | Temporal.ZonedDateTime | undefined | Explicit #term natural string input (e.g. new Tempo('#fiscal.q1')) |
[TermHook.ordinal] | (groups: Record<string, any>, anchor: Tempo, context?: TermParseContext) => Tempo | Temporal.ZonedDateTime | undefined | Anchored ordinal expressions (e.g. Tempo.from('3rd day of #sprint.2', { anchor })) |
[TermHook.step] | (unit: string, count: number, tempo: Tempo) => Tempo | undefined | Stepping arithmetic via dictionary syntax: t.add({ '#term': n }), t.sub({ '#term': n }) |
[TermHook.diff] | (other: Tempo, unit: string, tempo: Tempo) => number | undefined | Difference calculation: t1.until(t2, '#term'), t1.since(t2, '#term') |
[TermHook.bound] | (boundary: 'start' | 'mid' | 'end', unit: string, tempo: Tempo) => Tempo | undefined | Range boundary snapping: t.set({ '#term': 'start' }), t.set('#term.mid') |
[TermHook.format] | (token: string, tempo: Tempo) => string | undefined | Custom token formatting: t.format('{#academic}'), t.format('{#academic:upper}') |
Complete Hook Example
import { Tempo, TermHook } from 'tempo-kit';
import { defineTerm } from 'tempo-kit/plugin/sdk';
export const SprintTerm = defineTerm({
key: 'sprint',
scope: 'sprint',
description: 'Two-week development sprint cycle',
define() {
return {
key: 'sprint.1',
start: this.set({ hour: 0, minute: 0, second: 0, millisecond: 0 }),
end: this.add({ days: 14 })
};
},
// 1. Parse: Resolve custom #sprint expressions
[TermHook.parse](input, ctx) {
if (input === '#sprint.current') {
return (ctx?.anchor ?? this).set({ day: 1 });
}
return undefined;
},
// 2. Ordinal: Handle ordinal offsets
[TermHook.ordinal](groups, anchor) {
// e.g. "3rd day of #sprint.current" or "penultimate day of #sprint.current"
const ord = groups.ord?.toLowerCase();
const val = groups.value ?? (ord === 'last' ? 14 : (parseInt(ord, 10) || Tempo.enums.ORDINAL[ord]));
if (!val) return undefined;
const dayOffset = val < 0 ? 14 + val + 1 : val;
if (dayOffset < 1 || dayOffset > 14) return undefined;
return anchor.add({ days: dayOffset - 1 });
},
// 3. Step: add/sub sprint blocks
[TermHook.step](unit, count, tempo) {
return tempo.add({ days: count * 14 });
},
// 4. Bound: Snap to sprint start/end
[TermHook.bound](boundary, unit, tempo) {
if (boundary === 'start') return tempo.set({ hour: 9, minute: 0, second: 0, millisecond: 0 });
if (boundary === 'end') return tempo.add({ days: 14 }).set({ hour: 17, minute: 0, second: 0, millisecond: 0 });
return undefined;
},
// 5. Diff: Sprints between two dates
[TermHook.diff](other, unit, tempo) {
const diffDays = tempo.until(other, 'days');
return Math.trunc(diffDays / 14);
},
// 6. Format: Custom sprint format token
[TermHook.format](token, tempo) {
if (token === '#sprint') {
return `Sprint-${Math.ceil(tempo.doy / 14)}`;
}
return undefined;
}
});Zero-Overhead Guarantee
All lifecycle hooks are strictly isolated behind the # domain term sigil:
- Calls to standard ISO date parsing (e.g.
new Tempo('2026-10-09')), core unit arithmetic (e.g.t.add({ months: 1 })), and standard formatting (t.format('{yyyy}-{mm}-{dd}')) bypass hook lookups entirely with 0ns overhead. - Existing terms that do not implement lifecycle hooks continue to use default range-based dispatching without interruption.
🛠️ Developer Guide: Best Practices
To ensure a custom Term plugin integrates fully with Tempo, follow these guidelines:
- Static
ranges&keysDiscovery: Always include thekeysproperty in yourdefineTermconfiguration (andrangeswhen using static interval models). Exposing an immutable frozen array of range keys (keys: MY_KEYS) both statically on the term definition (Term.keys) and within the resolved scope object (t.term.<scope>.keys) provides a uniform, introspectable API contract across all Terms, avoiding ambiguous plural properties (such as.quartersor.seasons). This enables programmatic discovery viaTempo.termsand allows the Ticker to automatically calculate next-pulse intervals. - Metadata-First Boundaries: If your plugin handles multiple sets (e.g. hemispheres or cultural calendars), avoid using array indices like
ranges[0]. Instead, add marker fields likesphereorgroupto each range object and use.filter()inside yourdefinefunction. - Memoization Safety: Keep the
definefunction pure. It will only be called once per instance access. - Math Readiness: Always use
getTermRangeor provide boundaries. Without them, users cannot use your Term inadd(),set(), orticker(). - Key consistency: It is valid to remap the returned scope
key(for example,cfy->FY2024) when that is the semantic value your Term represents. Be intentional and keep it consistent with yourrangeslookup and consumer expectations. - Unique Names & Collisions: Keep
keyandscopeglobally unique across all registered Terms. Avoid reusing an existing Termkey(e.g., another plugin already usesqtr) orscopealias. Current behavior is not ideal for collisions: duplicate Term keys are ignored, while scope alias resolution is order-dependent and can shadow another Term. Treat collisions as unsupported and choose unique names to ensure deterministic behavior. - Semantic Casing: To provide a predictable developer experience, adhere to the following casing standards for your
TermandRangefields:- Lower-case: Internal identifiers (Term
keyandscope) and marker fields (e.g.,group,sphere,id). - CapInit / TitleCase: Presentational identifiers (e.g., Range
keyorsymbol, like'Q1'or'Spring'). This ensurest.term.season.keyreturns a properly capitalized string. - Free-form text: Longer descriptive fields (e.g.,
label,description,trait).
- Lower-case: Internal identifiers (Term
- IDE Autocomplete (Interface Augmentation): To provide a world-class developer experience, always augment the global
TempoTermRegistryinterface with your custom keys and payload types. This ensures IDEs can provide strict type-checking and autocomplete when users accesst.term.myKey.ts// IDE Autocomplete (Interface Augmentation) declare module 'tempo-kit' { interface TempoTermRegistry { rsn: 'Spring' | 'Summer' | 'Autumn' | 'Winter'; retailSeason: { key: 'Spring' | 'Summer' | 'Autumn' | 'Winter'; symbol: string; // ... } } }
🧭 Best Practices: Idempotency & Side-Effects
WARNING
Because Term lookups are memoized (cached) on the instance, the define function must be pure and idempotent. It should only depend on the current Tempo instance state and its configuration (this.config).
Never apply side-effects or modify external state within a Term definition. The function is only guaranteed to run once per instance access; subsequent reads will return the cached value directly without re-executing your logic.