# Tempo Full Documentation Context (v5.1.1)
> This file contains the complete concatenated markdown documentation set for tempo-kit (v5.1.1). It is intended for automated LLM context ingestion and RAG indexing.
---
## Glossary
- **Cadence** (`reactivity`): The rhythmic scheduling interval or pattern governing ticker executions and reactive signal updates.
- **Calendar** (`temporal-math`): A system for organizing days into months and years (such as iso8601, gregory, hebrew, or islamic-civil) tracked by every Tempo instance.
- **Clock Drift** (`plugins`): The gradual offset between local system time and true reference network time, compensated by the NTP plugin.
- **Dialect** (`plugins`): An external date/time format token grammar (such as LDML, Moment, POSIX strftime, or Oracle TO_CHAR) bridged by @tempo-kit/plugin-dialects.
- **Disposable** (`reactivity`): An object implementing dispose() and Symbol.dispose for deterministic timer and subscription cleanup via TypeScript using declarations.
- **Duration** (`temporal-math`): A signed span of calendar and clock units (years, months, days, hours, minutes, seconds, sub-seconds) used in Tempo arithmetic and formatting.
- **Dynamic Functional Context (DFC)** (`architecture`): Tempo's pattern where configuration options (such as timeZone, locale, or calendar) accept lazy evaluator functions (() => T) resolved per request.
- **Enum** (`architecture`): A Proxy-wrapped, null-prototype lookup dictionary built with Enum.from() or Enum.extend() that supports static reflection without prototype pollution.
- **Epoch** (`temporal-math`): Elapsed time since the Unix epoch (1970-01-01T00:00:00Z), exposed by Tempo as .epoch.ms (number) and .epoch.ns (bigint).
- **IANA Time Zone** (`standards`): A canonical geographic region identifier (such as Australia/Sydney or America/New_York) carrying historical and DST offset rules.
- **Instant** (`temporal-math`): A precise, absolute point on the universal temporal timeline, independent of time zones or calendars.
- **Interval** (`temporal-math`): A half-open [start, end) span (inclusive start, exclusive end) between two temporal points supporting containment, overlap, union, and reactive state observation.
- **ISO 8601** (`standards`): The international standard for date, time, UTC offset, duration, and week-date string representations.
- **Lazy Evaluation** (`architecture`): Deferring expensive derived computations (such as calendar decompositions, formatted caches, and DFC options) until first read and memoizing the result.
- **Locale** (`standards`): A BCP 47 language tag (such as en-AU or fr-FR) governing month/weekday names, relative-time phrasing, numbering systems, and regional date parsing.
- **Modifier** (`formatting`): An orthogonal token extension (e.g., :compact, :hh, :ordinal, :roman, :zero) refining how a format token or term serializes or parses values.
- **Namespace** (`plugins`): A deeply frozen static or instance extension object mounted on Tempo via defineNamespace() or definePlugin() (e.g., Tempo.signals, t.geo).
- **Offset** (`temporal-math`): A fixed numeric displacement from UTC (e.g., +10:00 or -05:00), distinct from an IANA time zone which carries historical and DST transition rules.
- **Parse Planner** (`architecture`): Tempo's layout selection and scoring subsystem that matches ambiguous input strings against registered snippets, dialects, and regional date layouts.
- **Pivot** (`formatting`): The two-digit year century cutoff (default 75) controlling whether 2-digit years resolve to 19xx or 20xx during parsing.
- **PlainDate** (`temporal-math`): A calendar date (year, month, day) without reference to a specific time of day, time zone, or geographical location.
- **PlainDateTime** (`temporal-math`): A wall-clock date and time without an attached time zone or UTC offset.
- **ReadonlySignal** (`reactivity`): A reactive accessor function adhering to the TC39 Signals proposal (Signify) that notifies subscribers of value and epoch changes.
- **RFC 9557** (`standards`): The Internet Extended Date/Time Format (IXDTF) standard extending RFC 3339 with bracketed time zone and calendar annotations (e.g., [Australia/Sydney][u-ca=iso8601]).
- **Sandbox** (`architecture`): An isolated Tempo subclass created via Tempo.extend() with its own configuration and plugin isolation for multi-tenant SSR or testing (term access uses the shared runtime term map, so tenants registering different terms under the same key can conflict).
- **Snippet** (`formatting`): A named regular-expression fragment registered in the parsing engine to match recurring sub-patterns (such as dates, times, or ordinals).
- **Soft Freeze** (`architecture`): Tempo's immutability strategy that provides non-destructive mutations without incurring the heavy V8 runtime cost of deep recursive Object.freeze().
- **Term** (`formatting`): A modular unit of temporal formatting, parsing, or range partitioning registered in the engine registry (e.g. #quarter, #season, #timeOfDay).
- **Token** (`formatting`): A bracketed lowercase format or parse placeholder inside a Tempo mask (e.g., {yyyy}, {mm}, {dd}, {hh}, {mi}, {ss}, {tz}).
- **ZonedDateTime** (`temporal-math`): A time-zone-aware, calendar-aware date and time combining an exact Instant, an IANA time zone, and a calendar system; Tempo's underlying Temporal representation.
---
# Document: 1-getting-started/ai-integration.md
# 🤖 AI & IDE Integration (`llms.txt`)
To ensure modern AI coding assistants—such as **Cursor**, **VS Code (GitHub Copilot)**, **Antigravity**, **ChatGPT**, and **Claude**—generate accurate, idiomatically aligned Tempo code and minimize hallucinations, Tempo publishes an official, standardized [`llms.txt`](https://tempo-kit.web.app/llms.txt) rulebook.
By providing these rules to your AI assistant, your IDE will respect Tempo's strict immutability, zero-cost getters, native `Temporal` runtime expectations, and layout token syntax out-of-the-box.
---
## 🚀 Quick Setup by IDE / Tool
### 1. Cursor IDE
Add Tempo to Cursor's native documentation index:
1. Open **Cursor Settings** (`Cmd + ,` or `Ctrl + ,`).
2. Navigate to **Features** ➔ **Docs**.
3. Click **+ Add new doc** and enter:
- **Name**: `Tempo`
- **URL**: `https://tempo-kit.web.app/llms.txt`
> [!TIP]
> Once added, type `@Tempo` in any Cursor chat or prompt window to inject exact API syntax rules into your conversation.
---
### 2. VS Code & GitHub Copilot
In VS Code, configure GitHub Copilot Chat by adding a `.github/copilot-instructions.md` file to the root of your workspace:
```markdown
# Tempo AI Rules
- Always use `Tempo` from `tempo-kit`.
- Never instantiate legacy JavaScript `Date`. Tempo expects native `Temporal` or polyfill.
- All mutating methods (`.add()`, `.subtract()`, `.set()`) return a brand-new, frozen `Tempo` instance.
- Refer to https://tempo-kit.web.app/llms.txt for full layout token grammar.
```
When prompting Copilot Chat in VS Code:
```text
"Using https://tempo-kit.web.app/llms.txt, write a custom layout parser..."
```
---
### 3. Antigravity AI Assistant
In Antigravity, you can reference the live endpoint directly in your chat prompt or store it as a localized Knowledge Item (KI):
- Reference `@https://tempo-kit.web.app/llms.txt` in your prompt for instant context ingestion.
---
### 4. ChatGPT & Claude Projects
For web-based LLM interfaces, reference or copy-paste the full, un-truncated documentation context file:
👉 **[Full RAG Documentation Bundle (`llms-full.txt`)](https://tempo-kit.web.app/llms-full.txt)**
---
## 🛠️ Prompting AI for Custom Layout Extensions
When asking AI assistants to generate custom layout patterns for non-standard date-time formats, instruct the model to use Tempo's configuration syntax (`Tempo.init({ registry: { layouts: { ... } } })`) and layout tokens (`{yy}`, `{mm}`, `{dd}`, `{hh}`, `{mi}`, `{ss}`).
### Sample Prompt:
> *"Using the rules from https://tempo-kit.web.app/llms.txt, register a custom Tempo layout for star-delimited dates (e.g., '08*04*2026') using `Tempo.init({ registry: { layouts: { ... } } })` and parse the date string using `new Tempo(...)`."*
### Generated Code (Actual Tempo Syntax):
```typescript
import { Tempo } from 'tempo-kit';
// 1. Register custom layout pattern using layout tokens
Tempo.init({
registry: {
layouts: {
star_date: '{mm}\\*{dd}\\*{yy}'
}
}
});
// 2. Parse date string matching the custom layout
const date = new Tempo('08*04*2026');
```
---
# Document: 1-getting-started/installation.md
# Installation Guide
`Tempo` is designed to be environment-agnostic. Whether you are building a server-side application, a modern browser project with ESM, or a performance-critical "Lite" bundle, `Tempo` provides a specific path for you.
## Temporal Polyfill Note
`Tempo` expects the host environment to provide `Temporal`, either through native runtime support or a user-supplied polyfill.
`Temporal` is the modern [ECMAScript date-time API](https://tc39.es/proposal-temporal/) shipping natively in modern environments (Deno 2.7+, Node.js 26+, Chrome 144+, Firefox 139+). In environments that do not yet support Temporal natively (check [caniuse.com/temporal](https://caniuse.com/temporal)), bundle `@js-temporal/polyfill`. To avoid needlessly inflating package sizes for modern apps, `Tempo` does not bundle a `Temporal` polyfill by default.
::: warning
Node.js environments that ship `Temporal` behind a feature flag (`--harmony-temporal`) may have incomplete implementations. For stability, we strongly recommend using `@js-temporal/polyfill` instead of the native flag until you upgrade to an official unflagged release.
:::
You can check at runtime with a simple guard:
```js
if (typeof globalThis.Temporal === 'undefined') {
// Load your Temporal polyfill for this environment
}
```
Note: The examples below include a polyfill for demonstration purposes only, so the snippets work consistently across environments.
---
## 💻 Server & Bundlers (Node.js, Bun, Vite)
For most modern projects using a package manager, install Tempo via the npm registry.
```bash
npm install tempo-kit # npm
yarn add tempo-kit # yarn
pnpm add tempo-kit # pnpm
bun add tempo-kit # bun
```
### Usage
```javascript
import { Tempo } from 'tempo-kit';
const t = new Tempo('next Friday');
```
### Node.js (with Native Temporal)
Native unflagged `Temporal` support is available in Node.js 26+ and is enabled by default.
```bash
node my-app.js
```
### Node.js (with Polyfill)
The polyfill import shown here is conditional guidance, not required for all environments.
```bash
npm install @js-temporal/polyfill
```
```javascript
import '@js-temporal/polyfill';
import { Tempo } from 'tempo-kit';
const t = new Tempo('next Friday');
```
---
## 🦕 Deno
Tempo is a native ESM package and works perfectly with Deno. You can add it via the `deno add` command which will resolve it from the npm registry.
As of Deno 2.7, the Temporal API is fully stabilized and enabled by default. You no longer need to pass the --unstable-temporal flag to use it.
```bash
deno add npm:tempo-kit
```
### Usage
```javascript
import { Tempo } from "tempo-kit";
const t = new Tempo();
```
---
## 🌐 Browser & Native Environments
Tempo provides multiple native browser distribution formats. Here is the quick breakdown of which approach to use:
- **Standard Usage** (No plugins): Use the Native ESM Bundle.
- **Plugins without a bundler**: Use **Smart CDNs** (Easiest setup) OR **Static CDNs** (Best production performance).
- **Plugins with a bundler** (Vite/Webpack): Do nothing. Your bundler handles the resolution automatically.
- **Non-ESM Environments**: Use the UMD Global Variable approach.
### 1. The Global Bundle (Standard Usage)
The easiest way to use Tempo natively in the browser is via the pre-optimized ESM bundle. It includes the full `tempo-kit` engine in a single file, eliminating network waterfall effects.
```html
```
```html
```
### 2. Smart CDNs (The "Best-of-Both-Worlds")
If you want the absolute easiest setup for **Tempo Plugins** natively in the browser, use an on-the-fly bundling CDN like [esm.sh](https://esm.sh). Smart CDNs act like a Node environment—they read the package resolution rules and resolve nested dependencies automatically, meaning you don't have to map any internal subpaths.
While you *could* import directly from the URL everywhere, the best practice is to use a tiny import map for your top-level packages to keep your application code clean:
```html
```
⚠️ Trade-offs of using Smart CDNs in Production
While `esm.sh` is fantastic for prototyping and reducing import map complexity, there are architectural trade-offs to consider before using it in a mission-critical production environment:
1. **Network Waterfalls:** The browser must fetch the module, parse it, and then fetch its nested dependencies sequentially. This can slow down page load times compared to a fully bundled application.
2. **Uptime Dependency:** You are introducing a critical third-party dependency into your runtime. If the CDN experiences routing issues, your application could break for end-users.
3. **Sub-dependency Version Floating:** `esm.sh` automatically resolves sub-dependencies based on semver constraints. If a sub-dependency introduces an accidental breaking change, it could affect your app.
4. **Suboptimal Tree Shaking:** The browser will download the entire module graph for that package; you cannot easily tree-shake unused exports as you can with a dedicated bundler like Vite or Webpack.
5. **Environment Parity:** Handling development versus production environments (like `process.env.NODE_ENV`) requires query parameters (e.g., `?dev`), which complicates deployment.
### 3. Static CDNs (Production-Ready)
For production environments where uptime and load speeds are critical, you should use a static file CDN (like jsdelivr). Because static CDNs serve raw files without compiling them on the fly, they are significantly faster and more reliable than Smart CDNs.
To use **Tempo Plugins** via a static CDN, you simply need to explicitly map the unified `plugin/sdk` subpath so the browser knows how to resolve the internal connections:
```html
```
> [!WARNING] Cache Busting
> The jsdelivr CDN aggressively caches major version tags (like `@5`). When relying on precise module resolution for plugins, it is highly recommended to use explicit patch versions (like `@5.1.1`) to avoid fetching mismatched or outdated sub-modules.
---
## 📦 Browser (Classic `
```
---
## 🧪 Granular "Lite" Builds (Advanced)
If you are extremely concerned about bundle size, you can bypass the "Batteries Included" entry point and import only the core engine. You then manually opt-in to the modules you need.
```javascript
import { Tempo } from 'tempo-kit/core';
import { MutateModule } from 'tempo-kit/mutate';
// Opt-in to specific functionality
Tempo.use(MutateModule);
const t = new Tempo().add({ days: 1 });
```
::: warning
When using the Lite build, the `Tempo` class will have almost no methods (like `.add()`, `.set()`, or `.format()`) until you explicitly call `Tempo.use()` with the appropriate module.
:::
---
## 🛡️ Versioning Policy
We recommend pinning your versions in production environments to ensure stability.
* **JSDelivr**: `https://cdn.jsdelivr.net/npm/tempo-kit@5/...` (Locks to major version 5)
* **Latest**: `https://cdn.jsdelivr.net/npm/tempo-kit/...` (Omit the version string to always receive the latest release. Note that JSDelivr will resolve a missing version tag to the latest published release).
---
## 🤖 AI & IDE Integration (`llms.txt`)
> [!TIP]
> Using **Cursor**, **VS Code (GitHub Copilot)**, **Antigravity**, **ChatGPT**, or **Claude**?
> Tempo publishes an official [`llms.txt`](https://tempo-kit.web.app/llms.txt) index to give AI assistants documented project context and reduce hallucinations regarding Tempo's syntax, token grammar, and immutability rules.
>
> 👉 **[Read the dedicated AI & IDE Integration Guide](./ai-integration.md)** for step-by-step setup instructions for your IDE or tool.
---
# Document: 1-getting-started/tempo.cookbook.md
# Tempo Cookbook
A collection of recipes for solving common date and time challenges using Tempo.
## Table of Contents
1. [The Basics](#the-basics)
2. [Parsing Challenges](#parsing-challenges)
3. [Manipulation and Calculations](#manipulation-and-calculations)
4. [Timezones and Locales](#timezones-and-locales)
5. [Business Logic and Terms](#business-logic-and-terms)
6. [Formatting and Localization](#formatting-and-localization)
7. [Interoperability](#interoperability)
---
## The Basics
### How do I get the current date and time?
Use the static `Tempo.now()` factory method to capture the current system date and time:
```typescript
const now = Tempo.now();
console.log(now.toString()); // e.g. "2026-07-31T14:42:11+10:00[Australia/Sydney]"
```
### Get "Now" in UTC or a specific time zone
Pass an options object directly to `Tempo.now()`:
```typescript
const utcNow = Tempo.now({ timeZone: 'UTC' });
const tokyoNow = Tempo.now({ timeZone: 'Asia/Tokyo' });
```
### How do I format a date for my UI?
Use the placeholder syntax in the `.format()` method.
```typescript
const t = new Tempo('2024-12-25');
t.format('{dd} {mon} {yyyy}'); // "25 December 2024"
t.format('{h12}:{mi}'); // "12:00am"
```
### How do I check if a date is valid?
```typescript
const t = new Tempo('invalid-date');
if (t.isValid) {
// ...
}
```
### Global Configuration
You can initialize global defaults that apply to all future `Tempo` instances.
```typescript
Tempo.init({
timeZone: 'UTC',
locale: 'en-GB',
silent: true
});
```
👉 **Learn More:** [Configuration Guide](../2-core-concepts/tempo.config.md)
---
## Parsing Challenges
### Parsing "Ambiguous" Digits (US vs UK)
Tempo intelligently resolves ambiguous dates like `04012026` based on your timezone.
```typescript
const us = new Tempo('04012026', { timeZone: 'America/New_York' });
console.log(us.format('{mon} {dd}')); // "April 01"
```
👉 **Learn More:** [Ambiguity Resolution Guide](../2-core-concepts/tempo.parse.md)
### Handling Relative Strings
Tempo natively understands human-readable offsets.
```typescript
new Tempo('yesterday');
new Tempo('next Friday');
new Tempo('2 weeks ago');
new Tempo('tomorrow afternoon');
```
👉 **Learn More:** You can seamlessly localize relative phrases (e.g. `next` to `prochain`) by reading the [Internationalized Parsing Guide](../2-core-concepts/tempo.parse.md#internationalized-parsing-locales).
### Parsing Unix Timestamps
Tempo handles both milliseconds (Number) and nanoseconds (BigInt).
```typescript
new Tempo(1716163200000); // Milliseconds
new Tempo(1716163200000000000n); // Nanoseconds
```
---
## Manipulation and Calculations
### Add or Subtract Time
Tempo instances are immutable; `add()` returns a new instance.
```typescript
const deadline = new Tempo().add({ days: 7, hours: 2 });
const past = new Tempo().add({ months: -1 });
// You can also step by semantic Terms using the `#` prefix!
const t1 = new Tempo('2024-05-15'); // Middle of Q2
const t2 = t1.add({ '#quarter': 1 }); // Middle of Q3: "2024-08-14" (approx)
```
### Jumping to Boundaries (`start`, `mid`, `end`)
The `.set()` method allows you to jump to the boundaries of native units (like months or years) or semantic Terms (using the `#` prefix). You can specify whether to land on the inclusive start, inclusive end, or the exact center.
```typescript
// Native Units
const monthStart = new Tempo().set({ month: 'start' });
// Semantic Terms (Lands on 30-Sep 23:59:59.999... Inclusive End)
const qtrEnd = new Tempo('2024-07-15').set({ '#quarter': 'end' });
// Lands on the arithmetic nanosecond midpoint of the period
const qtrMid = new Tempo().set({ '#quarter': 'mid' });
```
### Slick Object Mutations
You can navigate relative to your current date by using Slick Shorthand operators directly inside `.set()`. Use the snippet shorthand keys (`yy`, `mm`, `ww`, `dd`, `wkd`, etc.) and provide a string payload containing a directional modifier:
```typescript
const t = new Tempo('2024-05-20'); // Monday
t.set({ mm: '>2' }); // July 20th
t.set({ wkd: '>Fri' }); // May 24th
```
👉 **Learn More:** To read about advanced chaining, order-of-operations, and architectural limitations, see the [Slick Object Mutations Deep Dive](../2-core-concepts/tempo.mutate.md#slick-object-mutations).
### How long until a deadline? (`until`)
```typescript
const t = new Tempo();
const daysLeft = t.until('2025-01-01', 'days');
console.log(`${daysLeft} days remaining`);
```
### Relative Time (`since`)
Generate human-readable relative time strings instantly.
```typescript
const t = new Tempo('yesterday');
console.log(t.since()); // "1d ago"
```
### Comparing & Checking Equality (`compare`, `equals`)
Compare two dates chronologically—even across different timezones—or test equality at instant or unit precision:
```typescript
const nyc = new Tempo('2026-05-10T18:00:00', { timeZone: 'America/New_York' }); // 22:00 UTC
const london = new Tempo('2026-05-10T23:00:00', { timeZone: 'Europe/London' }); // 22:00 UTC (same instant)
const tokyo = new Tempo('2026-05-11T09:00:00', { timeZone: 'Asia/Tokyo' }); // 00:00 UTC (May 10 20:00 in NYC)
// Exact instant comparison (returns -1 | 0 | 1)
Tempo.compare(nyc, london); // 0 (same instant across timezones)
Tempo.compare(nyc, tokyo); // -1 (nyc is 2 hours earlier)
Tempo.compare(nyc); // Compare `nyc` against now (omitted 2nd arg)
// Granular comparison projected into the 1st operand's timezone
Tempo.compare(nyc, tokyo, 'day'); // 0 (both fall on May 10 in America/New_York; 'date' also accepted)
Tempo.compare(nyc, tokyo, { unit: 'hour' }); // -1 (18:00 vs 20:00 in New York)
// Exact instant & unit-level equality
Tempo.equals(nyc, london); // true (same instant across timezones)
nyc.equals(tokyo, 'day'); // true (same calendar day in New York)
nyc.equals('2026-05-10T23:00:00', { unit: 'day' }); // true (raw string inherits nyc's timezone)
nyc.equals('week'); // Is `nyc` in the current ISO week? (compares against now)
```
👉 **Learn More:** See [Comparisons & Predicates](../2-core-concepts/tempo.compare.md) for supported units, `{ unit }` options, `t.is.*` predicates, and timezone projection rules.
---
## Timezones and Locales
### Convert Time to Another Zone
```typescript
const nyc = new Tempo('2024-05-20 10:00', { timeZone: 'America/New_York' });
const london = nyc.set({ timeZone: 'Europe/London' });
console.log(nyc.format('{hh}:{mi}')); // "10:00"
console.log(london.format('{hh}:{mi}')); // "15:00"
```
### Dynamic / Multi-Tenant Context (Functional Options)
Context options (`timeZone`, `locale`, `calendar`, `sphere`) accept supplier functions (`() => string`). Tempo resolves suppliers at instantiation time to construct an immutable, frozen instance:
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';
const requestContext = new AsyncLocalStorage<{ timeZone: string; locale: string }>();
// Configure dynamic suppliers that evaluate against current request context
const t = new Tempo('now', {
timeZone: () => requestContext.getStore()?.timeZone || 'UTC',
locale: () => requestContext.getStore()?.locale || 'en-US'
});
```
👉 **Learn More:** See the [Configuration Guide](../2-core-concepts/tempo.config.md#_4-1-dynamic-functional-context-evaluation) for details on functional options and immutability guarantees.
---
## Business Logic and Terms
### Is it the weekend?
Use the built-in `t.is.weekend()` and `t.is.weekday()` predicates — they are automatically locale-aware (backed by `Intl.Locale.prototype.getWeekInfo()` and Tempo's regional fallback resolver, the same data exposed by `t.intl.info.weekend`), so they adapt to regional weekend days such as Friday & Saturday (`[5, 6]`) in `ar-SA`:
```typescript
// Standard weekend ([6, 7] for Saturday & Sunday in en-US)
const us = new Tempo('2026-12-04', { locale: 'en-US' }); // Friday
us.is.weekend(); // false
us.is.weekday(); // true
// Regional weekend ([5, 6] for Friday & Saturday in ar-SA)
const sa = new Tempo('2026-12-04', { locale: 'ar-SA' }); // Friday
sa.is.weekend(); // true
sa.is.weekday(); // false
```
If you need the raw ISO day-of-week numbers (`1` = Monday … `7` = Sunday), inspect `t.dow` or `t.intl.info.weekend` directly. See the [Comparisons & Predicates Guide](../2-core-concepts/tempo.compare.md) for all built-in `t.is.*` checks (`leapYear`, `today`, `past`, `future`, `dst`, `between`, and custom predicates).
### What Calendar Quarter are we in?
Using the `qtr` Term plugin (`term.qtr` is a convenient alias for the full `term.quarter` property).
```typescript
const t = new Tempo();
console.log(`Current Quarter: ${t.term.qtr}`); // "Q1", "Q2", etc.
```
### Hemispheric Seasons
Tempo Terms are hemisphere-aware.
```typescript
const sydney = new Tempo('2024-07-01', { sphere: 'south' });
console.log(sydney.term.szn); // "Winter"
const london = new Tempo('2024-07-01', { sphere: 'north' });
console.log(london.term.szn); // "Summer"
// or even via the timeZone setting
console.log(new Tempo({ timeZone: 'America/New_York' }).term.szn); // "Summer"
console.log(new Tempo({ timeZone: 'Australia/Sydney' }).term.szn); // "Winter"
```
---
## Formatting and Localization
### Semantic Formatting
Use specific Term tokens like `{#quarter}` or `{#season}` to automatically embed a Term's label (or key) into a format string.
```typescript
const t = new Tempo();
console.log(t.format('We are currently in the {#quarter}')); // "We are currently in the First Quarter"
```
### Format Modifiers & Localization
Format strings support chained colon-modifiers (e.g., `:upper`, `:locale`, `:ord`) to dynamically change the presentation casing or delegate to the native `Intl` API. You can stack them to get the exact presentation required!
```typescript
const t = new Tempo('2024-05-15 15:30', { locale: 'fr-FR' });
t.format('{mon:upper}'); // "MAY" (English Default -> UpperCase)
t.format('{mon:long}'); // "mai" (Native French Intl output via styling bridge)
t.format('{mon:long:upper} {dd}'); // "MAI 15" (Native French Intl output)
```
👉 **Learn More:** See the [Smart Formatting Guide](../2-core-concepts/tempo.format.md) for the complete list of available modifiers.
::: tip
**Tired of typing styling modifiers?**
If you find yourself repeatedly writing `:long` or `:short` for the same localized date structure, save it to the global **FORMATS** registry! This creates a clean, reusable shortcut:
```typescript
Tempo.init({
locale: 'fr-FR',
registry: {
formats: {
'ui-date': '{wkd:long}, {dd:raw} {mon:long} {yyyy}'
}
}
});
t.format('ui-date'); // Resolved with all modifiers intact!
```
*Note: Format keys are resolved case-sensitively from the global `registry.formats` object. If the requested key is not found, Tempo will simply treat the provided string as a literal layout string rather than throwing an error.*
:::
👉 **Learn More:** To build custom zero-overhead logic evaluators (like Fiscal Years or native Intl bridges), read the [Custom Format Tokens Deep Dive](../2-core-concepts/tempo.format.md#🛠️-custom-format-tokens).
👉 **Learn More:**
- [Smart Formatting Guide](../2-core-concepts/tempo.format.md)
- [Internationalization & Locale](../4-advanced-reference/tempo.intl.md)
- [Smart Parsing Guide](../2-core-concepts/tempo.parse.md)
---
### Ticker Plugin
The Ticker engine is a community plugin for precisely driving business logic (like recurring billing or reporting cycles) on specific date boundaries.
```typescript
// Drive internal reporting precisely when a new quarter begins
await using quarterly = Tempo.ticker({ '#quarter': 1 });
for await (const t of quarterly) {
generateReport(t.term.qtr);
}
```
👉 **Learn More:** See the [Ticker Plugin Documentation](../../../plugins/ticker/doc/index.md) for detailed configuration, term-driven intervals, and `await using` syntax requirements.
---
### Format & Parse Dialects Plugin (Moment, Luxon, SQL, POSIX, PHP)
If you are migrating existing code or layouts from Moment.js, Luxon, date-fns, POSIX `strftime`, PHP, or SQL, use the [`@tempo-kit/plugin-dialects`](../../../plugins/dialects/doc/index.md) community plugin.
```typescript
// Zero-config drop-in import automatically mounts dialect shims:
import '@tempo-kit/plugin-dialects/install';
const t = new Tempo('2026-10-24T15:30:00');
// Luxon convenience shim (.toFormat)
t.toFormat('yyyy-MM-dd HH:mm:ss'); // "2026-10-24 15:30:00"
// LDML & Moment parsing
Tempo.fromFormat('2026-10-24', 'yyyy-MM-dd'); // LDML parsing via Luxon shim
Tempo.dialects.parse('2026-10-24', 'YYYY-MM-DD', 'moment'); // Moment layout parsing
// Direct dialect formatters
t.dialects.sql('YYYY-MM-DD HH24:MI:SS'); // Oracle / PostgreSQL TO_CHAR
t.dialects.php('Y-m-d H:i:s'); // PHP date()
t.dialects.go('2006-01-02 15:04:05'); // Go reference layout
```
👉 **Learn More:** See the [Dialects Plugin Documentation](../../../plugins/dialects/doc/index.md) for full token specifications, multi-candidate parsing fallbacks, and cross-ecosystem translation.
---
## Interoperability
### Converting to / from Native `Date`
```typescript
const date = new Tempo().toDate();
const tempo = new Tempo(new Date());
```
### Converting to `Temporal` Objects
```typescript
const zdt = new Tempo().toDateTime(); // Temporal.ZonedDateTime (or .toDateTime())
const instant = new Tempo().toInstant(); // Temporal.Instant
const pdt = new Tempo().toPlainDate(); // Temporal.PlainDate
```
### Sorting an array of Tempos
`Tempo.compare` compares exact instants on the timeline, so standard sorting automatically handles any mix of timezones and calendars with zero manual alignment:
```typescript
const dates = [
new Tempo('2026-05-11T09:00:00', { timeZone: 'Asia/Tokyo' }), // May 11 00:00 UTC
new Tempo('2026-05-10T18:00:00', { timeZone: 'America/New_York' }), // May 10 22:00 UTC (2h earlier)
new Tempo('2026-05-10T23:00:00', { timeZone: 'Europe/London' }), // May 10 22:00 UTC (same instant as NYC)
];
dates.sort(Tempo.compare); // Chronological order across mixed timezones
```
When sorting at a coarser **unit** granularity (such as `'day'` or `'month'`), pass an `anchor` or explicit `timeZone` / `calendar` in `CompareOptions` so Tempo evaluates every pair against one consistent reference frame:
```typescript
// Option A: Anchor mixed items to a reference Tempo (e.g. dates[0])
dates.sort((a, b) => Tempo.compare(a, b, { unit: 'day', anchor: dates[0] }));
// Option B: Normalize evaluations to an explicit fixed timezone & calendar (order-independent)
dates.sort((a, b) => Tempo.compare(a, b, { unit: 'day', timeZone: 'UTC', calendar: 'iso8601' }));
```
::: info Granular Sorting: `anchor` vs. Fixed Frame
Without `anchor` or `timeZone` / `calendar`, `Tempo.compare(a, b, 'day')` evaluates in `a`'s timezone and calendar—which is asymmetric if `.sort()` swaps mixed-zone elements freely. Passing `anchor: dates[0]` is convenient when the first item defines your reference zone, though different initial array orders can change which element acts as the anchor; specifying a fixed `{ timeZone, calendar }` guarantees deterministic results regardless of input order.
:::
---
# Document: 1-getting-started/tempo.repl.md
# Interactive REPL & Feature Showcase
Tempo offers two dedicated, zero-install in-browser environments running 100% client-side via native ECMAScript Modules (`esm.sh`):
1. [**🎨 Feature Showcase & Workbench**](#interactive-feature-showcase): A dynamic, visual sandbox to test format tokens, chained mutations, relative durations, world geolocation, and astronomical ephemeris in real time with auto-generated TypeScript code.
2. [**⚡ Freeform Code REPL**](#freeform-code-repl): A freeform JavaScript/TypeScript code editor with real-time evaluation, console streaming, official plugin preloading, and snippet URL sharing.
---
## 🎨 Interactive Feature Showcase {#interactive-feature-showcase}
Explore live formatting, chained mutations, hemisphere-aware astronomical seasons, and celestial mechanics without writing boilerplate:
---
## Key Capabilities
### 1. Preloaded Official Plugins
Both environments pre-register the standard `Tempo` class along with default official plugins:
- `@tempo-kit/plugin-geo`
- `@tempo-kit/plugin-celestial`
You can immediately access Terms, seasons, and celestial data without import boilerplate:
```javascript
const t = new Tempo('today', { geo: { lat: -33.86, lng: 151.2 } });
console.log(t.term.szn); // "Spring"
console.log(t.term.lunar.phase); // "First Quarter"
```
### 2. Dynamic Plugin Loading & Presets
Need an additional plugin like `@tempo-kit/plugin-spatial`, `@tempo-kit/plugin-ticker`, or custom third-party modules? Select their preset from the preset dropdown or use standard dynamic imports in the Code REPL:
```javascript
const { SpatialPlugin } = await import('@tempo-kit/plugin-spatial');
Tempo.use(SpatialPlugin);
console.log('Spatial plugin active!');
```
### 3. AI Semantic Parsing & Natural Language Scheduling
Explore generative date parsing, conversational recurrence, and multi-point event scheduling powered by [`@tempo-kit/plugin-ai`](/doc/9-plugins/ai.index):
- Select the **Preset: AI Semantic Parsing & Scheduling** from the preset dropdown.
- **Supported Provider Configuration (BYOK)**: Provide an API key or local endpoint in `Tempo.ai.init({ providers: [...] })` before calling `Tempo.ai.parse` or `Tempo.ai.schedule`.
- **External Resources & Free Keys**:
- **[Groq Console](https://console.groq.com/keys)**: Ultra-fast inference with a generous free tier (recommended for quick testing).
- **[Google AI Studio (Gemini)](https://aistudio.google.com/app/apikey)**: Free API key for Gemini models.
- **[OpenAI Platform](https://platform.openai.com/api-keys)**: Standard GPT-4o / GPT-4o-mini keys.
- **[Ollama](https://ollama.com)**: 100% free, private local LLMs. *Note: When running locally for browser access, start Ollama with CORS enabled: `OLLAMA_ORIGINS="*" ollama serve`.*
> [!WARNING]
> **API Key Safety in Share Links**:
> When you click **📋 Share**, the editor content is encoded into the URL hash (`#code=...`). **Never paste production or sensitive API keys into shared snippets**. For live testing, use ephemeral personal sandbox keys or local Ollama.
### 4. Shareable Snippets & Presets
- **Share**: Click the **📋 Share** button in the REPL header to encode your code directly into a shareable URL hash (`#code=...`).
- **Copy Code**: Click **📋 Copy Code** in the Showcase to grab production-ready TypeScript code for your current visual setup.
### 5. Keyboard Shortcuts
- **`Ctrl + Enter`** (Windows/Linux) or **`Cmd + Enter`** (macOS): Immediately re-evaluate the current editor code.
- **`Tab`**: Inserts 2-space indentation.
---
# Document: 2-core-concepts/tempo.cache.md
# Cache Management Guide
**Tempo** includes a centralized, high-performance **`BoundedCache`** singleton accessible via `Tempo.cache`. It provides dual-layer resolution for dynamic relative dates (with LRU eviction and TTL expiration) and static business glossaries (immortal keys).
---
## 🏛️ Centralized Cache Architecture
All date resolution caching—whether triggered by standard `Tempo` parsing or the Tempo AI plugin (`parseAI`, `formatAI`, `contextAI`)—is managed centrally by `Tempo.cache`.
::: info Cache Behavior: Standard Tempo vs. Tempo AI Plugin
* **Standard Tempo**: Caching is **opt-in**. Built-in date parsing executes at sub-microsecond speeds using standard regex matching. `Tempo.cache` is consulted when you seed a static glossary or enable caching.
* **Tempo AI Plugin**: Caching is **automatic**. To eliminate network latency (~500ms+) and avoid redundant LLM API billing, AI functions (like `parseAI`) automatically check `Tempo.cache` before sending network requests and cache every successful LLM resolution.
:::
### Cache Topology & Configuration
You can configure global cache parameters using `Tempo.init()`:
```typescript
import { Tempo } from 'tempo-kit';
Tempo.init({
cache: {
maxSize: 1000, // Maximum number of entries before LRU eviction (default: 1000)
ttl: 24 * 60 * 60 * 1000 // Time-to-live in milliseconds (default: 24 hours)
}
});
```
* **Capacity Management (LRU):** When the cache reaches `maxSize`, the Least Recently Used dynamic entry is automatically evicted.
* **TTL Expiration:** Dynamic entries older than `ttl` are automatically purged upon lookup.
* **Static Glossary Isolation:** Static entries added to the glossary are **exempt** from both LRU eviction and TTL expiration.
---
## 📖 Seeding & Appending Glossaries
You can seed static business terms into `Tempo.cache` using a native JavaScript `Map` or via `Tempo.init({ cache: map })`:
```typescript
const businessGlossary = new Map([
['fiscal year start 2026', '2026-07-01T00:00:00Z'],
['q3 board review', '2026-09-15T09:00:00Z']
]);
// Appends entries to Tempo.cache as static, immortal terms
Tempo.init({ cache: businessGlossary });
```
::: tip Non-Destructive Appending
Passing a `Map` or custom key-value pairs to `Tempo.init({ cache })` or `initAI({ cache })` **appends** to the existing cache without clearing previously cached terms or resetting cache capacity settings.
:::
---
## 💡 When to Use What: Glossary vs. Alias vs. Snippet/Layout
Tempo provides multiple mechanisms for augmenting parsing intelligence. Choosing the right pattern depends on whether your logic is static, dynamic, structural, or string replacement:
| Mechanism | Tier / Location | Evaluation Model | Best Used For... |
| :--- | :--- | :--- | :--- |
| **Glossary** (`Tempo.cache`) | Built-in Engine | Zero-cost $O(1)$ Map lookup | Pre-calculated static ISO date/time strings or exact business dates. |
| **Aliases / Events / Periods** (`registry.events` / `periods`) | Registry Engine | Dynamic function or target string | Computing dynamic business dates (e.g. `'deadline' => () => this.add({ days: 30 })`). |
| **Snippet / Layouts** (`registry.snippets` / `layouts`) | Parser Planner | Regex pattern matcher | Structural natural language formats (e.g. `yyyy/mm/dd` or custom date tokens). |
### Decision Tree
1. **Use a Glossary (`Tempo.cache`)** when you have fixed, pre-resolved ISO dates for specific terms (e.g., `'eoy 2026'` -> `'2026-12-31T23:59:59Z'`). It offers instant $O(1)$ resolution without invoking the regex parser.
2. **Use an Alias (`registry.events` / `periods`)** when you need dynamic rules calculated relative to the current date/time (e.g., `'market-close'` -> `'16:00'` or `'deadline'` -> `30 days from now`).
3. **Use a Snippet or Layout (`registry.snippets` / `layouts`)** when parsing custom input structures with variable numbers or tokens (e.g. `"2026-W05"` or `"Quarter 3, 2026"`).
---
## 🤖 AI Plugin Cache Integration (`@tempo-kit/plugin-ai`)
The `@tempo-kit/plugin-ai` plugin works hand-in-hand with `Tempo.cache` to reduce LLM API calls and costs across AI functions:
```typescript
import { Tempo } from 'tempo-kit';
import { parseAI, initAI } from '@tempo-kit/plugin-ai';
initAI({ providers: [...] });
// First lookup: Triggers LLM call -> Stores ISO result in Tempo.cache
const t1 = await parseAI("The penultimate Tuesday before Thanksgiving in 2026");
// Second lookup: Instantly resolves from Tempo.cache (O(1) local hit, $0 cost)
const t2 = new Tempo("The penultimate Tuesday before Thanksgiving in 2026");
```
### Two-Tier Resolution Architecture
1. **Date-Salted Relative Cache**: Relative queries (e.g. `"next Tuesday"`) are salted with the anchor date so cached entries remain valid for the given day.
2. **Static Glossary Fallback**: Business glossary terms seeded via `initAI({ cache })` or `Tempo.init({ cache })` are checked first, providing zero-latency resolution without ever contacting the LLM.
---
# Document: 2-core-concepts/tempo.compare.md
# Comparisons & Predicates
Comparing dates, sorting timelines, checking whether an event falls inside a billing window, or testing calendar states like weekends and Daylight Saving Time are among the most common operations in any date-time application.
Tempo organizes these into three complementary surfaces:
- **`Tempo.compare(a, b, unitOrOptions?)`** — Three-way comparator (`-1 | 0 | 1`) designed for sorting (`dates.sort(Tempo.compare)`).
- **`Tempo.equals(a, b, unitOrOptions?)` / `t.equals(other?, unitOrOptions?)`** — Non-throwing equality checks at exact instant or calendar-unit granularity.
- **`t.is.*`** — A lazy-memoized, frozen, extensible predicate namespace for readable relational checks, interval bounds (`between`), 7 built-in calendar/state checks, and your own domain predicates via `config.registry.predicates`.
---
## Sorting & Three-Way Comparison (`Tempo.compare`) {#tempo-compare}
`Tempo.compare(a, b, unitOrOptions?)` returns `-1` if `a` is earlier than `b`, `0` if equal, or `1` if later. Because its signature matches `Array.prototype.sort` and compares **exact instants** (`epoch.ns`) by default, passing `Tempo.compare` sorts events across different timezones in true chronological order — even when their wall-clock times appear out of order:
```typescript
import { Tempo } from 'tempo-kit';
const events = [
new Tempo('2026-06-15T09:00:00', { timeZone: 'America/New_York' }), // 13:00Z
new Tempo('2026-06-15T20:00:00', { timeZone: 'Australia/Sydney' }), // 10:00Z
new Tempo('2026-06-15T20:30:00', { timeZone: 'Asia/Tokyo' }), // 11:30Z
new Tempo('2026-06-15T12:00:00', { timeZone: 'UTC' }), // 12:00Z
];
events.sort(Tempo.compare).map((t) => `${t.tz} (${t.iso})`);
// → [
// 'Australia/Sydney (2026-06-15T10:00:00Z)',
// 'Asia/Tokyo (2026-06-15T11:30:00Z)',
// 'UTC (2026-06-15T12:00:00Z)',
// 'America/New_York (2026-06-15T13:00:00Z)',
// ]
```
By default, `Tempo.compare()` compares **exact instants** (`epoch.ns`), so two `Tempo` values in different timezones that represent the same moment return `0`. Pass a `CompareUnit` or `CompareOptions` object to compare at calendar/time granularity or within a specific timezone/calendar frame:
```typescript
const morning = new Tempo('2026-06-15T08:00:00Z');
const evening = new Tempo('2026-06-15T20:00:00Z');
Tempo.compare(morning, evening); // → -1 (exact instant)
Tempo.compare(morning, evening, 'day'); // → 0 (same calendar day)
Tempo.compare(morning, evening, 'hour'); // → -1 (08:00 < 20:00)
// Evaluate calendar-day boundary in a specific timezone
const lateUtc = new Tempo('2026-06-15T22:00:00Z');
const earlyUtc = new Tempo('2026-06-15T02:00:00Z');
Tempo.compare(lateUtc, earlyUtc, { unit: 'day', timeZone: 'UTC' }); // → 0
Tempo.compare(lateUtc, earlyUtc, { unit: 'day', timeZone: 'Australia/Sydney' }); // → 1 (June 16 vs June 15)
```
> [!NOTE]
> `Tempo.compare()` throws a `RangeError` if either operand (or `options.anchor`) is invalid, matching `Temporal.*.compare()`. For non-throwing boolean checks, use `Tempo.equals()`, `t.equals()`, or `t.is.*`.
---
## Equality (`Tempo.equals` & `t.equals`) {#tempo-equals}
Both `Tempo.equals(a, b, unitOrOptions?)` and instance `t.equals(other?, unitOrOptions?)` return `boolean` and never throw on invalid inputs (returning `false` instead):
```typescript
const a = new Tempo('2026-06-15T10:00:00Z');
const b = new Tempo('2026-06-15T20:00:00+10:00[Australia/Sydney]');
const c = new Tempo('2026-06-15T18:30:00Z');
a.equals(b); // → true (same exact instant)
a.equals(c); // → false (different instants)
a.equals(c, 'day'); // → true (same calendar day)
// Omitting `other` compares against `now`
new Tempo().equals('day'); // → true
```
---
## Relational Predicates (`t.is.*`) {#relational-predicates}
Every `Tempo` instance exposes a lazy-memoized, `Object.freeze()`-protected **`t.is`** namespace. Accessing `t.is` allocates once per instance (`t.is === t.is`) and incurs $O(0)$ overhead on instances that never read it.
| Method | Meaning | Default (`other` omitted) |
| :--- | :--- | :--- |
| `t.is.before(other?, unitOrOpts?)` | `t < other` | Compares against `now` |
| `t.is.after(other?, unitOrOpts?)` | `t > other` | Compares against `now` |
| `t.is.same(other?, unitOrOpts?)` | `t === other` | Compares against `now` |
| `t.is.sameOrBefore(other?, unitOrOpts?)` | `t ≤ other` | Compares against `now` |
| `t.is.sameOrAfter(other?, unitOrOpts?)` | `t ≥ other` | Compares against `now` |
```typescript
const launch = new Tempo('2026-06-15T10:00:00Z');
const cutoff = new Tempo('2026-06-15T14:30:00Z');
launch.is.before(cutoff); // → true
launch.is.after(cutoff); // → false
launch.is.same(cutoff, 'day'); // → true
launch.is.sameOrBefore(cutoff); // → true
cutoff.is.sameOrAfter(launch); // → true
// Single-argument unit shorthand compares against `now`
new Tempo().is.same('day'); // → true
new Tempo('2000-01-01').is.before('year'); // → true
```
All `t.is.*` predicates return `false` without throwing when `this` or any comparison operand is invalid.
---
## Range Checks (`t.is.between` & `Tempo.enums.BOUNDS`) {#between-and-bounds}
`t.is.between()` checks whether `this` falls inside a bounded or open-ended range. It accepts either two positional endpoints or an `Interval` / `{ start, end }` object:
```typescript
const start = new Tempo('2026-06-01T00:00:00Z');
const mid = new Tempo('2026-06-15T12:00:00Z');
const end = new Tempo('2026-07-01T00:00:00Z');
// Positional endpoints (default: half-open '[)' → start ≤ t < end)
mid.is.between(start, end); // → true
start.is.between(start, end); // → true
end.is.between(start, end); // → false
// Interval or { start, end } range overload
const june = new Tempo.Interval(start, end);
mid.is.between(june); // → true
mid.is.between({ start, end }); // → true
```
### Boundary Inclusivity (`Tempo.enums.BOUNDS`) {#bounds-enum}
`Tempo.enums.BOUNDS` defines the four standard mathematical interval modes. The default is **`halfOpen` (`'[)'`)**, matching `Interval` slicing, `Temporal` range conventions, and contiguous partitioning (so adjacent months `[Jun 1, Jul 1)` and `[Jul 1, Aug 1)` never double-count midnight on July 1):
| Enum Member | String | Condition |
| :--- | :---: | :--- |
| `Tempo.enums.BOUNDS.halfOpen` *(default)* | `'[)'` | `start ≤ t < end` |
| `Tempo.enums.BOUNDS.inclusive` | `'[]'` | `start ≤ t ≤ end` |
| `Tempo.enums.BOUNDS.exclusive` | `'()'` | `start < t < end` |
| `Tempo.enums.BOUNDS.leftOpen` | `'(]'` | `start < t ≤ end` |
Pass `bounds` inside the options object (optionally combined with `unit`, `timeZone`, `calendar`, or `anchor`):
```typescript
const { inclusive, exclusive, leftOpen } = Tempo.enums.BOUNDS;
end.is.between(start, end, { bounds: inclusive }); // → true
start.is.between(start, end, { bounds: exclusive }); // → false
end.is.between(start, end, { bounds: leftOpen }); // → true
// Combine unit granularity with inclusive bounds
const july1Evening = new Tempo('2026-07-01T20:00:00Z');
july1Evening.is.between(start, end, { unit: 'day', bounds: inclusive }); // → true
```
### Open-Ended & Inverted Ranges
- **Open-ended boundaries**: Pass `null` for `start` or `end` to leave that side unbounded (`t.is.between(null, cutoff)` or `t.is.between({ start, end: null })`).
- **Inverted ranges**: If both endpoints are bounded and `start > end`, `between()` returns `false`.
- **Invalid bounds string**: Passing an unrecognized `bounds` value throws a `RangeError`.
---
## Built-In Calendar & State Checks {#calendar-state-checks}
`t.is` ships with 7 built-in calendar and temporal state predicates (all zero-argument methods returning `boolean`):
| Method | Behavior |
| :--- | :--- |
| `t.is.leapYear()` | `true` if `this`'s year is a leap year in its active calendar (`zdt.inLeapYear`). |
| `t.is.weekend()` | Locale-aware weekend check using `Intl.Locale` `weekInfo.weekend` (defaults to Sat/Sun `[6, 7]`; e.g., Fri/Sat `[5, 6]` for `ar-SA` and `he-IL`). |
| `t.is.weekday()` | Logical inverse of `t.is.weekend()` (returns `false` on invalid instances). |
| `t.is.today()` | Dynamic check: `true` if `this` falls on the same calendar day as `now` in `this`'s timezone. |
| `t.is.past()` | Dynamic check: `true` if `this.epoch.ns < now.epoch.ns`. |
| `t.is.future()` | Dynamic check: `true` if `this.epoch.ns > now.epoch.ns`. |
| `t.is.dst()` | `true` if `this` is currently observing Daylight Saving Time in its timezone (`false` for UTC and fixed-offset zones). |
```typescript
// Leap year
new Tempo('2024-06-01').is.leapYear(); // → true
new Tempo('2026-06-01').is.leapYear(); // → false
// Locale-aware weekend / weekday
new Tempo('2026-06-12', { locale: 'en-US' }).is.weekend(); // → false (Friday in US)
new Tempo('2026-06-12', { locale: 'ar-SA' }).is.weekend(); // → true (Friday in Saudi Arabia)
// Dynamic relative checks
new Tempo().is.today(); // → true
new Tempo().subtract({ days: 1 }).is.past(); // → true
new Tempo().add({ days: 1 }).is.future(); // → true
// Daylight Saving Time
new Tempo('2026-01-15T12:00:00', { timeZone: 'Australia/Sydney' }).is.dst(); // → true (AEDT +11)
new Tempo('2026-07-15T12:00:00', { timeZone: 'Australia/Sydney' }).is.dst(); // → false (AEST +10)
new Tempo('2026-01-15T12:00:00Z', { timeZone: 'UTC' }).is.dst(); // → false
```
---
## Extensible Custom Predicates (`config.registry.predicates`) {#custom-predicates}
You can register domain-specific predicates onto `t.is` globally via `Tempo.init()` or in an isolated sandbox via `Tempo.extend()`:
```typescript
import { Tempo } from 'tempo-kit';
const BizTempo = Tempo.extend({
registry: {
predicates: {
businessHour: (t) => t.is.weekday() && t.hh >= 9 && t.hh < 17,
olderThan: (t, years: number) => t.is.before(new Tempo().subtract({ years })),
},
},
});
const mondayMorning = new BizTempo('2026-06-15T10:30:00', { locale: 'en-US' });
mondayMorning.is.businessHour(); // → true
mondayMorning.is.olderThan(5); // → false
```
### TypeScript Autocomplete (`TempoPredicateRegistry`)
Augment `TempoPredicateRegistry` in your app or plugin's `.d.ts` file to get full IDE autocomplete and type checking for custom predicates:
```typescript
import 'tempo-kit';
declare module 'tempo-kit' {
interface TempoPredicateRegistry {
businessHour(): boolean;
olderThan(years: number): boolean;
}
}
```
### Safety & Override Rules
- **Core relational operators are locked**: The 6 structural operators (`before`, `after`, `same`, `sameOrBefore`, `sameOrAfter`, `between`) cannot be overwritten by `registry.predicates`.
- **State predicates are sandbox-overridable**: The 7 built-in pure state predicates (`leapYear`, `weekend`, `weekday`, `today`, `past`, `future`, `dst`) are seeded in `Default.registry.predicates`, so you can shadow them inside a `Tempo.extend()` sandbox (e.g., overriding `weekend: (t) => [5, 6, 7].includes(t.dow)` for a 4-day workweek, which `weekday()` automatically reflects) without affecting the global `Tempo` class.
- **Prototype safety**: Unsafe keys (`__proto__`, `constructor`, `prototype`) are ignored via `isSafeKey()`.
- **Boolean coercion & invalid-instance guard**: Return values are coerced via `Boolean(...)`, and invalid `Tempo` instances return `false` without invoking the custom predicate.
- **Sandbox isolation**: Predicates registered via `Tempo.extend({ registry: { predicates } })` stay scoped to that sandbox and do not leak onto the global `Tempo` class.
---
# Document: 2-core-concepts/tempo.config.md
# Configuration Guide
**Tempo** provides a flexible, multi-tiered configuration system. Settings are applied in a specific order of precedence, allowing you to set broad defaults that can be refined at the application or instance level.
## Precedence Hierarchy
Settings are loaded in the following order (where later stages override earlier ones):
1. **Library Defaults**: Sensible out-of-the-box baseline.
2. **Persistent Storage**: Sticky user preferences (which merge into Defaults).
3. **Global Discovery**: Enterprise-level setup discovered via `Symbol.for('$Tempo')`.
4. **Library Extension**: Dynamic feature registration via `Tempo.use()`.
5. **Explicit Initialization**: Baseline configuration via `Tempo.init()`.
6. **Instance Constructor**: Specific overrides for a single `new Tempo()` call.
---
## 🏆 Best Practice: The `tempo.config.ts` Pattern
Rather than scattering `Tempo.init()` or `Tempo.use()` calls throughout your application, the recommended best practice is to centralize your environment setup into a single `tempo.config.ts` (or `.js`) file.
This mirrors modern ecosystem standards (like `vite.config.ts` or `tailwind.config.js`) and ensures that plugins, timezones, and custom aliases are consistently applied before any domain logic executes.
::: info Target Environment & Discovery
**Automatic zero-config discovery** relies on Node.js file system capabilities and is exclusive to Server and Node.js environments.
In bundled frontend environments (like Vite or Webpack), you can still maintain a central `tempo.config.ts`, but you must explicitly import and pass it to `Tempo.init(config)` at your application entry point (e.g. `main.ts`). If you are using Tempo via a `
```
---
## 5. Authoring Custom Plugins
Interested in creating your own plugin? Check out the [Creating Custom Plugins Guide](../3-extending-tempo/tempo.extension.md) and [Plugin Ecosystem Catalog](../3-extending-tempo/ecosystem.md) to learn how to register custom getters, term definitions, and dynamic proxies.
---
# Document: 9-plugins/ai.architecture.md
# Provider Architecture & Security
The `@tempo-kit/plugin-ai` plugin is designed to be highly flexible, supporting both direct Bring Your Own Key (BYOK) integrations for backend systems, and Proxied integrations for frontend clients.
## Bring Your Own Key (BYOK) & Zero-Config Discovery
For Node.js, Deno, and Bun backends, `@tempo-kit/plugin-ai` supports **Zero-Config Auto-Discovery**. If standard environment variables (`GROQ_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `MISTRAL_API_KEY`) are present, calling `initAI()` is optional—the plugin will automatically discover credentials and wire up provider defaults lazily on first function call.
Alternatively, you can supply your API keys and execution options explicitly via `initAI`:
```typescript
import { initAI } from '@tempo-kit/plugin-ai';
initAI({
providers: [
...(process.env.GROQ_API_KEY ? [{ id: 'groq', key: process.env.GROQ_API_KEY }] : []),
...(process.env.GEMINI_API_KEY ? [{ id: 'gemini', key: process.env.GEMINI_API_KEY }] : []),
...(process.env.OPENAI_API_KEY ? [{ id: 'openai', key: process.env.OPENAI_API_KEY }] : [])
]
});
```
### Advanced Configuration (Custom Models & LLM Options)
By default, standard providers automatically map to their optimal APIs and default models.
However, you can explicitly override URLs, models, and inject arbitrary LLM parameters (like `temperature`) for power-user control!
```typescript
initAI({
providers: [
// 1. Enterprise Azure OpenAI (via Entra ID Bearer token or backend proxy wrapper)
// Note: BYOK requests send 'Authorization: Bearer '. When connecting to Azure OpenAI,
// supply an Entra ID bearer token as provider.key or route through an Azure API gateway.
...(process.env.AZURE_ENTRA_BEARER_TOKEN ? [{
id: 'openai',
key: process.env.AZURE_ENTRA_BEARER_TOKEN,
url: 'https://my-enterprise.openai.azure.com/v1/chat/completions',
model: 'your-enterprise-model',
options: { temperature: 0.2, seed: 42 }
}] : []),
// 2. Local Open-Source Models (e.g. Ollama)
{
id: 'local',
key: 'no-key-needed',
url: 'http://localhost:11434/v1/chat/completions',
model: 'your-local-model',
options: { timeout: 5000 } // Custom provider-level timeout (5s)
}
]
});
```
### Per-Request Lazy Resolution & Fallback Defaults
When dispatching requests via `transport.ts`, all provider fields (`key`, `url`, `model`) and execution context (`timeZone`, `locale`, `calendar`, `sphere`) are resolved lazily just-in-time using functional evaluation (`evaluate` / `evaluateAsync`):
1. **Explicit Dynamic Suppliers**: If a supplier function was provided (e.g. `key: async () => await getRotatedKey()`), it is called per-dispatch.
2. **Built-in Fallbacks**: If a property is omitted or resolves to `undefined`, the transport layer seamlessly cascades to the compiled `DEFAULT_PROVIDERS` templates, remote manifest endpoints, and auto-discovered environment variables.
3. **No Configuration Mutation**: The dynamic resolution runs ephemerally per HTTP dispatch without mutating or locking shared global provider state.
### Dynamic Provider Manifests & Remote Endpoint Trust
By default, `@tempo-kit/plugin-ai` lazily fetches provider defaults (model IDs, endpoints, token parameter keys) from `https://tempo-kit.web.app/providers.v1.json` once per application lifecycle.
- **Remote Manifest Trust & Endpoint Enforcement**:
- `remoteConfigUrl` must use `https:` (or `http://localhost` / `http://127.0.0.1`), enforced by `isValidManifestUrl()`. It is not restricted to a fixed host allowlist, so applications must not pass untrusted user-supplied URLs to `remoteConfigUrl`.
- Any dynamic `provider.url` values received from the manifest or dynamically returned via `fetchDefaults` must use verified HTTPS or localhost origins before `getResolvedProviderDefaults()` merges them into runtime provider configurations. HTTPS validation alone does not enforce a provider host allowlist, so manifest content must also be trusted. Unauthenticated HTTP (non-localhost) or malformed URLs are rejected and stripped before merging.
- **Validation on `fetchDefaults` Hook**: The same HTTPS/localhost origin verification is enforced when resolving custom provider options via the `fetchDefaults` callback. Any dynamic hook attempting to return non-HTTPS (non-localhost) or malformed URLs will have the `url` property safely discarded.
- **Async Resolution & Promise Lifecycle**: `initAI()` returns a `Promise`.
- **Synchronous Fire-and-Forget**: Calling `initAI(...)` synchronously without `await` immediately initializes system state with compiled local provider defaults (`DEFAULT_PROVIDERS`). You can execute `parseAI()` immediately on the next line without blocking. The remote manifest is fetched in the background and transparently updates provider defaults once received.
- **Guaranteed Remote Resolution**: If your application strictly requires remote provider defaults to be resolved before executing your first AI request, you can `await initAI(...)`:
```typescript
// Await guaranteed remote manifest completion before proceeding
await initAI({
providers: [{ id: 'groq', key: process.env.GROQ_API_KEY! }]
});
```
- **Fail-Open & Air-Gapped Fallback**: If the network request fails, times out (1500ms limit), or the application is running offline or in an air-gapped environment, `initAI()` automatically and silently falls back to compiled local defaults (`DEFAULT_PROVIDERS`).
- **Disabling Remote Manifest**: Pass `remoteConfigUrl: false` to disable remote manifest fetching entirely:
```typescript
initAI({
providers: [{ id: 'groq', key: process.env.GROQ_API_KEY! }],
remoteConfigUrl: false // Disable remote manifest fetching
});
```
### Frontend Security Warning
> [!CAUTION]
> **Never** expose a raw LLM API key in a client-side browser bundle (like React, Vue, or Svelte) or store it in any browser storage (`localStorage`, `sessionStorage`, `IndexedDB`, `OPFS`, or browser cache). We strongly recommend **zero browser storage** for API credentials; any Cross-Site Scripting (XSS) vulnerability, compromised NPM dependency, or malicious browser extension can inspect client-side storage and extract secret keys, leading to quota drainage, unexpected billing spikes, or account bans. BYOK provider keys are *only* safe on backend servers and edge workers.
## Browser & Client-Side Proxy Architecture
To execute AI functions within client-side browser applications safely, route requests through a secure self-hosted backend proxy or unified AI Gateway (such as a Cloudflare Worker, Next.js API route, Express server, OpenRouter, Portkey, or LiteLLM):
```mermaid
flowchart LR
subgraph Browser ["Client-Side Browser (SPA)"]
Client["Tempo AI Plugin (initAI / parseAI / diffAI)"]
end
subgraph Backend ["Self-Hosted Proxy / AI Gateway"]
Proxy["Your Backend API / AI Gateway • User Authentication & Rate Limits • Secure Secret Management"]
end
subgraph Providers ["Upstream LLM Providers"]
LLM["Groq • OpenAI • Gemini • Anthropic"]
end
Client -- "1. HTTPS (TLS 1.2+) Bearer Token / Auth Header" --> Proxy
Proxy -- "2. HTTPS (TLS 1.2+) Private Provider API Key" --> LLM
LLM -- "3. HTTPS (TLS 1.2+) Raw JSON Completion" --> Proxy
Proxy -- "4. HTTPS (TLS 1.2+) Validated Payload" --> Client
```
### 1. Browser Configuration Example
Configure `initAI` in your browser code to target your backend proxy or AI Gateway URL:
```typescript
import { initAI, parseAI } from '@tempo-kit/plugin-ai';
// Safe for browser deployment: No private LLM API keys are bundled
await initAI({
providers: [
{
id: 'my-gateway',
url: 'https://api.mycompany.com/v1/ai/chat/completions', // Your secure proxy endpoint
key: userSessionToken, // Short-lived user Bearer JWT token
model: 'llama-3.3-70b-instruct'
}
]
});
// All Tempo AI functions now execute securely through your proxy
const date = await parseAI("Team standup next Wednesday at 9:30am");
```
### 2. Backend Proxy Handler Example (Next.js / Cloudflare Worker / Express)
Your backend endpoint receives the request, validates the user's session, enforces ingress quotas, attaches your private LLM API key, and forwards the validated payload to the upstream provider:
```typescript
// Example: Next.js API Route / Cloudflare Worker / Express Proxy Handler
export async function POST(req: Request, env?: { GROQ_API_KEY?: string }) {
// 1. Authenticate user session
const authHeader = req.headers.get('Authorization');
const session = await validateUserSession(authHeader);
if (!session) {
return new Response('Unauthorized', { status: 401 });
}
// 2. Ingress validation & per-user quota enforcement
const body = await req.json();
if (typeof body?.prompt !== 'string' || body.prompt.length > 4096) {
return new Response('Invalid prompt or payload exceeds size limit', { status: 400 });
}
if (!checkUserRateLimit(session.userId)) {
return new Response('Too Many Requests', { status: 429 });
}
// 3. Resolve API key (Cloudflare Worker env binding or Node/Next.js process.env)
const apiKey = env?.GROQ_API_KEY || (typeof process !== 'undefined' ? process.env?.GROQ_API_KEY : undefined);
if (!apiKey) {
return new Response('Provider key configuration missing', { status: 500 });
}
// 4. Construct upstream fetch with bounded timeout and cleanup
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s upstream limit
try {
const upstreamResponse = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'openai/gpt-oss-120b',
messages: body.messages,
temperature: 0.1,
}),
signal: controller.signal
});
// 5. Return provider payload to client
const data = await upstreamResponse.json();
return new Response(JSON.stringify(data), {
status: upstreamResponse.status,
headers: { 'Content-Type': 'application/json' }
});
} catch (err: any) {
if (err.name === 'AbortError' || controller.signal.aborted) {
return new Response(JSON.stringify({ error: 'Upstream provider gateway timeout' }), {
status: 504,
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify({ error: 'Upstream connection failure' }), {
status: 502,
headers: { 'Content-Type': 'application/json' }
});
} finally {
clearTimeout(timeoutId);
}
}
```
---
## 🔒 Security & Privacy Guarantees
> [!TIP]
> For an in-depth breakdown of our automated PII redaction, Smart Debug infrastructure, and tamper-resistant Proxy introspection, see the dedicated **[Security & Privacy Architecture Guide (`security.md`)](./ai.security.md)**.
Whether running directly on backend servers (Node.js, Deno, Bun, Edge Workers) or through a client-side browser proxy, `@tempo-kit/plugin-ai` enforces strict security and privacy standards:
### 1. Transport Security (HTTPS / TLS)
All network communication—both from client to proxy and from proxy/server to upstream LLM endpoints—is required over HTTPS. Negotiated TLS versions (such as TLS 1.2 or TLS 1.3) depend on deployment environment and server configuration unless strictly enforced by your reverse proxy. Plaintext HTTP endpoints are disallowed in production environments (permitted only on `localhost` during local development).
### 2. Ephemeral Processing & Cache Retention Controls
Temporal processing payloads (dates, times, context snippets, prompts) are processed ephemerally. The plugin does not send telemetry or store user prompt data on external analytics servers. However, functions supporting caching (e.g. `parseAI`, `formatAI`, `diffAI`) may retain prompt-derived cache keys and final results in local memory or configured custom cache adapters according to the resolved TTL. Requests requiring zero cache retention must explicitly pass `cache: false`.
### 3. In-Memory Credential Redaction & Immutability
* **Automated Key Redaction**: Calling `getAiConfig()` returns a sanitized, deeply read-only snapshot of active configurations with all provider `key` values replaced with `[REDACTED]`, preventing accidental exposure in log files, APM traces, or crash dumps.
* **Frozen Metadata**: All diagnostic metadata attached to `Tempo` instances via `.ai` and all structured AI result objects (`TempoAiFormatResult`, `TempoAiExtractResult`, `TempoAiDiffResult`, `TempoScheduleResult`, `TempoRecurrenceResult`, `TempoContext`) are deeply frozen with `Object.freeze()` and guarded via runtime `Proxy` wrappers, protecting against direct runtime mutation.
### 4. Deterministic Schema Guardrails & Confidence Range Verification
All LLM prompts are paired with rigid, machine-verifiable JSON schemas. Responses undergo strict boundary validation, regex parsing, confidence range verification (`0.0` to `1.0`), and schema verification before any native `Tempo` date object or structured result payload is instantiated. If an LLM returns malformed, out-of-range, or unparseable data, the plugin throws a typed `TempoAiError` or triggers automatic provider fallback rather than silently propagating corrupt data.
### 5. Partitioned Caching & Fail-Open Storage Resilience
* **Strict Cache Key Partitioning**: Caches are namespaced and hashed (`ai:::...`) with timezone, locale, calendar, and anchor date isolation to prevent cross-tenant or cross-regional cache poisoning.
* **Fail-Open Protection**: If a custom distributed cache adapter (e.g. Redis or Cloudflare KV) encounters network disruption or errors, the plugin automatically fails open to direct LLM resolution, preserving application uptime.
## Multi-Provider Execution Strategies (`AiMode`)
Because third-party APIs can experience downtime, latency spikes, or quota exhaustion, `@tempo-kit/plugin-ai` provides six dedicated dispatch strategies configured via `AiMode` (or string literals):
| Strategy | Enum (`AiMode`) | Primary Advantage | Typical Use Case |
| :--- | :--- | :--- | :--- |
| **Fallback** *(Default)* | `AiMode.Fallback` | Minimum token cost (sequential cascade) | Default production baseline & background tasks |
| **Hedged** | `AiMode.Hedged` | Ultra-fast latency with low token overhead (~1.15x) | Latency-sensitive interactive search & chatbots |
| **RoundRobin** | `AiMode.RoundRobin` | Cyclic rotation across multi-key pools | High-throughput batch ingestion across API keys |
| **Adaptive** | `AiMode.Adaptive` | Telemetry-driven rate-limit avoidance | Multi-tier provider pools with mixed quotas |
| **Race** | `AiMode.Race` | Absolute minimum response latency | Real-time typeahead & autocomplete |
| **Consensus** | `AiMode.Consensus` | Cross-LLM verification & hallucination trapping | High-stakes legal, financial, and contract dates |
👉 For detailed architecture breakdowns, Mermaid decision trees, and configuration guides for each mode, see the **[Multi-Provider Execution Modes Guide (`modes.md`)](./ai.modes.md)**.
### Provider ID Canonicalization
Provider IDs are normalized case-insensitively during `initAI` lookup (e.g. `'Gemini'`, `'gemini'`, `'OpenAI'`), automatically applying default endpoints and models while preserving the caller's registered identifier for logging and metadata.
---
# Document: 9-plugins/ai.context.md
# `contextAI` — Context & Regional Inference
`contextAI()` is designed to analyze unstructured or ambiguous text (e.g. user biographies, locations, or email bodies) and infer their regional configuration settings. It resolves these properties to a standard configuration object containing timezone, locale, calendar system, and hemisphere.
> [!TIP]
> **Smart Debug Telemetry**: Enabling `debug: true` activates operational logs. In production environments (`NODE_ENV === 'production'`), PII (emails, phone numbers, auth tokens) is automatically sanitized and masked in console output and terminal inspections. See the [Security & Privacy Architecture Guide](./ai.security.md).
This is highly useful for user onboarding settings, automatic context mapping for calendar syncs, and geolocating inputs dynamically without maintaining static geographic mapping tables.
---
## Basic Usage
> [!NOTE]
> `@tempo-kit/plugin-ai` features zero-config auto-discovery. If provider keys exist in your environment (`GROQ_API_KEY`, `OPENAI_API_KEY`, etc.) or `tempo.config.json`, calling `initAI()` is **completely optional**.
```typescript
import { contextAI } from '@tempo-kit/plugin-ai';
// 1. Infer contextual settings directly from unstructured text (auto-discovers provider keys)
const context = await contextAI("I'm a photographer based in Sydney, Australia.");
console.log(context.timeZone); // "Australia/Sydney"
console.log(context.locale); // "en-AU"
console.log(context.calendar); // "gregory"
console.log(context.sphere); // "south"
console.log(context.confidence);// 0.98
```
---
## Configuration Options (`AiContextOptions`)
| Option | Type | Description |
| :--- | :--- | :--- |
| **`force`** | `boolean` | If true, bypasses the cache to initiate a fresh LLM query. |
| **`cache`** | `boolean` | If false, disables writing to and reading from cache adapters. |
| **`cacheAdapter`** | `AiCacheAdapter` | Custom cache engine (e.g., Redis) for caching results on this request. |
| **`ttl`** | `number` | Time-to-live override in milliseconds for cached results. |
| **`minConfidence`**| `number` | Minimum confidence score threshold (0.0 to 1.0) required to return a valid slot. Throws `TempoAiError(422)` if lower. |
| **`mode`** | `AiMode` | Concurrency routing strategy (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`). Refer to the [Multi-Provider Execution Modes Guide](./ai.modes.md). |
| **`providers`** | `AiProvider[]` | Per-request provider configuration overrides. |
| **`timeout`** | `number` | Per-request timeout in milliseconds (overrides provider and global timeouts). |
| **`hedgeDelay`** | `number` | Delay in milliseconds before initiating speculative hedging in `AiMode.Hedged` (default: `800ms`). |
| **`debug`** | `boolean` | If true, logs prompt context and cache operations to console (automatically PII-sanitized in production). |
| **`softErrors`** | `boolean` | If true, returns `TempoAiError` into array index position instead of rejecting the entire batch query. |
---
## Result Schema (`TempoContext`)
```typescript
export interface TempoContext {
/** Inferred IANA time zone identifier (e.g. 'America/New_York') */
timeZone: string;
/** Inferred BCP 47 language/region tag (e.g. 'en-US') */
locale: string;
/** Inferred Unicode calendar system type (e.g. 'gregory') */
calendar: string;
/** Inferred hemisphere, or undefined if ambiguous */
sphere?: 'north' | 'south' | undefined;
/** Confidence rating from 0.0 (unparseable) to 1.0 (certain) */
confidence: number;
/** Resolution source ('cache' or provider ID like 'groq', 'gemini', 'openai') */
provider: string;
/** Step-by-step reasoning or justification provided by the engine/LLM */
reasoning?: string | undefined;
}
```
---
## Key Architectural Behaviors
### 1. Workspace Baseline Context
`contextAI` inspects the host runtime or current `Tempo` configuration (`Tempo.options.timeZone`, `Tempo.options.locale`, etc.) as a fallback baseline. If an input like `"at home"` is provided, the LLM will ground its inference in the workstation's baseline defaults.
### 2. Strict Confidence Thresholds
Using `minConfidence`, developers can guarantee that low-certainty or completely ambiguous inputs (e.g., `"in the park"`) throw a `TempoAiError(422)` rather than silently returning guessed context parameters:
```typescript
const context = await contextAI("meeting somewhere online", { minConfidence: 0.9 });
// Throws TempoAiError(422): Inferred context confidence (0.4) is below the required threshold of 0.9.
```
### 3. Timezone Validation
Before returning, the returned IANA timezone string is dynamically validated against the runtime's native JavaScript `Intl` API. If the LLM returns an unsupported or fake timezone identifier, `contextAI` throws a `TempoAiError(422)` to prevent application runtime failures.
### 4. Parallel Batch Processing
You can pass an array of strings to process multiple contexts concurrently:
```typescript
const [context1, context2] = await contextAI([
"Working from Kyoto",
"Living in Melbourne"
]);
```
### Combining `contextAI` with `parseAI` (The Pivot Flow)
Often, a user will mention their location in one sentence and a relative time in another. You can chain these APIs together to form a seamless date-resolution pipeline:
```typescript
import { contextAI, parseAI } from '@tempo-kit/plugin-ai';
// 1. Deduces the context
const ticketContext = await contextAI("customer issue from our London office");
// ticketContext = { timeZone: 'Europe/London', locale: 'en-GB', sphere: 'north' }
// 2. Feed the output context directly as options into parseAI
const resolutionTime = await parseAI("issue occurred on 04/05/2026 at 3 PM", ticketContext);
// 1. Correctly parses 04/05 to May 4th (UK format) rather than April 5th.
// 2. Adjusts to BST/GMT (Europe/London).
```
---
# Document: 9-plugins/ai.diff.md
# `diffAI` — Contextual & Business Date Deltas
`diffAI()` expresses the temporal delta between two `Tempo` instances, timestamps, or date strings in human, business, or operational terms.
While core `Tempo` provides precise numeric calculations (`start.until(end, 'day')`), `diffAI` bridges the gap to domain-specific narrative explanations (e.g. accounting working days, delivery SLAs, relative countdowns, and sprint planning summaries) backed by arithmetic grounding.
---
## Basic Usage
```typescript
import { Tempo } from 'tempo-kit';
import { initAI, diffAI } from '@tempo-kit/plugin-ai';
// 1. Initialize AI providers
await initAI({
providers: [
{ id: 'groq', key: process.env.GROQ_API_KEY }
]
});
const start = new Tempo('2026-08-01T09:00:00Z'); // Saturday
const end = new Tempo('2026-08-10T17:00:00Z'); // Next Monday
const diff = await diffAI(start, end, 'explain in terms of business working days');
console.log(diff.formatted); // "5 business days (approx. 224 calendar hours)"
console.log(diff.businessDays); // 5
console.log(diff.days); // 9.33
console.log(diff.hours); // 224
console.log(diff.confidence); // 0.96
```
---
## Configuration Options (`AiDiffOptions`)
| Option | Type | Description |
| :--- | :--- | :--- |
| **`holidays`** | `string[]` | Explicit array of holiday dates (`'year-month-day'`, ISO 8601) to exclude from business days. |
| **`region`** | `string` | Regional context (e.g., `'AU-NSW'`, `'US'`) passed to LLM grounding. |
| **`timeZone`** | `string` | Target IANA timezone for date boundaries and calculation. |
| **`locale`** | `string \| string[]` | Locale for narrative language formatting. |
| **`force`** | `boolean` | If true, bypasses the cache to initiate a fresh LLM query. |
| **`cache`** | `boolean` | If false, disables writing to and reading from cache adapters. |
| **`cacheAdapter`** | `AiCacheAdapter` | Custom cache engine (e.g., Redis) for caching results on this request. |
| **`ttl`** | `number` | Time-to-live override in milliseconds for cached results. |
| **`minConfidence`**| `number` | Minimum confidence score threshold (0.0 to 1.0) required. Throws `TempoAiError(422)` if lower. |
| **`mode`** | `AiMode` | Concurrency routing strategy (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`). Refer to the [Multi-Provider Execution Modes Guide](./ai.modes.md). |
| **`softErrors`** | `boolean` | If true, returns `TempoAiError` into array indices instead of rejecting batch queries. |
---
## Result Schema (`TempoAiDiffResult`)
```typescript
export interface TempoAiDiffResult {
/** Human-friendly, contextual narrative text summarizing the difference */
formatted: string;
/** Total calendar days between start and end */
days?: number | undefined;
/** Total elapsed calendar hours between start and end */
hours?: number | undefined;
/** Total business working days (excluding weekends and matching holidays) */
businessDays?: number | undefined;
/** List of holiday dates (year-month-day, ISO 8601) encountered within the interval */
holidays?: string[] | undefined;
/** Confidence rating from 0.0 (unparseable) to 1.0 (certain) */
confidence: number;
/** Resolution source ('cache' or provider ID like 'groq', 'gemini', 'openai') */
provider: string;
/** Step-by-step reasoning or justification provided by the engine/LLM */
reasoning?: string | undefined;
}
```
---
## Key Architectural Behaviors
### 1. Native Grounding Context
To guarantee arithmetic precision and prevent LLM hallucinations, `diffAI` natively computes exact calendar days, elapsed hours, and business working days using `Tempo` before dispatching to the LLM. Business day grounding automatically respects regional weekend definitions via `Intl.LocaleInfo` (e.g. Friday/Saturday in `ar-SA`, Friday-only in `fa-IR`, or Saturday/Sunday in standard ISO regions) as well as explicitly provided `holidays`. These metrics are supplied as grounding constraints in the system prompt.
### 2. Public Holiday Exclusions
You can supply regional public holidays (e.g., from `tempo-fns` via `getPublicHolidays`) to automatically adjust business day counters:
```typescript
import { getPublicHolidays } from 'tempo-fns';
const holidays = (await getPublicHolidays(2026, 'AU')).map(h => h.date);
const result = await diffAI('2026-12-24', '2027-01-04', 'calculate net business days', {
holidays,
region: 'AU',
});
console.log(result.businessDays); // 5 (Christmas, Boxing Day, New Year's Day excluded)
console.log(result.holidays); // ['2026-12-25', '2026-12-26', '2027-01-01']
```
### 3. Directional Awareness & Reverse Intervals
When the end date is earlier than the start date, `diffAI` indicates past/backward direction and provides negative business day counts (e.g. `-5` business days), allowing the LLM to format relative past descriptions (e.g. `"5 business days ago"`).
### 4. Parallel Batch Processing
You can pass an array of diff pairs to resolve multiple deltas concurrently:
```typescript
const [diff1, diff2] = await diffAI([
{ start: '2026-08-01', end: '2026-08-05', prompt: 'summarize for billing' },
{ start: '2026-08-05', end: '2026-08-15', prompt: 'explain project sprint' },
]);
```
---
# Document: 9-plugins/ai.extract.md
# `extractAI` — Unstructured Text & Calendar Event Extraction
`extractAI()` scans unstructured, multi-paragraph text (emails, meeting transcripts, chat logs, task notes, calendar invitations) to automatically identify, parse, and extract all embedded temporal entities and time-bound events into structured `TempoAiExtractResult` records containing native `Tempo` instances.
Relative expressions (such as *"tomorrow at 10am"*, *"next Tuesday from 1 to 3pm"*, *"final deliverables due Friday EOD"*) are resolved and mathematically grounded against an explicit or current reference `anchor` timestamp, timezone, and calendar system.
---
## Basic Usage
```typescript
import { Tempo } from 'tempo-kit';
import { initAI, extractAI } from '@tempo-kit/plugin-ai';
// 1. Initialize AI providers
await initAI({
providers: [
{ id: 'groq', key: process.env.GROQ_API_KEY }
]
});
const emailText = `
Hi team,
Let's schedule our Sprint Review tomorrow from 10:00 AM to 11:30 AM in Room 4A.
Also, reminder that all pull requests and documentation are due next Friday by 5:00 PM.
`;
const anchor = new Tempo('2026-08-10T09:00:00Z'); // Monday morning
const result = await extractAI(emailText, { anchor, timeZone: 'America/New_York' });
for (const event of result.events) {
console.log(`[${event.type}] ${event.label}`);
console.log(` Start: ${event.start.format('{yyyy}-{mm}-{dd} {hh}:{mi}')}`);
if (event.end) {
console.log(` End: ${event.end.format('{yyyy}-{mm}-{dd} {hh}:{mi}')}`);
}
console.log(` Source: "${event.rawText}" (Confidence: ${event.confidence})`);
}
```
---
## Configuration Options (`AiExtractOptions`)
| Option | Type | Description |
| :--- | :--- | :--- |
| **`anchor`** | `TempoDateInput` | Reference anchor date for relative expressions (defaults to current time). |
| **`timeZone`** | `string` | Target IANA timezone for grounding and output Tempo instances. |
| **`locale`** | `string \| string[]` | Target BCP 47 locale or language tag (e.g. `'en-US'`, `'fr-FR'`). |
| **`calendar`** | `string` | Calendar system (e.g. `'gregory'`, `'hebrew'`, `'islamic'`). |
| **`categories`** | `string[]` | Optional list of categories to filter entities (e.g. `['meeting', 'deadline']`). |
| **`region`** | `string` | Regional context (e.g. `'AU-NSW'`, `'US-NY'`) passed to LLM grounding. |
| **`force`** | `boolean` | If true, bypasses cache to force a fresh LLM query. |
| **`cache`** | `boolean` | If false, disables writing to and reading from cache adapters. |
| **`cacheAdapter`** | `AiCacheAdapter` | Custom cache engine (e.g., Redis, Cloudflare KV) for caching results. |
| **`ttl`** | `number` | Time-to-live override in milliseconds for cached results (defaults to 24h). |
| **`minConfidence`**| `number` | Minimum confidence score threshold (0.0 to 1.0) required. Throws `TempoAiError(422)` if lower. |
| **`mode`** | `AiMode` | Concurrency routing strategy (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`). Refer to the [Multi-Provider Execution Modes Guide](./ai.modes.md). |
| **`softErrors`** | `boolean` | If true, returns `TempoAiError` into array indices instead of rejecting batch queries. |
---
## Result Schema (`TempoAiExtractResult`)
```typescript
export interface TempoAiExtractResult {
/** Array of extracted events with instantiated Tempo objects. */
events: TempoExtractedEvent[];
/** Overall extraction confidence score between 0.0 and 1.0. */
confidence: number;
/** ID of the provider that fulfilled the request (or 'cache'). */
provider: string;
/** Optional summary or reasoning from the LLM. */
reasoning?: string | undefined;
}
export interface TempoExtractedEvent {
/** Short descriptive label or title of the extracted event/activity. */
label: string;
/** Start date-time point as an instantiated Tempo instance. */
start: Tempo;
/** Optional end date-time point (if an interval or duration was mentioned). */
end?: Tempo | undefined;
/** Classification category ('point' | 'interval' | 'deadline' | 'recurrence' | 'tentative'). */
type: TempoEventType;
/** Raw text snippet extracted from the source document. */
rawText?: string | undefined;
/** Confidence score for this specific entity extraction (0.0 to 1.0). */
confidence: number;
}
```
---
## Key Architectural Behaviors
### 1. Mathematical Grounding & Hallucination Suppression
To prevent hallucinated dates, `extractAI` calculates grounding anchor coordinates before dispatching to the LLM:
- Localized ISO reference timestamp and timezone
- Day of the week name and ordinal index
- Target calendar system and regional context
- Constrained JSON schema ensuring valid ISO dates
### 2. Native `Tempo` Instances
Extracted start and end points are immediately instantiated as live `Tempo` objects, ready for subsequent date math, interval arithmetic, or timezone shifting:
```typescript
const result = await extractAI(transcript);
const meeting = result.events[0];
// Instant date operations with Tempo
const reminderTime = meeting.start.subtract('15 minutes');
console.log(`Set alarm for: ${reminderTime.format('{h12}:{mi} {mer}')}`);
```
### 3. Multi-Tier Distributed Caching
`extractAI` integrates multi-tier caching (in-memory and optional asynchronous `AiCacheAdapter` such as Redis or Cloudflare KV). Cached ISO timestamps are rehydrated into live `Tempo` objects upon cache hits:
```typescript
const result = await extractAI(documentText, {
cacheAdapter: redisCacheAdapter,
ttl: 86_400_000, // 24 hours
});
```
### 4. Parallel Batch Extraction
Process arrays of documents concurrently with optional `softErrors` fault-tolerance:
```typescript
const documents = [
"Team offsite next Thursday from 9am to 5pm.",
"Project proposal submission deadline is August 20 at midnight."
];
const results = await extractAI(documents, { softErrors: true });
```
---
# Document: 9-plugins/ai.format.md
# Grounding & Natural Language Parsing
Because natural language dates are entirely relative (e.g., *"next Tuesday"*) and culturally ambiguous (e.g., *"11/12"*), an LLM cannot reliably parse them in a vacuum.
The Tempo AI plugin solves this by automatically injecting **deterministic temporal and regional grounding coordinates** before dispatching queries to the LLM.
## Temporal & Regional Grounding
The plugin automatically resolves the active `Tempo.config` to establish the exact reference time and regional coordinates:
- **Anchor Reference Clock**: The exact ISO timestamp at the moment of invocation.
- **Regional Coordinates**: TimeZone (e.g., `America/New_York`), Calendar system (`iso8601`), Locale (`en-US`), and Hemisphere (`northern`).
Along with your text query, the plugin passes these grounding coordinates directly to the model's system prompt:
> *`Grounding Anchor: [Anchor], Timezone: [TZ], Calendar: [Cal], Locale: [Loc], Hemisphere: [Sphere]`*
### Custom Grounding Anchors & Options
You can explicitly override any grounding coordinate on a per-request basis by passing an options object as the second argument, identical to how you pass configuration options to a standard `new Tempo()` constructor:
```typescript
// Explicitly evaluate this complex relative query from the perspective of September 1st
const dt = await parseAI("The penultimate Tuesday before Thanksgiving", {
anchor: '2026-09-01T00:00:00Z'
});
// Explicitly parse assuming a Japanese locale and timezone
const tokyoDt = await parseAI("The second Sunday of May", {
locale: 'ja-JP',
timeZone: 'Asia/Tokyo'
});
```
### Why Cultural & Regional Grounding is Critical
Passing the `Locale` and `TimeZone` is critical for the LLM to know whether `"11/12"` represents November 12th (US format) or 11th of December (UK/EU format). The plugin grounds these ambiguous tokens transparently based on your standard Tempo configuration!
## Symbiotic Neuro-Symbolic Architecture (LLM Semantics + Tempo Math) {#neuro-symbolic-architecture}
LLMs are language predictors, not calculators. While they excel at cultural knowledge and linguistic intent (knowing that *"Melbourne Cup"* is the first Tuesday of November, or *"US Thanksgiving"* is the fourth Thursday of November), even strong models are notoriously prone to mental-calendar hallucinations when subtracting weekdays across month boundaries or guessing what day of the week a future date falls on.
To solve this without sacrificing natural-language flexibility, `parseAI()` and `extractAI()` split the problem in two:
1. **The LLM handles semantics**: Translating unstructured prose, idioms, and holiday knowledge into a structured JSON **`plan`** (or `startPlan` / `endPlan` in `extractAI`), such as *"1st Tuesday of November 2027, then step backward to Friday"*.
2. **Tempo handles the math**: Executing that plan deterministically via `Temporal` arithmetic (`evaluateDatePlan`), preserving exact DST wall-clock offsets, leap years, and active calendar boundaries—overriding any hallucinated `iso` the model may have emitted alongside it (note that if the model explicitly returns `iso: 'INVALID'`, plan evaluation is skipped so unparseable/gibberish rejections are respected).
> [!NOTE]
> **Fallback & Limitations**: If a provider omits `plan` (or the expression relies on lunar/non-Gregorian holiday tables such as Eid, Diwali, or Chinese New Year outside the plan grammar), the plugin falls back gracefully to the model's `iso` string. Remember that Tempo guarantees the calendar math *given* the rule—if a model misstates a cultural rule itself, pairing with `@tempo-kit/plugin-holidays` or `@tempo-kit/plugin-cultural` remains the authoritative source.
## The Decoupled Output Bridge
To ensure deterministic, type-safe behavior, the plugin enforces a strict decoupled bridge between AI text generation and JavaScript object hydration:
* **For Point-in-Time Parsing (`parseAI`)**: The LLM emits a structured `plan` (preferred) alongside a fallback local ISO 8601 string. Tempo evaluates `plan` deterministically (preserving offsets across DST fall-back hours) or constructs a `new Tempo()` instance from `iso` with caller-defined timezone and calendar context.
* **For Structured Functions (`formatAI`, `extractAI`, `diffAI`, `contextAI`)**: The LLM completes rigid JSON schemas validated against strict boundary rules, instantiating typed result objects (`TempoAiFormatResult`, `TempoAiExtractResult`, `TempoAiDiffResult`, `TempoContext`).
* **For Intervals & Generators (`scheduleAI`, `recurrenceAI`)**: The plugin hydrates interval boundaries into a proxied `Interval` or exposes an iterable generator yielding sequential `Tempo` instances.
This eliminates AST-construction ambiguity and provides clean runtime contracts for every operation.
### Relative Date Ambiguity Tie-Breakers
To eliminate model variance on idioms like "Next Friday" or "Last Tuesday", the plugin enforces static system prompt ambiguity rules:
* `"next [weekday/unit]"`: Evaluated as the immediate next chronological occurrence after the grounding anchor.
* `"last [weekday/unit]"` / `"previous [weekday/unit]"`: Evaluated as the most recent past occurrence prior to the grounding anchor.
* `"this [weekday]"`: Evaluated as the occurrence within the current calendar week containing the grounding anchor.
### Confidence Thresholds & Metadata Handling
When `minConfidence` is supplied in options (e.g. `{ minConfidence: 0.85 }`):
* **`parseAI`**: Any LLM response returning a confidence score below the threshold produces a `Tempo` instance with `isValid === false` (when using `softErrors: true`) or throws a `TempoAiError(422)`.
* **Structured Functions (`formatAI`, `extractAI`, `diffAI`, `contextAI`, `scheduleAI`, `recurrenceAI`)**: Low-confidence completions immediately throw a `TempoAiError(422)` (or return a `TempoAiError` in batch arrays when `softErrors: true` is enabled).
Every resolved `Tempo` instance returned by `parseAI` has a non-writable, frozen `.ai` metadata descriptor containing execution audit data:
```typescript
const dt = await parseAI("Christmas 2026", { debug: true });
console.log(dt.ai);
// {
// provider: 'openai',
// cached: false,
// confidence: 0.95,
// ambiguous: false,
// granularity: 'day',
// rawIso: '2026-12-25T00:00:00',
// rawPrompt: 'Christmas 2026', // Present when debug is enabled
// normalizedPrompt: 'christmas 2026' // Present when debug is enabled
// }
```
*(For other AI functions like `extractAI` or `diffAI`, diagnostic metadata including `confidence`, `reasoning`, and `provider` is attached directly to the returned result object.)*
---
# Document: 9-plugins/ai.index.md

# @tempo-kit/plugin-ai
Tempo community plugin for LLM-powered natural language date parsing, schedule compilation, and temporal processing.
This plugin bridges the gap between deterministic date-math and unstructured NLP inputs, utilizing large language models (like Gemini, Groq, or OpenAI) to safely and asynchronously parse, format, and process complex natural language temporal expressions into `Tempo` instances.
::: warning 🔒 Security Notice
Raw LLM API keys must **never** be exposed in client-side browser bundles or stored in any client-side storage mechanisms (`localStorage`, `sessionStorage`, `IndexedDB`, OPFS / Origin Private File System, or browser cache). We recommend **zero browser storage** for API credentials; BYOK (Bring Your Own Key) is only secure on backend servers (Node, edge workers). For public frontend applications, route requests through a secure backend proxy service.
:::
## Key Features
- **Natural Language Parsing**: `parseAI` turns free-form expressions into `Tempo` instances (single or batch).
- **Structured AI Results**: Narrative formatting (`formatAI`), event extraction (`extractAI`), time deltas with business days (`diffAI`), and regional context inference (`contextAI`).
- **Recurrence & Scheduling**: Natural language to iterable series (`recurrenceAI`) and conflict-aware appointment slots (`scheduleAI`).
- **Multi-Provider Execution Modes**: Hedged, RoundRobin, Adaptive, Race, Consensus, and Fallback strategies across providers such as Gemini, Groq, and OpenAI.
- **Grounded & Validated**: Timezone and locale grounding, schema enforcement, and confidence thresholds with typed `TempoAiError` results.
- **Privacy & Security Controls**: PII masking, plus documented BYOK (backend) and proxy (browser) provider patterns.
- **Two Usage Patterns**: The cohesive `Tempo.ai.*` namespace or tree-shakeable standalone functions.
---
## Installation
```bash
npm install @tempo-kit/plugin-ai
```
---
## Quickstart
Installing `AiPlugin` mounts the frozen **`Tempo.ai`** static action namespace onto `Tempo`:
```typescript
import { Tempo } from 'tempo-kit';
import { AiPlugin } from '@tempo-kit/plugin-ai';
Tempo.use(AiPlugin);
// All AI capabilities are available under Tempo.ai.*
await Tempo.ai.init({ provider: 'tempo' });
const event = await Tempo.ai.parse("next Tuesday around 2:30pm");
```
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-ai/install';
const event = await Tempo.ai.parse("next Tuesday around 2:30pm");
```
---
## Two Usage Patterns: Namespace vs Tree-Shakeable Functions
The AI plugin provides two distinct integration approaches:
| Approach | Import Syntax | Ideal For |
| :--- | :--- | :--- |
| **Cohesive Namespace** | `import { AiPlugin } from '@tempo-kit/plugin-ai'` | Full-featured apps, Node.js backends, REPLs, and IDE auto-complete via `Tempo.ai.*` |
| **Tree-Shakeable Functions** | `import { parseAI, initAI } from '@tempo-kit/plugin-ai'` | Minimal client-side bundles and microservices importing only specific functions |
### Tree-Shakeable Standalone Functions
For bundle-sensitive projects, import individual functions directly without attaching anything to `Tempo`:
```typescript
import { initAI, parseAI } from '@tempo-kit/plugin-ai';
// 1. Initialize trial sandbox or explicit providers
await initAI({ provider: 'tempo' });
// 2. Call standalone function directly
const dt = await parseAI("The penultimate Tuesday before Thanksgiving in 2026");
console.log(dt.format('{yyyy}-{mm}-{dd}')); // 2026-11-17
```
---
## API Reference
All AI functions return a standard ES Promise and are accessible either as standalone tree-shakeable functions or via the cohesive `Tempo.ai.*` namespace.
| Standalone Function / `Tempo.ai` Method | Input | Returns (`Promise<...>`) | Description | Doc |
| :--- | :--- | :--- | :--- | :---: |
| **`parseAI`** `Tempo.ai.parse` | Natural language text string(s) | `Tempo` \| `Tempo[]` \| `(Tempo \| TempoAiError)[]` | Single point-in-time `Tempo` instance (or batch array) | |
| **`formatAI`** `Tempo.ai.format` | Date-time + prompt / style | `TempoAiFormatResult` \| `TempoAiFormatResult[]` \| `(TempoAiFormatResult \| TempoAiError)[]` | **Contextual narrative date formatting** (`formatted`, `confidence`, `provider`, `reasoning`) | |
| **`extractAI`** `Tempo.ai.extract` | Unstructured text string(s) | `TempoAiExtractResult` \| `TempoAiExtractResult[]` \| `(TempoAiExtractResult \| TempoAiError)[]` | **Extracted temporal entities & calendar events** (`events: TempoExtractedEvent[]`, `confidence`, `reasoning`) | |
| **`recurrenceAI`** `Tempo.ai.recurrence` | Natural language pattern or RRULE string | `TempoRecurrenceResult` | **Iterable series of `Tempo` dates** (with `.take(n)`, `[Symbol.iterator]`, & RRULE string) | |
| **`scheduleAI`** `Tempo.ai.schedule` | Booking prompt + busy constraints | `TempoScheduleResult` | **Resolved appointment slot** (`start`, `end`, `slot`, `alternatives`, `ai.conflictBumped`) | |
| **`diffAI`** `Tempo.ai.diff` | Start & End dates + prompt | `TempoAiDiffResult` \| `TempoAiDiffResult[]` \| `(TempoAiDiffResult \| TempoAiError)[]` | **Narrative time delta & business days** (`formatted`, `businessDays`, `days`, `hours`, `holidays`) | |
| **`contextAI`** `Tempo.ai.context` | Context text string(s) | `TempoContext` \| `TempoContext[]` \| `(TempoContext \| TempoAiError)[]` | **Inferred regional context** (`timeZone`, `locale`, `calendar`, `sphere`) | |
| **`initAI`** `Tempo.ai.init` | Provider config & API keys | `void` | Configured AI provider farm | |
### Summary of Distinct Return Contracts
To streamline error handling and data consumption, return shapes across the AI plugin follow three distinct contracts:
| Category | Functions | Return Type | Single Query Low-Confidence / Failure | Batch Array `softErrors: true` Contract |
| :--- | :--- | :--- | :--- | :--- |
| **Point-in-Time Date** | `parseAI` | `Tempo` (with `.ai`) | Throws `TempoAiError` (or returns invalid `Tempo` if `minConfidence` threshold unmet) | Returns invalid `Tempo` (`isValid === false`) in array position |
| **Structured AI Objects** | `formatAI` `extractAI` `diffAI` `contextAI` | `TempoAiFormatResult` `TempoAiExtractResult` `TempoAiDiffResult` `TempoContext` | Throws `TempoAiError` (422 for low confidence, 429 for quota, 500 for network) | Returns typed `TempoAiError` object directly in array position |
| **Intervals & Generators** | `scheduleAI` `recurrenceAI` | `TempoScheduleResult` (Proxied `Interval`) `TempoRecurrenceResult` (`.take(n)`) | Throws `TempoAiError` (Single item query only) | N/A (Single query operations) |
---
## Topic Guides
> [!IMPORTANT]
> **Production Recommendation**: Due to the complexities of LLM APIs, including caching gotchas, context injection, rate limits, and calendar math hallucinations, we strongly recommend reading the dedicated guides below before deploying this plugin in a production environment.
- [Production Use Cases & Architectural Patterns](./ai.use-cases-and-patterns.md) (Interactive conversational scheduling, multi-LLM consensus, multi-tenant proxy gateways)
- [Security & Privacy Architecture](./ai.security.md) (Smart Debug Telemetry, PII Masking, HTTPS & Proxy Introspection)
- [Multi-Provider Execution Modes](./ai.modes.md) (Hedged, RoundRobin, Adaptive, Race, Consensus, Fallback)
- [Provider Architecture & Security](./ai.architecture.md) (BYOK vs Proxy patterns, Browser Security, TLS 1.3 & Privacy Guarantees)
- [Grounding & Natural Language Parsing](./ai.grounding.md) (How Timezone and Locale are injected)
- [Rate Limits & Cache Management](./ai.rate-limits.md) (Tracking API quotas, handling 429 errors, and custom Redis caches)
---
> [!NOTE]
> **Community Feedback & Prompt Engineering**: While `@tempo-kit/plugin-ai` utilizes deterministic grounding, schema enforcement, and confidence validation, LLM outputs can vary across models and prompt styles. We actively welcome community feedback and prompt optimizations—please report any edge cases or suggestions on the [Magma GitHub Issue Tracker](https://github.com/magmacomputing/magma/issues/new?template=bug_report_ai.yml).
>
> **Production Notice & "As-Is" Disclaimer**: Magma Computing Solutions and the Tempo core maintainers provide `@tempo-kit/plugin-ai` "as-is" without warranty of any kind. Large Language Models operate probabilistically; developers and system architects are responsible for validating AI-generated temporal outputs before committing them to financial, legal, medical, or life-critical applications.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/ai.init.md
# Multi-Provider Execution Modes (`AiMode`)
`@tempo-kit/plugin-ai` provides a robust, multi-provider dispatch orchestrator that handles latency hedging, quota load-balancing, consensus verification, and fault-tolerant failovers across diverse LLM providers (e.g. OpenAI, Anthropic, Groq, Mistral, Google Gemini, Ollama, local vLLM).
Execution modes can be configured globally during plugin initialization or overridden per request:
```typescript
import { initAI, parseAI, AiMode } from '@tempo-kit/plugin-ai';
// Global configuration
await initAI({
providers: [
{ id: 'groq', key: process.env.GROQ_API_KEY },
{ id: 'openai', key: process.env.OPENAI_API_KEY }
],
mode: AiMode.Hedged
});
// Per-request override
const dt = await parseAI('next friday at 3pm', {
mode: AiMode.Adaptive
});
```
---
## Strategy Comparison
| Mode | Dispatch | Token Cost | Latency | Rate-Limit Resilience |
| :--- | :--- | :---: | :---: | :---: |
| **`Fallback`** *(Default)* | Sequential | 🟢 1 request | 🟡 Moderate | 🟢 Proactive Cooldown Filter |
| **`Hedged`** | Staggered (primary + timer) | 🟢 ~1.15 avg | 🟢 Ultra-Fast | 🟢 Proactive Cooldown Filter |
| **`RoundRobin`** | Cyclic rotation | 🟢 1 request | 🟡 Moderate | 🟢 High (Cyclic + Filter) |
| **`Adaptive`** | Quota-sorted rotation | 🟢 1 request | 🟡 Moderate | 🟢 Maximum (Telemetry-Ranked) |
| **`Race`** | Full parallel | 🔴 N requests | 🟢 Ultra-Fast | 🟢 Proactive Cooldown Filter |
| **`Consensus`** | Full parallel + voting | 🔴 N requests | 🟡 Moderate | 🟢 Proactive Cooldown Filter |
---
## Global Telemetry & Cooldown Filtering
Regardless of the execution mode chosen, the AI dispatch engine actively monitors per-provider rate-limiting metadata across all network responses (`x-ratelimit-remaining-requests`, `x-ratelimit-remaining-tokens`, `x-ratelimit-reset-requests`, `retry-after`).
```mermaid
flowchart LR
A["Incoming Request\n(Any AiMode)"] --> B{"Check Provider Farm\nCooldown State"}
B -- "Exhausted (remaining === 0\n& resetAt > now)" --> C["🚫 Proactively Filter Out\n(Skip 429 endpoints)"]
B -- "Ready / High Quota" --> D["✅ Active Provider Pool"]
C -. "If ALL in cooldown" .-> D
D --> E["Dispatch via Selected Mode\n(Fallback, Race, Hedged, etc.)"]
```
### Proactive Cooldown Avoidance
Before dispatching any request:
1. **Cooldown Detection**: The orchestrator checks if any configured provider has exhausted its request or token quota (`remainingRequests === 0` or `remainingTokens === 0`) and is within an active reset window (`resetAt > now`, derived from response reset timestamps or `retry-after` metadata).
2. **Pre-Dispatch Filtering**: In `Fallback`, `Race`, `Hedged`, and `RoundRobin` modes, exhausted providers are automatically removed from the active candidate pool for that request.
- **`Fallback` & `Hedged`**: Avoids stalling on primary providers that are guaranteed to reject with HTTP 429.
- **`Race`**: Saves network bandwidth and avoids firing wasted requests to rate-limited models.
- **`RoundRobin`**: Skips over cooling-down keys without breaking the cyclic load-balancing progression.
3. **Fail-Open Resilience**: If *all* providers in the farm are currently in a cooldown window, the orchestrator keeps all providers available rather than failing prematurely, allowing the request to cascade or surface accurate rate-limit errors.
---
## Dispatch Decision Guide
```mermaid
flowchart TD
Start(["Where does this run?"]) --> UI["User-facing\n(search bar, chatbot, form)"]
Start --> Batch["Background / batch\n(ingestion, ETL, reports)"]
Start --> Audit["High-stakes audit\n(legal, financial, scheduling)"]
UI --> MultiUI{"Multiple providers\nor API keys?"}
MultiUI -- No --> Fallback["⬇️ AiMode.Fallback\nDefault • Most cost-efficient"]
MultiUI -- Yes --> CostSpeed{"Latency sensitive\nor cost concern?"}
CostSpeed -- "Fastest response (high cost)" --> Race["🏁 AiMode.Race\nAbsolute fastest response"]
CostSpeed -- "Staggered concurrency (lower cost)" --> Hedged["⏳ AiMode.Hedged\nStaggered latency hedging"]
Batch --> Quota{"Quota pressure\nor multiple keys?"}
Quota -- "Spread evenly" --> RR["🔄 AiMode.RoundRobin\nCyclic key rotation"]
Quota -- "Avoid 429 proactively" --> Adaptive["📡 AiMode.Adaptive\nTelemetry-driven ordering"]
Quota -- "Single key, simple" --> Fallback["⬇️ AiMode.Fallback\nDefault • Most cost-efficient"]
Audit --> Consensus["🗳️ AiMode.Consensus\nCross-LLM voting • Highest accuracy"]
```
---
## Mode Deep-Dives & Code Examples
### 1. `AiMode.Fallback` — Sequential Cascade *(Default)*
Dispatches requests to providers sequentially in configured order until a provider succeeds and satisfies `minConfidence`. The most cost-efficient mode.
**Best for:** Standard production baseline — general date parsing and background tasks.
```typescript
const dt = await parseAI('first monday in october 2026', {
mode: AiMode.Fallback,
minConfidence: 0.85 // Automatically cascades to next provider if score is too low
});
```
---
### 2. `AiMode.Hedged` — Speculative Latency Hedging
Sends a request to the primary provider immediately. If no valid response arrives within `hedgeDelay` (default: `800ms`), launches a speculative concurrent request to the secondary provider. The first valid response wins; all in-flight requests are aborted.
**Best for:** Latency-sensitive user-facing APIs — search bars, chatbots, web forms.
```typescript
const dt = await parseAI('schedule team sync for next wednesday at 2pm', {
mode: AiMode.Hedged,
hedgeDelay: 600 // Launch hedge after 600ms if primary is still pending
});
```
> [!TIP]
> `hedgeDelay` can also be set globally in `initAI({ hedgeDelay: 600 })` so it applies to all functions (`parseAI`, `recurrenceAI`, `scheduleAI`, `extractAI`).
---
### 3. `AiMode.RoundRobin` — Multi-Key Cyclic Load Balancing
Cycles through the configured provider pool on each invocation (`0 → 1 → 2 → 0 ...`). If the selected starting provider fails, automatically falls over to the remaining providers in cyclic order.
**Best for:** High-throughput batch processing — ingesting large volumes of dates across multiple API keys to avoid single-account RPM throttling.
```typescript
await initAI({
providers: [
{ id: 'groq-key-1', key: process.env.GROQ_KEY_1 },
{ id: 'groq-key-2', key: process.env.GROQ_KEY_2 },
{ id: 'groq-key-3', key: process.env.GROQ_KEY_3 }
],
mode: AiMode.RoundRobin
});
```
---
### 4. `AiMode.Adaptive` — Rate-Limit Telemetry Prioritization
Reads `x-ratelimit-*` HTTP headers after every provider response and stores per-provider quota snapshots. On subsequent requests, providers are ranked dynamically by highest remaining quota descending, guaranteeing that providers with ample headroom are prioritized ahead of constrained models.
**Best for:** Multi-tier production gateways — mixed free/paid provider pools where proactively avoiding `429 Too Many Requests` is essential.
```typescript
const dt = await parseAI('quarterly review deadline next quarter', {
mode: AiMode.Adaptive
});
```
> [!NOTE]
> Telemetry accumulates across calls. The first request in a session uses original provider order; sorting kicks in from the second call onward once header data is available.
---
### 5. `AiMode.Race` — Speculative Parallel Execution
Dispatches requests concurrently across all configured providers. The fastest successful response is returned, and all remaining requests are immediately cancelled via `AbortSignal`.
**Best for:** Real-time interactive typeahead — live search inputs or autocomplete where the fastest possible response is required regardless of token cost.
```typescript
const dt = await parseAI('tomorrow at noon', {
mode: AiMode.Race
});
```
---
### 6. `AiMode.Consensus` — Multi-LLM Cross-Validation
Dispatches requests concurrently across all providers and compares the normalized outputs (e.g. ISO timestamps for `parseAI`, RRULE strings for `recurrenceAI`, formatted strings for `diffAI`/`formatAI`, or structured entity counts for `extractAI`). If all responding providers agree, confidence is elevated to `1.0` (unanimous). If providers disagree, the highest-confidence candidate is returned and flagged with `ai.ambiguous = true` (attached to `Tempo.ai` on `parseAI` or returned on structured result objects).
**Best for:** High-stakes legal, financial, and scheduling — contract dates, event conflict resolution, or auditing where hallucination prevention requires unanimous LLM agreement.
```typescript
// 1. Point-in-time cross validation
const dt = await parseAI('contract renewal date', {
mode: AiMode.Consensus
});
if (dt.ai?.ambiguous) {
console.warn('Providers disagreed — treat this date with caution.');
}
// 2. High-precision duration calculation across multiple providers
const diff = await diffAI(startDate, endDate, 'in business days excluding UK bank holidays', {
mode: AiMode.Consensus
});
```
---
# Document: 9-plugins/ai.onboarding.md
# AI Configuration & Onboarding Guide
Tempo provides two complementary parsing layers:
1. **Core Tempo Deterministic Engine**: Resolves standard dates, ISO strings, and regular relative expressions (e.g. `"tomorrow at 5pm"`, `"next Tuesday"`, `"3 days ago"`) instantly at zero token cost and zero network latency.
2. **Tempo AI Plugin**: Leverages LLMs for complex semantic reasoning, cultural calendars, event-anchored dates, and ambiguous colloquialisms (e.g. `"The Friday before Melbourne Cup"`, `"Third Thursday in November after Thanksgiving"`, `"First business day after Orthodox Easter"`).
---
## 3-Tier Configuration Architecture
Choose the setup that fits your environment:
```mermaid
flowchart TD
Start["Developer starts with Tempo AI"] --> Q1{"Where is code running?"}
Q1 -- "Browser / Client / Sandbox" --> Q2{"Have your own backend?"}
Q1 -- "Server / Node.js / Deno / Bun" --> S1["Tier 3: Environment Variables or Direct Key GROQ_API_KEY=... or initAI({ provider: 'groq', apiKey: '...' })"]
Q2 -- "No (Evaluation Sandbox)" --> T1["Tier 1: Tempo Trial Sandbox initAI({ provider: 'tempo' }) (Free 20 req/hr trial sandbox)"]
Q2 -- "Yes (Secure Proxy)" --> T2["Tier 2: Backend Proxy Endpoint initAI({ endpoint: 'https://api.yourdomain.com/api/ai' })"]
```
### Tier Comparison Matrix
| Tier | Best For | Configuration | Rate Limits & Data Handling |
| :--- | :--- | :--- | :--- |
| **Tier 1: Tempo Sandbox** | Rapid prototyping, browser REPL, onboarding tutorials | `initAI({ provider: 'tempo' })` | Free community evaluation sandbox: 20 req/hr per IP (powered by a managed high-reasoning model). Queries are sanitized and retained for up to 30 days for prompt diagnostics. |
| **Tier 2: Backend Proxy** | Production web apps, mobile apps, SPAs | `initAI({ endpoint: 'https://api.yourdomain.com/api/ai' })` | Your backend manages quotas, authentication, and secret storage. Zero data touches Tempo servers. |
| **Tier 3: Direct Keys** | Server-side APIs, microservices, CLI tools, serverless | `initAI({ provider: 'groq', apiKey: '...' })` or `initAI({ providers: [...] })` | Full direct provider quota with dynamic key/endpoint supplier support. Direct client-to-provider egress. |
---
## Tier 1: Tempo Trial Sandbox (Evaluation)
To quickly explore semantic date parsing without provisioning external API keys or setting up a proxy backend, opt-in to the free Tempo trial sandbox:
```typescript
import { initAI, parseAI } from '@tempo-kit/plugin-ai';
// Initialize with Tempo's free evaluation sandbox
await initAI({ provider: 'tempo' });
const dt = await parseAI("The third Thursday in November after Thanksgiving");
console.log(dt.format());
```
> [!NOTE]
> **Attention: Trial Gateway Telemetry & Rate Limits**:
> The public Tempo trial evaluation gateway (`provider: 'tempo'`) collects pseudonymous, de-identified telemetry regarding sandbox usage (latency, error rates, model performance, token counts, and HMAC-SHA-256 salted IP hashes) to shape the plugin roadmap and improve parsing schemas.
>
> If you require strict zero data retention or do not wish to participate in trial sandbox diagnostics, configure your own secure backend proxy (Tier 2) or direct BYOK provider credentials (Tier 3).
> Learn more in our [Security & Privacy Guide](./ai.security.md).
>
> **Trial Rate Limits**: The free sandbox enforces an IP rate limit of **20 requests/hour**. When exceeded, Tempo AI raises a descriptive `TempoAiError(429)` guiding you to Tier 2 or Tier 3. To continually improve prompt accuracy and diagnose parsing edge cases, queries sent through the free sandbox are scrubbed of credentials and personal identifiers and stored for up to 30 days. Do not submit sensitive personal information through the trial sandbox.
---
## Tier 2: Backend Proxy (Recommended for Web Apps)
Never expose private LLM API tokens in client-side browser JavaScript. Instead, configure a single root proxy endpoint:
```typescript
import { initAI, parseAI } from '@tempo-kit/plugin-ai';
// Configure proxy endpoint once at app startup
initAI({
endpoint: 'https://api.yourdomain.com/api/aiProxy'
});
// All subsequent AI calls route through your backend proxy (unless a provider specifies an explicit per-provider endpoint override):
const meeting = await parseAI("The last Friday before Melbourne Cup Day");
```
Your backend server (Express, Cloud Functions, Next.js API route) terminates client requests, attaches server-bound secrets, forwards requests upstream with timeout and abort management, and handles client disconnects:
```typescript
// Backend handler example (Firebase Cloud Function / Express)
export const handleAiProxy = async (req, res) => {
// 1. Authenticate caller (verify JWT / session token)
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer '))
return res.status(401).json({ error: 'Unauthorized: Missing or invalid authentication token.' });
// 2. Verify caller authorization and enforce caller-specific rate limits
const user = await verifyUserSession(authHeader.split('Bearer ')[1]);
if (!user)
return res.status(403).json({ error: 'Forbidden: Caller not authorized for AI proxy routing.' });
// 3. Configure AbortController with 15s timeout & client disconnect listener
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15_000);
const onClientDisconnect = () => controller.abort();
res.on('close', onClientDisconnect);
try {
// 4. Forward sanitized payload upstream with server-side private key & signal
const payload = req.body;
const upstreamRes = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GROQ_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload),
signal: controller.signal
});
const data = await upstreamRes.json();
res.status(upstreamRes.status).json(data);
} catch (err: any) {
if (controller.signal.aborted) {
if (res.writableEnded || res.headersSent) return;
return res.status(504).json({ error: 'Gateway Timeout: Upstream AI inference timed out or client disconnected.' });
}
res.status(500).json({ error: `AI Proxy Error: ${err.message}` });
} finally {
clearTimeout(timeoutId);
res.removeListener?.('close', onClientDisconnect);
}
};
```
---
## Tier 3: Direct Keys & Environment Variables (Server-Side)
### Method A: Environment Variables (Auto-Discovery)
In Node.js, Deno, or Bun environments, standard provider environment variables are detected automatically:
```bash
# In your .env or shell:
GROQ_API_KEY="gsk_..."
OPENAI_API_KEY="sk-..."
```
```typescript
import { parseAI } from '@tempo-kit/plugin-ai';
// Automatically discovers GROQ_API_KEY and OPENAI_API_KEY:
const result = await parseAI("Two weeks after our Q3 quarterly investor dinner");
```
### Method B: Explicit `initAI`
```typescript
import { initAI, AiMode } from '@tempo-kit/plugin-ai';
await initAI({
mode: AiMode.Fallback,
providers: [
{
id: 'groq',
key: process.env.GROQ_API_KEY
// Automatically resolves default endpoint & latest model from DEFAULT_PROVIDERS / live manifest
},
{
id: 'custom-internal-gateway',
endpoint: 'https://ai-gateway.internal.corp/v1/chat/completions',
key: () => getVaultSecret('gateway-token'), // Dynamic supplier
model: 'gpt-4o-mini' // Optional: override or specify custom model identifier
}
],
timeout: 5000
});
```
> [!TIP]
> **Dynamic Manifest & Zero-Maintenance Model Defaults**:
> For standard providers (`groq`, `openai`, `gemini`), specifying `model` or `endpoint` is optional. Tempo AI automatically populates them from built-in `DEFAULT_PROVIDERS` and continuously synchronizes the latest optimal models at runtime via the remote provider manifest (`providers.v1.json`). Explicit model parameters are only required when overriding defaults or routing to private custom gateways.
---
## Configuration Parameter Reference
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `endpoint` | `string \| (() => string)` | Global backend proxy URL for all unconfigured providers. |
| `providers` | `AiProvider[]` | Array of configured AI providers. |
| `providers[].endpoint` | `string \| (() => string)` | Target chat completions API endpoint URL. |
| `providers[].key` | `string \| (() => string \| Promise)` | Provider API key or dynamic async key resolver. |
| `providers[].model` | `string \| (() => string)` | Model identifier. |
| `mode` | `AiMode` | Execution strategy (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`). |
| `timeout` | `number` | SLA timeout in milliseconds (default: `15000`). |
| `force` | `boolean` | Set to `true` to force fresh LLM fetches and bypass deterministic pre-parsing globally. |
| `cache` | `boolean \| CacheAdapter` | Cache configuration. |
| `telemetry` | `boolean` | Set to `false` to opt-out of anonymous usage telemetry (default: `true`). |
---
# Document: 9-plugins/ai.parse.md
# `parseAI` — Natural Language Point-in-Time Parsing
`parseAI()` is the primary entry point for converting complex, unstructured natural language date/time expressions into deterministic `Tempo` instances.
> [!TIP]
> **Neuro-Symbolic Resolution**: When a provider returns a usable `plan`, `parseAI()` pairs LLM semantic understanding with Tempo's deterministic `Temporal` calendar engine—so queries like *"Friday before Melbourne Cup next year"* are resolved by rule rather than mental LLM arithmetic (if no usable plan is returned, it falls back to the model's `iso`). See [Grounding & Neuro-Symbolic Architecture](./ai.grounding.md#neuro-symbolic-architecture) for details and fallback behavior.
## Basic Usage
```typescript
import { parseAI, initAI } from '@tempo-kit/plugin-ai';
// Initialize AI providers
await initAI({
providers: [
{ id: 'groq', key: process.env.GROQ_API_KEY }
]
});
// Parse natural language
const dt = await parseAI("The penultimate Tuesday before Thanksgiving in 2026");
console.log(dt.format('{yyyy}-{mm}-{dd}')); // 2026-11-17
console.log(dt.ai?.confidence); // 0.98
```
## Options & Overrides
`parseAI(input, options)` accepts per-request options:
```typescript
const dt = await parseAI("Third Friday of October", {
anchor: '2026-05-10T12:00:00Z', // Anchor date for relative calculations
timeZone: 'Australia/Sydney', // Context timezone
locale: 'en-AU', // Context locale
minConfidence: 0.85, // Require at least 0.85 confidence score
timeout: 3000, // 3-second request timeout (throws TempoAiError(504) if exceeded)
force: true, // Skip native pre-parsing & cache lookup
debug: true // Enable operational trace logging & .ai metadata
});
```
## Multi-Provider Execution Modes
`parseAI` supports all six multi-provider execution strategies (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`) configured globally or overridden per-request.
For a comprehensive guide, decision flowcharts, and configuration details for all execution modes, refer to the [Multi-Provider Execution Modes Guide](./ai.modes.md).
## Batch Array Parsing
Pass an array of prompts to process multiple queries in parallel while preserving index ordering:
```typescript
const [dt1, dt2] = await parseAI([
"New Years Day 2026",
"Groundhog Day 2026"
]);
console.log(dt1.format('{yyyy}-{mm}-{dd}')); // 2026-01-01
console.log(dt2.format('{yyyy}-{mm}-{dd}')); // 2026-02-02
```
## Diagnostic Metadata (`.ai`)
When a date is parsed, a frozen diagnostic metadata object is attached to the returned `Tempo` instance:
```typescript
console.log(dt.ai);
/*
{
provider: 'groq',
cached: false,
confidence: 0.98,
ambiguous: false,
granularity: 'day',
rawIso: '2026-11-17T00:00:00'
}
*/
```
---
# Document: 9-plugins/ai.rate-limits.md
# Rate Limits & Cache Management
When using third-party AI APIs, your application is subject to strict rate limits.
The plugin automatically tracks these limits by reading the standard `x-ratelimit-*` HTTP headers returned by providers like OpenAI and Groq.
## Tracking Quota Real-time
Quota and rate-limit metadata can be inspected in two convenient ways:
### 1. Request-Locked Instance Metadata (`dt.ai.limits`)
For `parseAI`, every resolved `Tempo` instance includes a frozen `.ai.limits` snapshot representing the rate limit state returned by provider HTTP headers for *that specific request*. Note that `.ai.limits` is guaranteed only for provider-backed network requests where rate-limit headers are returned by the selected provider; results resolved via native parsing (`provider: 'native'`) or cache hits (`provider: 'cache'`) may omit `.ai.limits` (`undefined`).
```typescript
const dt = await parseAI("The third Friday of next month");
if (dt.ai?.limits) {
console.log(`Remaining Tokens: ${dt.ai.limits.remainingTokens}`);
console.log(`Remaining Requests: ${dt.ai.limits.remainingRequests}`);
console.log(`Resets At: ${dt.ai.limits.resetAt?.format('{hh}:{mi}:{ss}')}`);
}
```
### 2. Global State Utility (`getAiRateLimits()`)
For quick status checks or global monitoring across the application lifecycle, `getAiRateLimits()` exposes the stats from the most recent LLM request:
```typescript
import { getAiRateLimits } from '@tempo-kit/plugin-ai';
// Returns global stats from the most recent LLM proxy request
const stats = getAiRateLimits();
if (stats) {
console.log(`Remaining Tokens: ${stats.remainingTokens}`);
console.log(`Remaining Requests: ${stats.remainingRequests}`);
console.log(`Limits Reset At: ${stats.resetAt?.format('{hh}:{mi}:{ss}')}`);
}
```
## Handling Quota Exhaustion (429s)
If you actually exhaust your quota and the provider rejects the request (e.g., HTTP 429 Too Many Requests), the plugin will instantly attempt to failover to the next provider in your configuration array.
If all providers fail, the plugin will throw a `TempoAiError`. This custom error class includes a highly valuable `retryAt` property:
```typescript
import { parseAI, TempoAiError } from '@tempo-kit/plugin-ai';
try {
const dt = await parseAI("The third Friday of next month");
} catch (error) {
if (error instanceof TempoAiError && error.code === 429) {
// Safely queue the remaining batch of dates until your minute-limit resets!
console.warn(`All API quotas exhausted. Retry after: ${error.retryAt}`);
}
}
```
## Cache Management
By default, Tempo AI functions integrate directly with `Tempo.cache` (`BoundedCache`) to store pre-resolved ISO 8601 results, drastically reducing LLM API calls and network latency on repetitive queries.
### Array Processing & Token Economics
When you pass an array of inputs to AI functions (such as `parseAI`), the plugin intentionally does **not** batch them into a single massive LLM request. Instead, it iterates through the array and processes each item individually.
This is by design for three critical reasons:
1. **Cache Efficiency**: Individual processing allows AI functions to instantly resolve duplicate strings against `Tempo.cache`, saving massive amounts of API tokens. If you pass an array of 10,000 dates, but only 1,000 are unique, only 1,000 network requests are made.
2. **Token Economics**: A single request consumes ~100 tokens (System Prompt + User String + Output ISO). Given that frontier models cost cents per million tokens, the risk of array-misalignment bugs (see below) far outweighs the negligible savings of batching system prompts.
3. **Deterministic Safety**: LLMs are language models, not arrays. If you pass 50 strings in a single prompt, smaller models often hallucinate and return 49 strings, completely breaking your array indexing. By dispatching items individually, we guarantee a strict 1:1 index alignment, prevent hallucinations from corrupting sibling entries, and allow granular per-item error isolation when `softErrors: true` is enabled.
> [!WARNING]
> **Granular Time Gotcha**: The cache key is automatically salted with the **calendar date** (`yyyy-mm-dd`) of the execution anchor. By default this uses the system execution date, but when `options.anchor` is explicitly set, it uses the caller-provided anchor date. Note that keeping a fixed anchor date retains the same cache key across midnight boundaries, so an automatic midnight cache miss is not guaranteed.
### Soft Errors in Array Batches
When processing arrays of inputs, an unparseable input or provider failure on one item will throw an error and reject the entire batch operation by default. Passing `softErrors: true` allows batch operations to continue processing all items and return per-item failure representations:
* **For `parseAI`**: Failed array items return an invalid `Tempo` instance (`isValid === false`).
* **For Structured Functions (`formatAI`, `extractAI`, `diffAI`, `contextAI`)**: Failed array items return the typed `TempoAiError` object directly in that array position.
```typescript
// 1. parseAI with softErrors returns invalid Tempo instances
const dates = await parseAI(["Thanksgiving 2026", "INVALID_PROMPT_STRING"], { softErrors: true });
console.log(dates[0].isValid); // true
console.log(dates[1].isValid); // false
// 2. Structured functions return TempoAiError objects into the array
import { formatAI, TempoAiError } from '@tempo-kit/plugin-ai';
const formatted = await formatAI([validDate, invalidDate], 'casual tone', { softErrors: true });
if (formatted[1] instanceof TempoAiError) {
console.warn(`Format failed with code: ${formatted[1].code}`);
}
```
### Static Glossary Seeding
In addition to dynamic cache lookups, `initAI` can be initialized with a pre-seeded `BoundedCache` or synchronous `Map` containing immortal static business terms (e.g. company glossaries). Static entries bypass TTL expiration and LLM network requests:
```typescript
const glossary = new Map([
['fiscal_q3_start', '2026-07-01T00:00:00Z'],
['annual_shutdown', '2026-12-24T00:00:00Z']
]);
initAI({
providers: [{ id: 'openai', key: process.env.OPENAI_API_KEY }],
cache: glossary
});
const start = await parseAI('fiscal_q3_start'); // Resolves instantly from static cache without hitting network!
```
### Bypassing Cache & Forcing Network Requests
Passing `cache: false` disables reading and writing to the cache, but native pre-parsing may still resolve standard phrases. To guarantee an LLM provider request while disabling caching of the response, combine `force: true` with `cache: false`:
```typescript
// Forces an LLM network request and prevents reading or writing to cache
const dt = await parseAI("The last Friday before Christmas", { force: true, cache: false });
```
### Evicting Bad Parses
If the LLM hallucinates or returns an incorrect absolute date, you can explicitly purge the string from the cache:
```typescript
import { aiCache } from '@tempo-kit/plugin-ai';
// Evict a single string
await aiCache.clear("2nd tuesday in nov");
// Or purge all AI cached entries
await aiCache.clear();
```
### Forcing a Refresh
If you want to explicitly query the LLM again and *overwrite* the existing cache entry with the new result, use the `force: true` flag:
```typescript
const dt = await parseAI("Q3_START", { force: true });
```
### Extensible Caching & Async Storage Adapters (`AiCacheAdapter`)
By default, parsed AI responses are cached in memory using `Tempo.cache` (`BoundedCache`). For distributed serverless environments (e.g. Next.js, Cloudflare Workers, Express) or cluster nodes, you can pass a custom synchronous or asynchronous storage adapter (`AiCacheAdapter`):
```typescript
import { initAI, parseAI, type AiCacheAdapter } from '@tempo-kit/plugin-ai';
import { Redis } from '@upstash/redis';
const redis = new Redis({ url: process.env.UPSTASH_URL!, token: process.env.UPSTASH_TOKEN! });
// Implement custom async Redis storage adapter with namespacing & prefix deletion support
const redisAdapter: AiCacheAdapter = {
get: async (key) => (await redis.get(`tempo:ai:${key}`)) ?? undefined,
set: async (key, value, ttlMs) => {
if (ttlMs !== undefined) await redis.set(`tempo:ai:${key}`, value, { px: ttlMs });
else await redis.set(`tempo:ai:${key}`, value);
},
delete: async (key) => {
await redis.del(`tempo:ai:${key}`);
},
clear: async (prefix) => {
const pattern = prefix ? `tempo:ai:${prefix}*` : `tempo:ai:*`;
let cursor = '0';
do {
const [nextCursor, keys] = await redis.scan(cursor, { match: pattern, count: 100 });
cursor = nextCursor;
if (keys.length > 0) await redis.del(...keys);
} while (cursor !== '0');
}
};
initAI({
providers: [{ id: 'groq', key: process.env.GROQ_API_KEY!, ttl: 7200000 }], // Provider-specific TTL (2 hours)
cacheAdapter: redisAdapter,
ttl: 3600000 // Global default TTL (1 hour)
});
// Call-site TTL override (15 minutes)
const dt = await parseAI("next Monday at 9am", { ttl: 900000 });
```
### Cascading TTL Resolution Policies
The plugin calculates cache TTL per entry using a strict resolution hierarchy:
1. **Call-site `options.ttl`**: `parseAI(prompt, { ttl: 900000 })`
2. **Provider-level `provider.ttl`**: `providers: [{ id: 'groq', ttl: 7200000 }]`
3. **Global `initAI({ ttl: 3600000 })`**
4. **Default TTL**: `3,600,000` ms (1 hour)
### Fail-Open Cache Resilience
Custom storage adapter calls (`adapter.get` and `adapter.set`) are wrapped in safe error handlers. If an external Redis instance crashes or encounters a network partition, the plugin logs a debug warning (if `debug: true`) and gracefully fails open to direct LLM resolution without crashing the application request.
---
# Document: 9-plugins/ai.recurrence.md
# `scheduleAI` — Intelligent Appointment Booking & Conflict Resolution
`scheduleAI()` provides automated slot booking, calendar conflict detection, working hour verification, and iterative slot bumping. It evaluates a natural language booking request (e.g. *"45 min sync next Wednesday afternoon"*) alongside a list of existing busy intervals and working hours to find the best available appointment slots.
---
## Basic Usage
```typescript
import { scheduleAI, initAI } from '@tempo-kit/plugin-ai';
// 1. Initialize provider
await initAI({
providers: [{ id: 'groq', key: process.env.GROQ_API_KEY }]
});
// 2. Schedule a meeting avoiding team standups
const booking = await scheduleAI("45 min sync next Wednesday afternoon", {
anchor: "2026-08-10 09:00",
timeZone: "America/New_York",
events: [
{ start: "2026-08-12 14:00", end: "2026-08-12 15:00", title: "Team standup" }
],
workingHours: { start: "09:00", end: "17:00" } // only match New York business hours
});
console.log(booking.start.format('{yyyy}-{mm}-{dd} {hh}:{mi}')); // 2026-08-12 15:00
console.log(booking.end.format('{yyyy}-{mm}-{dd} {hh}:{mi}')); // 2026-08-12 15:45
console.log(booking.durationMinutes); // 45
console.log(booking.ai?.conflictBumped); // true (pushed past team standup)
```
---
## Configuration Options (`TempoScheduleOptions`)
| Option | Type | Description |
| :--- | :--- | :--- |
| **`anchor`** | `TempoDateInput` | Anchor reference time to evaluate relative dates from. Defaults to workstation/browser current time. |
| **`events`** | `Array` | A list of existing busy calendar intervals or booked events that the meeting must not overlap with. |
| **`workingHours`** | `TempoWorkingHours` | Daily time window constraint (hour:minute format) inside which slots must fit. |
| **`timeZone`** | `string` | Target IANA timezone to calculate the booking slot and boundaries within. |
| **`minConfidence`**| `number` | Minimum confidence score threshold (0.0 to 1.0) required to return a valid slot. |
| **`mode`** | `AiMode` | Concurrency routing strategy (`fallback`, `race`, `consensus`, `hedged`, `roundrobin`, `adaptive`). Refer to the [Multi-Provider Execution Modes Guide](./ai.modes.md). |
### `TempoInterval` Interface
```typescript
export interface TempoInterval {
start: Tempo;
end: Tempo;
}
```
### Event Input Shape (`ScheduleEventInput`)
The `events` (or `intervals`) option accepts raw event objects, continuous `TempoInterval` pairs, native `Interval` instances, or `[start, end]` tuples:
```typescript
export type ScheduleEventInput =
| { start: TempoDateInput; end: TempoDateInput; title?: string; label?: string }
| TempoInterval
| Interval
| [TempoDateInput, TempoDateInput]
| TempoDateInput;
```
---
## Result Schema (`TempoScheduleResult`)
```typescript
export interface TempoScheduleResult {
/** The calculated start timestamp of the selected slot */
start: Tempo;
/** The calculated end timestamp of the selected slot */
end: Tempo;
/** The resolved slot represented as a Tempo Interval object */
slot: Interval;
/** The duration of the resolved meeting in minutes */
durationMinutes: number;
/** Alternative available slot intervals that also satisfy all constraints */
alternatives: Interval[];
/** Metadata on the AI resolution process */
ai?: {
provider: string;
confidence: number;
conflictBumped: boolean; // True if the slot was pushed/bumped to avoid a busyEvent conflict
reasoning?: string;
};
}
```
---
## Internal Conflict Bumping Engine
When an LLM proposes a slot (like Wednesday at 2:00 PM), `scheduleAI` doesn't just trust it blindly. It runs a deterministic check using Tempo's native `Interval.overlaps()` method against your `events` list:
1. If the proposed slot overlaps with any busy event, the engine shifts (bumps) the slot forward iteratively.
2. It re-verifies the new slot against all other busy events and working hours constraints.
3. If it successfully lands on a free spot, it marks `ai.conflictBumped: true`.
4. If no free spot can be found within the proposed date frame, it returns a failed interval with low confidence.
This decoupled architecture ensures that the LLM is used for parsing intent (finding the duration and preferred time slot) while Tempo's math engine handles the strict conflict prevention.
---
# Document: 9-plugins/ai.security.md
# Security & Privacy Architecture
The `@tempo-kit/plugin-ai` plugin is engineered with a **"Privacy and Security by Default"** philosophy. Because date parsing and calendar scheduling frequently interact with Personally Identifiable Information (PII)—such as meeting attendees, emails, phone numbers, and sensitive notes—the plugin incorporates multi-layered security controls to protect user data across transit, runtime memory, log output, and caching tiers.
```mermaid
flowchart TD
subgraph Input ["1. Ingress & Transport"]
User["User Prompt / Event Data"] -->|"HTTPS / TLS 1.3 Enforcement"| Transport["Secure Transport Layer"]
end
subgraph Memory ["2. In-Memory Processing & Storage"]
Transport --> Schema["Rigid Schema Validation & Grounding"]
Schema --> Runtime["In-Memory Execution (Full Fidelity Access)"]
Runtime --> Cache["Partitioned Multi-Tier Cache (Namespaced by Tenant/TZ/Locale)"]
end
subgraph Egress ["3. Egress & Smart Debugging"]
Runtime --> ProxyMeta["Proxy-Wrapped Result Objects (attachCustomInspect)"]
ProxyMeta --> Logic["Application Business Logic (100% Raw Data Access)"]
ProxyMeta -->|"console.log() / util.inspect"| Logger["Smart Logger (logDebug) • NODE_ENV=production: Auto-Masked PII • NODE_ENV=development: Full Diagnostic Logs"]
end
```
---
## 1. Smart Debug Telemetry & PII Hardening
Debugging LLM integrations traditionally presents a major security dilemma: enabling debug logs often inadvertently dumps raw prompts containing sensitive user emails, phone numbers, and auth tokens into centralized log aggregators (e.g. Datadog, CloudWatch, Sentry).
`@tempo-kit/plugin-ai` significantly mitigates this risk through **Smart Debug Infrastructure**:
### Universal Environment Detection & Zero-Config Safety
* **Unified Flag**: Telemetry is enabled directly using `{ debug: true }` on individual requests or globally via `initAI({ debug: true })`.
* **Environment-Aware Sanitization**: The runtime automatically inspects `NODE_ENV`. In production environments (`NODE_ENV === 'production'`), all debug logs and terminal outputs automatically sanitize sensitive data before printing to `console.log` or `console.warn`.
* **Development Fidelity**: In non-production environments (local development, testing), full diagnostic strings are preserved for seamless prompt debugging.
### Automatic PII Redaction
In production mode, all debug telemetry is scrubbed through automated regex sanitizers:
* **Email Addresses**: Masked to initial and domain (e.g., `john.doe@enterprise.com` → `j***@enterprise.com`).
* **Phone Numbers**: Masked to last four digits (e.g., `+1-555-867-5309` → `***-***-5309`).
* **Bearer & API Tokens**: Redacted with prefix/suffix preservation (e.g., `Bearer sk-proj-1234...` → `Bearer sk-p...1234`).
* **Length Bounds**: Exceptionally long strings (> 256 characters) are safely truncated with character count annotations to prevent log bloat and denial-of-service attacks.
```typescript
import { parseAI, initAI } from '@tempo-kit/plugin-ai';
await initAI({
providers: [{ id: 'groq', key: process.env.GROQ_API_KEY }],
debug: true // Safe in all environments
});
// Input containing sensitive attendee data
const date = await parseAI("Meeting with john.smith@company.org (call 555-123-4567) next Friday");
// In Production, console.log(date.ai) outputs:
// {
// provider: 'groq',
// confidence: 0.98,
// rawPrompt: 'Meeting with j***@company.org (call ***-***-4567) next Friday',
// reasoning: 'Parsed meeting for next Friday with j***@company.org'
// }
```
---
## 2. Tamper-Resistant Proxy Introspection
All AI return objects (`Tempo.ai`, `TempoAiFormatResult`, `TempoAiExtractResult`, `TempoAiDiffResult`, `TempoScheduleResult`, `TempoRecurrenceResult`) utilize JavaScript `Proxy` wrappers and Node.js custom inspection hooks (`Symbol.for('nodejs.util.inspect.custom')` and `.toJSON()`):
1. **Terminal & Log Safety**: When an AI result object is logged via `console.log()`, `util.inspect()`, or serialized for telemetry, the custom inspection hook intercepts the call and outputs the PII-masked view.
2. **100% In-Memory Code Integrity**: In-memory property access within your application code (`date.ai?.rawPrompt`, `result.events[0].rawText`, `res.reasoning`) retains full, unmodified data fidelity.
3. **Deep Immutability**: Metadata properties attached to `Tempo` instances are frozen using `Object.freeze()`, preventing runtime tampering or prototype pollution by downstream code or dependencies.
```typescript
const result = await formatAI(targetDate, 'Notify alice.cooper@domain.com');
// 1. Terminal / Log Aggregators see sanitized PII in production:
console.log(result);
// => { formatted: '...', reasoning: '... client a***@domain.com ...' }
// 2. Your application code receives full raw fidelity:
const rawReasoning = result.reasoning;
// => "Formatted for client alice.cooper@domain.com"
```
---
## 3. Transport Security & Network Hardening
### Enforced HTTPS / TLS
* **Strict HTTPS Requirement**: All network communication with upstream LLM APIs and remote configuration servers must use HTTPS with modern TLS (TLS 1.2 or TLS 1.3).
* **Plaintext HTTP Disallowed**: Unencrypted HTTP endpoints are rejected at runtime, with an exception allowed exclusively for `localhost` origins during local development or unit testing with mock servers.
### Dynamic Manifest Host Verification
* **Trusted Remote Endpoints**: When `loadRemoteManifest` resolves provider manifests, it enforces trusted origin allowlists.
* **Provider URL Sanitization**: Any dynamic endpoint received via remote manifests or the `fetchDefaults` hook is verified before runtime merging. Disallowed hosts are rejected and stripped to prevent server-side request forgery (SSRF).
---
## 4. Credential Isolation & BYOK Architecture
### Automated In-Memory Key Redaction
* Calling `getAiConfig()` returns a sanitized, read-only configuration snapshot.
* All provider `key` values, authorization tokens, and shared secrets are permanently replaced with `[REDACTED]`, ensuring secrets cannot be leaked via diagnostic endpoints or error monitors.
### Dynamic Secret Vaults & Automated Key Rotation
* Provider `key` parameters support synchronous and asynchronous supplier functions (`AsyncEvaluable` / `() => Promise | string`), while `url`, `model`, and temporal context fields accept synchronous suppliers (`Evaluable`).
* **Enterprise Secret Vaults**: Instead of pinning long-lived static API keys in memory, applications can integrate cloud key vaults (e.g. AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, Doppler):
```typescript
initAI({
providers: [
{
id: 'openai',
// Evaluated just-in-time on every provider HTTP dispatch
key: async () => await secretVault.getSecret('OPENAI_API_KEY')
}
]
});
```
* **Multi-Tenant / Per-Request Key Isolation**: In SaaS applications where each tenant supplies their own BYOK credentials, resolve keys dynamically from the active request context without re-initializing global AI state:
```typescript
initAI({
providers: [
{
id: 'openai',
// Pulls tenant-specific key from AsyncLocalStorage or request session
key: () => {
const tenant = tenantStore.getStore();
if (!tenant) throw new Error('No tenant context found');
return tenant.openaiApiKey;
}
}
]
});
```
* **Short-Lived & OAuth Token Refreshers**: Dynamic suppliers allow automatic token refresh for short-lived credentials (e.g. Google Cloud Vertex AI / Azure Entra ID OAuth tokens) without service disruption:
```typescript
initAI({
providers: [
{
id: 'gemini',
key: async () => (await authClient.getAccessToken()).token
}
]
});
```
* Keys are fetched just-in-time prior to the HTTP request and never stored in plain text in persistent global state, enabling zero-downtime key rotation.
### Frontend Zero-Storage Principle
* **No Client-Side Secrets (Zero Browser Storage)**: LLM API keys must **never** be bundled into client-side single-page applications (React, Vue, Svelte) or stored in any browser storage (`localStorage`, `sessionStorage`, `IndexedDB`, `OPFS`, Web Locks, or browser cache). We recommend **zero browser storage** for API credentials; any client-side persistence remains accessible to same-origin scripts and vulnerable to XSS exfiltration.
* **Proxy Architecture**: Public frontend web applications must route requests through a self-hosted backend proxy or secure AI Gateway (Cloudflare Worker, Next.js API Route) where private API keys are kept server-side.
---
## 5. Ephemeral Processing, Partitioned Caching & Trial Gateway Data Handling
### Local Libraries Zero Telemetry Architecture
* The `tempo-kit` core library and `@tempo-kit/plugin-ai` package **collect zero telemetry, analytics, or prompt logs**.
* When using **Tier 2 (Private Backend Proxy)** or **Tier 3 (Direct Provider Keys / BYOK)**, prompt processing and temporal computations occur ephemerally during request execution directly between your infrastructure and your configured LLM provider. Zero data touches Magma Computing servers.
### Trial Sandbox Gateway (`provider: 'tempo'`) Data Handling & Diagnostics
> [!NOTE]
> **Attention: Trial Gateway Telemetry Notice**
> The public Tempo trial evaluation gateway (`provider: 'tempo'`) collects pseudonymous telemetry regarding sandbox usage (latency, error rates, model performance, token counts, and HMAC-SHA-256 salted IP hashes).
> This information is used to diagnose parsing failures, tune prompt schemas, and shape the plugin roadmap.
> For developers requiring strict zero retention or zero external logging, route requests through your own backend proxy (Tier 2) or direct BYOK provider keys (Tier 3) as detailed in our [Configuration & Onboarding Guide](./ai.onboarding.md).
* **Prompt Engineering & Diagnostics**: Natural language date expressions and model completion responses sent to the free trial gateway may be recorded in diagnostic telemetry records (when payload capture is enabled) to diagnose parsing edge cases, detect hallucinations, and tune temporal context prompts.
* **Pseudonymous IP Hashing**: Client IP addresses are hashed using HMAC-SHA-256 with a secure server-side salt prior to storage; the gateway stores this HMAC-derived pseudonymous IP identifier, while raw IP addresses are not stored.
* **Zero Retention Choice (Tier 2 & Tier 3)**: The free trial gateway provides community-subsidized compute for rapid prototyping. If your application handles sensitive data or requires strict zero data retention, use Tier 2 (custom backend proxy) or Tier 3 (direct BYOK keys).
* **Retention Policy**: Trial gateway telemetry records (including recorded prompt and completion diagnostic bodies) become eligible for automated deletion after **30 days** via Firestore TTL. Firestore TTL deletion executes asynchronously in the background, typically within 24 to 72 hours of TTL expiration.
* **Sensitive Data**: Do not submit proprietary or sensitive personal information through the trial sandbox gateway. For strict zero retention, configure your own backend proxy (`initAI({ endpoint })`) or private provider keys (`initAI({ provider: 'groq', apiKey })`) together with provider-side zero-data-retention controls and request-level cache bypass (`cache: false` or `force: true`) or a non-persisting cache adapter; local cache management via `Tempo.cache` or `AiCacheAdapter` provides caller-controlled client persistence.
### Partitioned Multi-Tier Caching
* **Namespaced Cache Keys**: Cache keys are generated with multi-factor domain partitioning (e.g., `diff::`, `format::`, `extract::`) incorporating the prompt text, anchor epoch, target timezone, locale, calendar system, and regional parameters to prevent contextual collision.
* **Storage Lifecycle**: Cached entries persist in the local `Tempo.cache` (`BoundedCache`) or caller-provided `AiCacheAdapter` (e.g. Redis, KV) strictly until TTL expiration or LRU capacity eviction.
* **Granular Bypass Controls**: Operations requiring zero cache persistence can supply `cache: false` or `force: true` on any individual request, or programmatically flush entries using `await aiCache.clear()`.
---
## 6. Schema Enforcement & Hallucination Defense
Large Language Models can occasionally hallucinate dates or output non-deterministic formats. `@tempo-kit/plugin-ai` prevents invalid data propagation through strict input/output boundaries:
1. **Rigid Schema Validation**: All provider completions are validated against deterministic schemas and regex patterns prior to object construction.
2. **Confidence Threshold Gating**: The plugin enforces configurable `minConfidence` thresholds (e.g. `minConfidence: 0.85`). Results falling below the threshold throw a typed `TempoAiError` or trigger automatic fallback.
3. **Deterministic Grounding Fallbacks**: Grounding metrics (such as business days, calendar day offsets, and duration calculations) are verified using deterministic `Tempo` calculations rather than unverified LLM assumptions.
---
## 7. Residual Risks & Threat Model Matrix
> [!IMPORTANT]
> **Primary Production Strategy**: The primary recommendation for production environments is to keep **`debug: false`** (the default). Smart Debug is designed as an automated safety net to prevent catastrophic PII leaks when developers troubleshoot live issues, but no automated sanitization layer can eliminate 100% of risk when raw diagnostic telemetry is captured.
The following matrix documents residual threat vectors and recommended mitigations:
| Threat Vector | Source | Risk Level | Architectural Behavior | Recommended Mitigation |
| :--- | :--- | :---: | :--- | :--- |
| **Direct Primitive Logging** | Developer `console.log(res.reasoning)` | Medium | Evaluates to the raw in-memory string and bypasses object inspection hooks. | Log entire result objects (`console.log(res)`) or leave `debug: false`. |
| **Object Spread Logging** | `console.log({ ...res })` | Low | Spreading copies raw enumerable keys into a plain object without non-enumerable inspect symbols. | Log the object directly (`console.log(res)`) rather than shallow spreading. |
| **Network-Layer APM Tracing** | Datadog, OpenTelemetry, Sentry HTTP capture | High | APM agents monkey-patching `fetch` capture raw outbound HTTP payloads in transit. | Disable full HTTP body capture on LLM routes in your APM configuration. |
| **Semantic PII** | Unstructured names, physical addresses, health info | Medium | Regexes catch structured PII (emails, phones, tokens) but not unstructured names/addresses. | Rely on payload truncation limits (< 256 chars) and avoid `debug: true` on sensitive workflows. |
| **Environment Variable Drift** | `NODE_ENV` not set or misconfigured | Low | Logger checks `NODE_ENV` (`production`, `prod`, `live`) and `PROD=true`. If unset, defaults to dev mode. | Verify deployment manifests explicitly export `NODE_ENV=production`. |
| **External Cache Driver Logs** | Third-party Redis/DB client debug logs | Low | Distributed cache adapters store raw JSON required to rehydrate `Tempo` instances. | Ensure production Redis/database clients have debug logging disabled. |
---
# Document: 9-plugins/ai.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
Integrating Large Language Models (LLMs) with date-time logic presents severe reliability hazards in production:
1. **Hallucinated Dates**: Models routinely miscalculate weekday-to-date mappings (e.g. claiming "next Friday" is the 14th when it is actually the 15th).
2. **Missing Reference Anchors**: Without an explicit reference anchor, relative expressions (*"in 3 days"*, *"tomorrow afternoon"*) resolve against arbitrary training cutoff dates.
3. **PII Leakage**: Sending full user prompts to third-party LLMs exposes sensitive user identities and private calendar details.
The `@tempo-kit/plugin-ai` plugin bridges LLM intelligence with Tempo's deterministic temporal engine, enforcing strict PII protection, anchor grounding, and schema validation.
---
## 1. Natural Language Booking: Ambiguous Input to Validated `Tempo`
In conversational scheduling bots (such as appointment booking agents or support chatbots), users describe meeting times in informal natural language:
- *"Can we meet next Wednesday at 2:30pm for 45 minutes?"*
- *"Schedule a review session on the second Friday of next month at 10am"*
`Tempo.ai.parse` grounds the prompt against an absolute server reference anchor (`anchor`) and user timezone, resolving a strongly typed `Tempo` instance:
```typescript
import '@tempo-kit/plugin-ai/install';
import { Tempo } from 'tempo-kit';
export async function parseAppointmentPrompt(
userInput: string,
userTimeZone: string
): Promise<{ scheduledStart: Tempo; durationMinutes: number }> {
// Ground the prompt against current time and user timezone
const anchorTime = new Tempo('now', { timeZone: userTimeZone });
const appointment = await Tempo.ai.parse(userInput, {
anchor: anchorTime,
timeZone: userTimeZone
});
return {
scheduledStart: appointment,
durationMinutes: 45
};
}
```
---
## 2. Converting Natural Language Recurrence to RFC 5545 RRULE
Calendar applications (Google Calendar, Outlook, Apple Calendar) require standard RFC 5545 iCalendar **RRULE** strings to synchronize recurring events. Parsing human recurrence patterns into valid RRULEs with deterministic end dates is error-prone.
`Tempo.ai.recurrence` converts natural language patterns directly into validated RRULE strings:
```typescript
import '@tempo-kit/plugin-ai/install';
import { Tempo } from 'tempo-kit';
export async function generateCalendarRule(recurrencePrompt: string): Promise {
const result = await Tempo.ai.recurrence(recurrencePrompt, {
anchor: new Tempo('now')
});
// Returns standard iCalendar RRULE format:
// e.g. "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU;COUNT=10"
return result.rrule;
}
// Example prompts:
// "every other Tuesday for 10 sessions" -> FREQ=WEEKLY;INTERVAL=2;BYDAY=TU;COUNT=10
// "first Monday of every month" -> FREQ=MONTHLY;BYDAY=1MO
```
---
## 3. Conflict-Free Slot Scheduling Around Busy Calendar Events
When building scheduling platforms (such as Calendly or Cal.com workflows), booking engines must calculate the first open slot that fits between existing busy event bounds.
`Tempo.ai.schedule` inspects an array of existing busy bounds and finds non-overlapping appointment slots within working hours:
```typescript
import '@tempo-kit/plugin-ai/install';
import { Tempo } from 'tempo-kit';
interface BusyBlock {
start: string;
end: string;
}
export async function findNextAvailableSlot(
busyCalendar: BusyBlock[],
requestedDurationMinutes: number
): Promise<{ slotStart: Tempo; slotEnd: Tempo }> {
const scheduleResult = await Tempo.ai.schedule({
busy: busyCalendar,
durationMinutes: requestedDurationMinutes,
workingHours: { start: '09:00', end: '17:00' },
anchor: new Tempo('now')
});
return {
slotStart: scheduleResult.start,
slotEnd: scheduleResult.end
};
}
```
---
## 4. Contextual Narrative Summaries for Customer Notifications
Raw ISO-8601 strings (`2026-10-05T14:30:00Z`) or mechanical countdowns (*"in 48 hours"*) feel impersonal in user-facing delivery updates or customer notifications.
`Tempo.ai.format` generates human-friendly, contextual narrative summaries with reasoning metadata:
```typescript
import '@tempo-kit/plugin-ai/install';
import { Tempo } from 'tempo-kit';
export async function createDeliveryNotification(deliveryDateIso: string): Promise {
const delivery = new Tempo(deliveryDateIso);
const narrative = await Tempo.ai.format(delivery, {
style: 'concise',
context: 'e-commerce package arrival'
});
// Generates contextual prose:
// "Arriving this Monday afternoon (in about 2 days)"
return narrative.formatted;
}
```
---
## 5. Enterprise PII Masking & Air-Gapped Fallback
In regulated enterprise environments (healthcare, finance, government), sending raw customer text to external LLMs breaches data privacy mandates (HIPAA, GDPR).
`tempo-plugin-ai` provides built-in PII redaction and multi-provider race/fallback modes. You can configure sensitive queries to route through an on-premise local model (e.g. Ollama) while falling back to cloud providers:
```typescript
import '@tempo-kit/plugin-ai/install';
import { Tempo } from 'tempo-kit';
// Initialize with local on-premise provider and cloud fallback
await Tempo.ai.init({
mode: 'fallback',
providers: [
{
id: 'ollama',
endpoint: 'http://localhost:11434/api/generate',
models: { default: 'llama3:8b' }
},
{
id: 'groq',
key: process.env.GROQ_API_KEY
}
]
});
```
---
# Document: 9-plugins/batch.index.md

# @tempo-kit/plugin-batch
This is a Community plugin for the [Tempo](https://github.com/magmacomputing/magma) library that parallelizes massive epoch mutation tasks across worker threads utilizing lock-free `SharedArrayBuffer` shared memory architecture for extreme throughput.
::: tip Perfect For
Heavy data ETL pipelines, massive IoT telemetry ingestion, financial ledger backtesting, and parallel bulk date-processing workloads.
:::
---
## Key Features
- **Worker-Thread Parallelism**: Splits massive epoch arrays across a background worker pool (`threads` defaults to the number of CPU cores).
- **Lock-Free Shared Memory**: Built on `SharedArrayBuffer` for zero-copy transfer, with a `postMessage` structural-cloning fallback.
- **Duration Shorthand Operations**: Mutate with `'+1w'`, `'+2 days'`, `'-15 mins'`, `'+1mo'`, or `'+1y'`.
- **Peak-Throughput Output**: Returns raw numeric timestamps by default; set `rehydrate: true` to receive `Tempo[]`.
- **Low-Level Access**: Exports `BatchOrchestrator` for direct `transform()` control.
---
## Installation
```bash
npm install @tempo-kit/plugin-batch
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { BatchPlugin } from '@tempo-kit/plugin-batch';
Tempo.use(BatchPlugin);
// Assume `epochs` is a massive array of integers representing timestamps
const epochs = [1700000000000, 1700000001000, /* ... millions more ... */];
// Mutate millions of dates concurrently using the background worker pool!
// The engine automatically splits the payload and offloads to workers
const batchResult = await Tempo.batch(epochs, '+1w', { threads: 4 });
console.log(batchResult); // Returns an array of mutated timestamp integers
```
### Zero-Boilerplate Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-batch/install';
const epochs = [1700000000000, 1700000001000];
const batchResult = await Tempo.batch(epochs, '+1w');
```
---
## API Reference
The Batch plugin mounts the static `Tempo.batch()` method and exports the underlying `BatchOrchestrator`:
| Export / Method | Signature | Returns | Description |
| :--- | :--- | :--- | :--- |
| **`Tempo.batch()`** | `(epochs: number[], operation: string, options?: BatchOptions)` | `Promise` | Splits the input array across worker threads and applies duration mutation. |
| **`BatchOrchestrator`** | Static class | `BatchOrchestrator` | Low-level orchestration engine with `transform()` and `sanitizeExecArgv()` tools. |
### Configuration Options (`BatchOptions`)
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| **`threads`** | `number` | `os.cpus().length` | Number of worker threads to allocate for the pool. |
| **`rehydrate`** | `boolean` | `false` | When `false`, returns raw numeric timestamps (`number[]`) for peak throughput. When `true`, rehydrates output numbers into `Tempo[]` instances. |
### Supported Mutation Operations
The `operation` parameter accepts either standard duration strings or shorthand intervals:
* Days: `'+1d'`, `'+2 days'`, `'-5d'`
* Weeks: `'+1w'`, `'+4 weeks'`
* Hours: `'+1h'`, `'+8 hours'`
* Minutes: `'+30m'`, `'-15 mins'`
* Months / Years: `'+1mo'`, `'+1y'`
---
## Topic Guides
- **[Parallel Worker Pool & SharedArrayBuffer Architecture](./batch.worker-architecture.md)**: Zero-copy `SharedArrayBuffer` vs `postMessage` structural cloning fallback, browser Cross-Origin Isolation (`COOP`/`COEP`), and worker isolate CLI flag allowlisting.
- **[Production Use Cases & Architectural Patterns](./batch.use-cases-and-patterns.md)**: Industrial IoT telemetry clock skew correction, financial tick backtesting pipelines, and large-scale CSV payroll processing.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/batch.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
This guide explores real-world systems patterns where `@tempo-kit/plugin-batch` accelerates high-volume temporal processing across multi-core server environments.
---
## 1. High-Throughput IoT Telemetry Skew Normalization
### Problem Statement
An industrial IoT gateway collects sensor packets from thousands of field devices. Due to firmware clock drift, timestamps must be shifted forward by a calibrated skew correction (e.g. `+12 seconds` or `+2 hours`) before being inserted into a time-series database. Processing 500,000 timestamps on the main Node.js event loop blocks incoming network sockets and causes packet loss.
### Architectural Solution
Use `Tempo.batch()` to offload the transformation to worker threads. The raw epoch numbers are transformed directly in shared memory (`SharedArrayBuffer`), keeping the main thread free to handle HTTP/MQTT connections.
```
Incoming Telemetry Batch (500k Epochs)
│
▼
Tempo.batch(epochs, '+12s')
│
┌───────────┼───────────┐
▼ ▼ ▼
Worker #1 Worker #2 Worker #3
(SharedArrayBuffer Float64Array Slices)
│
▼
Zero-Copy Mutated Epoch Array -> PostgreSQL TimescaleDB
```
### Production Implementation
```typescript
import { Tempo } from 'tempo-kit';
import { BatchPlugin } from '@tempo-kit/plugin-batch';
Tempo.use(BatchPlugin);
export interface IngestedTelemetryBatch {
deviceId: string;
skewOffset: string; // e.g. "+12s" or "-30m"
rawEpochs: number[];
}
/**
* Normalizes device telemetry timestamps in background workers.
*/
export async function normalizeDeviceBatch(batch: IngestedTelemetryBatch): Promise {
// Parallelize the mutation across available CPU cores
const normalizedEpochs = await Tempo.batch(batch.rawEpochs, batch.skewOffset, {
rehydrate: false // keep as primitive numbers for maximum database bulk-copy throughput
});
return normalizedEpochs;
}
// Example Execution
const sampleEpochs = [1700000000000, 1700000001000, 1700000002000];
const normalized = await normalizeDeviceBatch({
deviceId: 'turbine-north-4',
skewOffset: '+1h',
rawEpochs: sampleEpochs
});
console.log('Original first epoch: ', sampleEpochs[0]);
console.log('Normalized first epoch:', normalized[0]); // 3600000 ms later
```
---
## 2. Financial Tick Data Backtesting & Interval Rolling
### Problem Statement
Quantitative trading algorithms simulate portfolio strategies over millions of historical trade ticks. Backtesting requires rolling timestamps forward across multiple simulation runs (e.g. testing strategy execution across shifted trading windows: `+1 week`, `+2 weeks`, `+1 month`). Processing 10,000,000 ticks sequentially in JavaScript takes tens of seconds.
### Architectural Solution
By specifying a dedicated thread pool size (`{ threads: 8 }`), `Tempo.batch` divides the 10M record array evenly across 8 workers, utilizing SIMD-like concurrent chunking to complete the transformation in a fraction of the time.
```typescript
import { Tempo } from 'tempo-kit';
import { BatchPlugin } from '@tempo-kit/plugin-batch';
Tempo.use(BatchPlugin);
export class BacktestEngine {
/**
* Shifts historical trade tick epochs into a prospective simulation window.
*/
static async shiftSimulationWindow(historicalEpochs: number[], windowShift = '+1w'): Promise {
console.time('Parallel Batch Shift');
const shiftedEpochs = await Tempo.batch(historicalEpochs, windowShift, {
threads: 8,
rehydrate: false
});
console.timeEnd('Parallel Batch Shift');
return shiftedEpochs;
}
}
```
---
## 3. Large-Scale CSV Payroll Date Processing
### Problem Statement
A payroll processing SaaS application receives monthly employee attendance CSV files containing hundreds of thousands of punch-clock records. The system needs to validate overtime boundaries by rolling dates forward to the nearest pay-period closing cycle and rehydrating them as full `Tempo` objects for business logic inspection.
### Architectural Solution
Use `{ rehydrate: true }` to receive fully initialized, immutable `Tempo` instances directly from the worker pool once parallel arithmetic finishes:
```typescript
import { Tempo } from 'tempo-kit';
import { BatchPlugin } from '@tempo-kit/plugin-batch';
Tempo.use(BatchPlugin);
export async function processPayrollEpochs(attendancePunchEpochs: number[]): Promise {
// Shift punch times to the closing cycle and rehydrate into Tempo instances
const payrollInstances: Tempo[] = await Tempo.batch(attendancePunchEpochs, '+14d', {
rehydrate: true // returns Tempo[] instances
});
return payrollInstances;
}
// Result: Array of fully featured Tempo objects ready for business rules
const instances = await processPayrollEpochs([1700000000000, 1700000005000]);
console.log(instances[0].format('{yyyy}-{mm}-{dd}'));
```
---
# Document: 9-plugins/batch.worker-architecture.md
# Parallel Worker Pool & SharedArrayBuffer Architecture
The `@tempo-kit/plugin-batch` plugin accelerates bulk date mutations across multi-core systems by partitioning massive epoch arrays and executing calculations concurrently across a pool of background worker threads.
---
## Dual-Mode Execution Engine
The orchestrator dynamically inspects the host runtime and automatically selects between zero-copy shared memory or structural cloning:
```
Tempo.batch(epochs, operation, options)
│
Is SharedArrayBuffer Available?
├─── YES ───► Mode A: SharedArrayBuffer (Zero-Copy)
└─── NO ───► Mode B: postMessage Structural Cloning
```
### Mode A: Lock-Free `SharedArrayBuffer` (High Throughput)
When running in Node.js or in browsers with Cross-Origin Isolation enabled:
1. The master process allocates two shared memory buffers sized to the exact input length:
```typescript
const inputBuffer = new SharedArrayBuffer(epochs.length * 8);
const outputBuffer = new SharedArrayBuffer(epochs.length * 8);
```
2. A typed `Float64Array` view is mounted over the buffer. Each 64-bit IEEE 754 double stores one millisecond timestamp.
3. The workload is partitioned into balanced slices (`chunkSize = Math.ceil(epochs.length / threadCount)`).
4. Each worker thread receives references to the shared memory buffers along with its assigned slice indices (`startIdx`, `endIdx`).
5. Workers access the shared buffers directly, mutating timestamps in place within their assigned slices, and post a lightweight `{ status: 'done' }` signal upon completion. Shared buffer access avoids serialization and array cloning across the thread boundary.
### Mode B: `postMessage` Structural Cloning (Graceful Degradation)
When running in browser environments where `SharedArrayBuffer` is restricted by security policies:
1. The orchestrator slices the input array into standard JavaScript array chunks.
2. Slices are transferred to workers via standard `postMessage({ chunk })`.
3. Workers compute results and post back the mutated array.
4. The main thread reassembles the chunked arrays into a single contiguous result.
---
## Worker Process Isolation & CLI Flag Sanitization
In Node.js, spawning worker threads via `new Worker()` automatically attempts to pass `process.execArgv` to child isolates. However, passing unverified process flags (such as `--max-old-space-size`, `--eval`, or custom CLI arguments) can crash worker isolates or cause memory segmentation faults.
To guarantee worker stability, `BatchOrchestrator` implements strict **ExecArgv Allowlist Sanitization**:
```typescript
const ALLOWED_FLAGS_WITH_VALUE = new Set([
'--import',
'--loader',
'--experimental-loader',
'-r',
'--require',
]);
const ALLOWED_STANDALONE_FLAGS = new Set([
'--experimental-vm-modules',
'--experimental-temporal',
'--experimental-specifier-resolution',
'--inspect',
'--inspect-brk',
'--trace-warnings',
'--no-warnings',
]);
```
Any process-level flags, heap limit overrides, or execution scripts outside this allowlist are safely stripped before worker initialization.
---
## Performance Trade-Off: Raw Epochs vs Hydration
To maximize processing speed across large payloads (e.g., 100,000 to 5,000,000 timestamps):
| Configuration | Output Type | Processing Characteristics | Ideal For |
| :--- | :--- | :--- | :--- |
| **`{ rehydrate: false }`** *(Default)* | `number[]` | **Ultra-Fast**. Returns raw numeric timestamps. Zero object allocation overhead on the main thread. | Telemetry ETL pipelines, database bulk inserts, streaming Kafka messages. |
| **`{ rehydrate: true }`** | `Tempo[]` | **Rich Object Surface**. Main thread maps output numbers into full `Tempo` instances. | UI display grids, domain models requiring immediate formatting or method access. |
### Benchmark Guidance
For arrays exceeding `50,000` items, keeping `{ rehydrate: false }` until final consumption reduces garbage collection pauses by up to **85%**.
---
# Document: 9-plugins/celestial.astro.md
# Astronomical Seasons, Solstices & Equinoxes
This guide explores astronomical solar quarters, equinoxes, solstices, and hemisphere-aware season calculations in `@tempo-kit/plugin-celestial`.
---
## 1. Overview & Mechanics {#overview}
`AstroTerm` (`t.term.astro`, `t.term.astronomy`, `t.term.equinox`, `t.term.solstice`) calculates the precise astronomical moments when the Sun crosses the celestial equator (Equinoxes) or reaches its northernmost / southernmost declinations (Solstices).
Calculations utilize the high-precision Jean Meeus solar ephemeris polynomial algorithms implemented in `tempo-fns`, providing sub-minute accuracy across historical and future years without requiring internet access.
---
## 2. Astronomical Events & Quarters {#events-and-quarters}
| Event Key | Astronomical Event | Northern Hemisphere Season | Southern Hemisphere Season | Approximate Date |
| :--- | :--- | :--- | :--- | :--- |
| `'Vernal'` | **Spring Equinox** (Solar Longitude = 0°) | Spring | Autumn | March 20–21 |
| `'Summer'` | **Summer Solstice** (Solar Longitude = 90°) | Summer | Winter | June 20–22 |
| `'Autumnal'` | **Autumnal Equinox** (Solar Longitude = 180°) | Autumn | Spring | September 22–23 |
| `'Winter'` | **Winter Solstice** (Solar Longitude = 270°) | Winter | Summer | December 21–22 |
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
// 1. Northern Hemisphere evaluation
const summerNorth = new Tempo('2026-07-15', { sphere: 'north' });
console.log(summerNorth.term.astro); // 'Summer'
console.log(summerNorth.term.astronomy.season); // 'Summer'
console.log(summerNorth.term.astronomy.event); // 'Solstice'
console.log(summerNorth.term.solstice); // 'Summer'
// 2. Southern Hemisphere evaluation (inverts seasonal labels)
const winterSouth = new Tempo('2026-07-15', { sphere: 'south' });
console.log(winterSouth.term.astro); // 'Summer' (astronomy quarter key)
console.log(winterSouth.term.astronomy.season); // 'Winter' (actual hemisphere season)
console.log(winterSouth.term.astronomy.event); // 'Solstice'
// 3. Automatic sphere derivation via geographic coordinates
const sydney = new Tempo('2026-07-15', { geo: { lat: -33.8688, lng: 151.2093 } });
console.log(sydney.sphere); // 'south' (auto-derived from negative latitude)
console.log(sydney.term.astronomy.season); // 'Winter'
```
---
## 3. Scoped Ephemeris Details (`t.term.astronomy`) {#astronomy-details}
Accessing `t.term.astronomy` provides the complete structured record for the active astronomical quarter:
```typescript
const t = new Tempo('2026-03-20T12:00:00Z', { sphere: 'north' });
const astro = t.term.astronomy;
console.log(astro.key); // 'Vernal'
console.log(astro.keys); // ['Vernal', 'Summer', 'Autumnal', 'Winter']
console.log(astro.season); // 'Spring'
console.log(astro.event); // 'Equinox'
console.log(astro.span.start); // Tempo instance for the quarter's start boundary
console.log(astro.span.end); // Tempo instance for the quarter's end boundary
```
---
## 4. Querying Specific Astronomical Events (`t.term.equinox` / `t.term.solstice`) {#specific-events}
You can filter queries directly for equinoxes or solstices:
```typescript
const spring = new Tempo('2026-04-01', { sphere: 'north' });
// Resolves only equinoxes
console.log(spring.term.equinox); // 'Vernal'
// Resolves only solstices
const june = new Tempo('2026-06-25', { sphere: 'north' });
console.log(june.term.solstice); // 'Summer'
```
---
## 5. Standalone Usage {#standalone}
If you only need astronomical seasons without the other celestial ephemeris terms, you can import and register `AstroTerm` directly:
```typescript
import { Tempo } from 'tempo-kit';
import { AstroTerm } from '@tempo-kit/plugin-celestial';
Tempo.use(AstroTerm);
const t = new Tempo('2026-09-23', { sphere: 'north' });
console.log(t.term.astro); // 'Autumnal'
```
---
# Document: 9-plugins/celestial.index.md

# @tempo-kit/plugin-celestial
A Community plugin for [Tempo](https://github.com/magmacomputing/magma) providing location-aware solar twilight events (`t.term.sun`, `t.term.solar`), real-time lunar cycle phases (`t.term.moon`, `t.term.lunar`), and astronomical tidal mechanics (`t.term.tide`, `t.term.tides`).
---
## Key Features
- **Solar Day Cycles**: Calculates `daylight`, `night`, `civil-twilight`, `nautical-twilight`, and `astronomical-twilight`.
- **Solar Ephemeris Data**: Returns `sunrise`, `sunset`, `noon`, `solarTime` (Local Apparent Solar Time), total `daylightDurationMs`, and observer `elevation` horizon dip adjustments.
- **Lunar Phase & Topocentric Ephemeris**: Calculates 8 discrete lunar phase states, illumination fraction (0.0–1.0), age in days, hemisphere-aware emojis, local `moonrise` and `moonset` events, meridian transit (`transit`), topocentric position (`altitude`/`azimuth`), bright limb crescent tilt (`crescentTiltDeg`), and orbital distance (`distanceKm`, `angularDiameterArcmin`, `isSupermoon`, `isMicromoon`).
- **Local Eclipse Obscuration**: Detects active solar and lunar eclipses (`'total-solar'`, `'annular-solar'`, `'partial-solar'`, `'total-lunar'`, `'partial-lunar'`, `'penumbral-lunar'`) and computes local disk obscuration fraction (`0.0` to `1.0`).
- **Astronomical Tidal Mechanics**: Provides pure astronomical solar/lunar alignment calculations (`t.term.tide`, `t.term.tides`) for `spring`, `neap`, and `normal` tides, alongside `isKingTide` perigee indicators.
---
## Installation
```bash
npm install @tempo-kit/plugin-celestial
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
// Provide geographic coordinates (e.g. New York City)
const t = new Tempo('2026-06-21T12:00:00Z', {
timeZone: 'America/New_York',
geo: { lat: 40.7128, lng: -74.006 }
});
// --- Solar Day State & Ephemeris ---
console.log(t.term.sun); // 'daylight'
console.log(t.term.solar.phase); // 'Daylight'
console.log(t.term.solar.sunrise); // Tempo instance for local sunrise
console.log(t.term.solar.noon); // Tempo instance for local solar noon
console.log(t.term.solar.solarTime); // Tempo instance for local apparent solar time (AST)
// --- Lunar Phase & Ephemeris ---
console.log(t.term.moon); // 'waxing-crescent'
console.log(t.term.lunar.phase); // 'Waxing Crescent'
console.log(t.term.lunar.illumination); // 0.45
console.log(t.term.lunar.moonrise); // Tempo instance for local moonrise (or null)
// --- Astronomical Tidal Mechanics ---
console.log(t.term.tide); // 'spring', 'neap', or 'normal'
console.log(t.term.tides.alignmentDeg); // Solar-lunar alignment angle (0..360°)
console.log(t.term.tides.isSpringTide); // true during Syzygy (New or Full Moon)
console.log(t.term.tides.isKingTide); // true when Spring Tide aligns with Lunar Perigee
// --- Term Lifecycle Hooks ---
// Snapping & stepping
t.set('#moon.start'); // Snap to start of active lunar phase
t.add('#moon'); // Step forward by 1 synodic lunation (~29.53 days)
t.set('#solar.start'); // Snap to sunrise
t.set('#solar.mid'); // Snap to solar noon
t.add('#tide'); // Step forward by 1 tidal cycle (745 min)
// Semantic parsing & ordinals
const nextSunrise = Tempo.from('#solar.sunrise', { anchor: t });
const equinox = Tempo.from('1st day of #equinox', { anchor: t });
// Dynamic token formatting
console.log(t.format('Moon: {#moon.emoji} {#moon.phase} ({#moon.illumination})'));
console.log(t.format('Sun: {#solar.phase} | Elev: {#solar.elevation}'));
```
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-celestial/install';
const t = new Tempo('2026-06-21T12:00:00Z', { geo: { lat: 40.7128, lng: -74.006 } });
console.log(t.term.sun);
```
### Geographic Coordinates & Null Contract
::: tip Pure Astronomical Calculations
Tidal state resolution and synodic lunar phases rely on deterministic celestial mechanics for reproducible, offset-independent math across all time zones.
:::
::: warning Location-Dependent Null Contract
- **Global Astronomical Properties** (`t.term.moon`, `t.term.lunar.phase`, `t.term.lunar.illumination`, `t.term.tides.isSpringTide`, `t.term.tides.alignmentDeg`) resolve location-independently and are always computed.
- **Geo-Dependent Properties** (`t.term.sun`, `solar.sunrise`, `solar.sunset`, `solar.noon`, `solar.solarTime`, `lunar.moonrise`, `lunar.moonset`, `lunar.transit`, `lunar.altitude`, `lunar.azimuth`, `lunar.crescentTiltDeg`, `lunar.distanceKm`, `lunar.eclipse`, `lunar.obscuration`, `tides.lunarTideMinute`) evaluate to `null` when geographic coordinates (`geo: { lat, lng }`) are omitted.
- **Distinction**: Property access on `t.term` evaluates to `undefined` if `CelestialPlugin` is not loaded, and to `null` if the plugin is active but location coordinates were not supplied. When `debug >= 1` is enabled in `Tempo` configuration, a developer warning is logged when evaluating geo-dependent keys without coordinates.
:::
::: tip Coordinates, Sphere & Timezone Resolution
- **`sphere` Derivation**: Setting `{ geo: { lat, lng } }` automatically computes the observer's hemisphere (`'north'`, `'south'`, or `'equator'`).
- **`timeZone` Requirement**: Geographic coordinates (`lat`, `lng`) calculate the exact physical UTC moments of astronomical events, but **do not** auto-derive political timezone boundaries in core Tempo. Always supply an explicit `timeZone` (e.g. `'America/New_York'` or `'UTC'`) to ensure local day and night ranges project deterministically across different host environments and CI runners.
:::
---
## Topic Guides
Explore detailed guides on specific celestial capabilities:
- **[Astronomical Seasons, Solstices & Equinoxes](./celestial.astro.md)**: Solar quarters, equinoxes, solstices, hemisphere-aware seasonal labels (`t.term.astro`, `t.term.equinox`, `t.term.solstice`), and sub-minute Meeus ephemeris boundaries.
- **[Solar Day Cycles & Ephemeris](./celestial.solar.md)**: Twilight bands (`civil`, `nautical`, `astronomical`), atmospheric elevation dip correction, exact apparent solar noon (`solar.noon`), and Local Apparent Solar Time (`solar.solarTime`).
- **[Lunar Ephemeris, Topocentric Ephemeris & Eclipses](./celestial.lunar.md)**: 8 synodic lunar phases, illumination ratio, lunar age, hemisphere-aware emojis, topocentric horizon events (`moonrise`/`moonset`), meridian transits (`transit`), real-time sky position (`altitude`/`azimuth`), crescent tilt (`crescentTiltDeg`), orbital distance (`isSupermoon`/`isMicromoon`), and local solar/lunar eclipse detection (`eclipse`/`obscuration`).
- **[Astronomical Tidal Mechanics](./celestial.tidal.md)**: Syzygy, quadrature, and perigee calculations (`spring`, `neap`, `king` tides), solar-lunar alignment angles, and 745-minute tidal cycles.
- **[Production Use Cases & Architectural Patterns](./celestial.use-cases-and-patterns.md)**: Photovoltaic microgrid inverter modes, greenhouse DLI supplemental lighting, maritime keel clearance windows, and golden hour drone flight scheduling.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/celestial.lunar.md
# Solar Day Cycles, Ephemeris & Apparent Solar Time
This guide covers solar twilight state classifications, horizon dip elevation adjustments, exact solar noon, Local Apparent Solar Time (AST), real-time horizontal coordinates, photometric lighting phases, and polar day/night handling in `@tempo-kit/plugin-celestial`.
---
## 1. Solar Phase States (`t.term.sun` / `t.term.solar`) {#solar-phase-states}
`SolarTerm` classifies the solar day into 5 deterministic states based on the Sun's center angle relative to the local geometric horizon:
| Solar State | Solar Elevation Angle (α) | Description |
| :--- | :--- | :--- |
| `'daylight'` | `α ≥ -0.833° - dip` | Sun is above the visible horizon. Full natural illumination. |
| `'civil-twilight'` | `-6° ≤ α < -0.833° - dip` | Bright twilight. Terrestrial objects are clearly distinguishable without artificial light. |
| `'nautical-twilight'` | `-12° ≤ α < -6°` | Medium twilight. Sea horizon is faintly visible; first-magnitude navigation stars appear. |
| `'astronomical-twilight'` | `-18° ≤ α < -12°` | Dark twilight. Sun no longer illuminates the sky; fainter stars become visible. |
| `'night'` | `α < -18°` | Total astronomical darkness. |
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
const t = new Tempo('2026-06-21T12:00:00Z', {
timeZone: 'America/New_York',
geo: { lat: 40.7128, lng: -74.006 }
});
console.log(t.term.sun); // 'daylight'
console.log(t.term.solar.key); // 'daylight'
console.log(t.term.solar.phase); // 'Daylight'
console.log(t.term.solar.keys); // ['night', 'astronomical-twilight', 'nautical-twilight', 'civil-twilight', 'daylight']
```
::: tip Explicit Timezone Pairing
While `{ geo: { lat, lng } }` automatically determines `sphere`, it does not auto-infer political timezone rules. Always pair geographic coordinates with an explicit `timeZone` (e.g. `'America/New_York'` or `'UTC'`) to ensure twilight ranges and day/night boundary timestamps project deterministically across all environments (including CI runners and cloud servers).
:::
---
## 2. Apparent Solar Noon (`t.term.solar.noon`) {#solar-noon}
`t.term.solar.noon` returns a `Tempo` instance representing the exact moment of the Sun's transit across the local observer's celestial meridian (the highest solar altitude of the day).
```typescript
const t = new Tempo('2026-06-21T12:00:00Z', { geo: { lat: 40.7128, lng: -74.006 } });
const solarNoon = t.term.solar.noon;
console.log(solarNoon.iso); // e.g. "2026-06-21T16:57:21.134Z"
```
---
## 3. Local Apparent Solar Time (`t.term.solar.solarTime`) {#apparent-solar-time}
Local Apparent Solar Time (AST) is the time measured directly by the apparent position of the Sun (a true solar sundial clock).
It incorporates:
1. Observer longitudinal displacement: `Δλ × 4 min/deg` from the Prime Meridian.
2. The **Equation of Time (EoT)**: accounting for Earth's orbital eccentricity and axial tilt (≈ -14 to +16 minutes variance across the year).
At the exact moment of solar noon, `solarTime` aligns to `12:00:00.000`.
```typescript
const t = new Tempo('2026-06-21T12:00:00Z', { geo: { lat: 40.7128, lng: -74.006 } });
// Query apparent solar time at current moment
const ast = t.term.solar.solarTime;
console.log(ast.format('{hh}:{mi}:{ss}')); // Local solar clock time
// At exact solar noon:
const atNoon = new Tempo(t.term.solar.noon.epoch.ms, { geo: { lat: 40.7128, lng: -74.006 } });
console.log(atNoon.term.solar.solarTime.format('{hh}:{mi}:{ss}')); // "12:00:00"
```
---
## 4. Atmospheric Elevation Dip Correction (`elevation`) {#elevation-dip}
Observers at higher elevations experience an expanded visible horizon due to geometric horizon dip:
```
dip ≈ 0.0347° × √(elevation_meters)
```
Passing `elevation` (in meters) automatically adjusts `sunrise`, `sunset`, and twilight timestamps:
```typescript
// Denver observer at 1,600 meters elevation
const denver = new Tempo('2026-06-21T12:00:00Z', {
geo: { lat: 39.7392, lng: -104.9903, elevation: 1600 }
});
console.log(denver.term.solar.elevation); // 1600
console.log(denver.term.solar.daylightDurationMs); // Longer daylight duration than sea level
```
---
## 5. Real-Time Solar Coordinates & Photometric Hours {#solar-coordinates}
When geographic coordinates are present, `SolarTerm` exposes topocentric horizontal coordinates and photography lighting metrics:
| Property | Type | Description |
| :--- | :--- | :--- |
| `altitude` | `number \| null` | Topocentric solar elevation angle in degrees above (+) or below (-) horizon (-90°..+90°). |
| `azimuth` | `number \| null` | Solar compass bearing in degrees (0°..360°, where 0° = North, 90° = East, 180° = South, 270° = West). |
| `zenith` | `number \| null` | Angular distance in degrees from the overhead zenith (`90° - altitude`). |
| `isGoldenHour` | `boolean \| null` | True when solar altitude is between -4° and +6° (warm, diffused sunlight). |
| `isBlueHour` | `boolean \| null` | True when solar altitude is between -6° and -4° (deep blue twilight sky). |
| `shadowRatio` | `number \| null` | Vertical object shadow length multiplier (`cot(altitude)`), or `null` when Sun is below the horizon. |
```typescript
const sydney = new Tempo('2026-12-21T02:00:00Z', {
geo: { lat: -33.8688, lng: 151.2093 }
});
console.log(sydney.term.solar.altitude); // e.g. 78.5°
console.log(sydney.term.solar.azimuth); // Compass bearing in degrees
console.log(sydney.term.solar.shadowRatio); // Object shadow multiplier
console.log(sydney.term.solar.isGoldenHour); // false
console.log(sydney.term.solar.isBlueHour); // false
```
---
## 6. Polar Regions Handling (Midnight Sun & Polar Night) {#polar-regions}
In high-latitude regions (|lat| > 66.5°), the Sun may remain continuously above or below the horizon for extended periods:
- **`isMidnightSun`**: `true` on dates when the Sun remains continuously above the visible horizon for 24 hours. `sunrise` and `sunset` evaluate to `null`, `daylightDurationMs` is 86,400,000 ms, and `key` remains `'daylight'`.
- **`isPolarNight`**: `true` on dates when the Sun does not rise above the visible horizon. `sunrise` and `sunset` evaluate to `null`, `daylightDurationMs` is 0 ms, and `key` transitions between twilight states (such as `'civil-twilight'` at midday) and total `'night'`.
```typescript
// Tromsø, Norway (69.65° N) on Summer Solstice
const midnightSun = new Tempo('2026-06-21T12:00:00Z', {
geo: { lat: 69.6492, lng: 18.9553 }
});
console.log(midnightSun.term.solar.isMidnightSun); // true
console.log(midnightSun.term.solar.sunrise); // null
console.log(midnightSun.term.solar.isDaylight); // true
// Tromsø, Norway on Winter Solstice
const polarNight = new Tempo('2026-12-21T12:00:00Z', {
geo: { lat: 69.6492, lng: 18.9553 }
});
console.log(polarNight.term.solar.isPolarNight); // true
console.log(polarNight.term.solar.key); // 'civil-twilight' at midday
```
---
## 7. Twilight Range Boundaries {#twilight-windows}
`t.term.solar.civil`, `t.term.solar.nautical`, and `t.term.solar.astronomical` provide sub-objects with `sunrise` and `sunset` `Tempo` instances for each twilight band:
```typescript
const { civil, nautical, astronomical } = t.term.solar;
console.log(civil.sunrise?.format('{hh}:{mi}')); // Civil dawn
console.log(civil.sunset?.format('{hh}:{mi}')); // Civil dusk
```
---
# Document: 9-plugins/celestial.tidal.md
# Astronomical Tidal Mechanics & Coastal Predictions
This guide explores astronomical tidal state classification, syzygy and quadrature alignment, perigee factors, King Tide indicators, local coastal tide predictions, and lunitidal port calibration in `@tempo-kit/plugin-celestial`.
---
## 1. Deterministic Astronomical Calculations {#astronomical-calculations}
Tidal state resolution in `TidalTerm` (`t.term.tide`, `t.term.tides`) relies purely on deterministic celestial mechanics:
- **Ecliptic Longitude Delta (Δλ)**: The angular separation between the Sun and the Moon.
- **Anomalistic Month Perigee Proximity**: The Moon's orbital distance from Earth along its elliptical orbit (perigee vs. apogee).
- **Meridian Transit Geometry**: Lunar upper and lower culminations relative to observer longitude.
---
## 2. Tidal States (`t.term.tide` / `t.term.tides.state`) {#tidal-states}
| Tidal State | Astronomical Mechanism | Impact on Water Levels |
| :--- | :--- | :--- |
| `'spring'` | **Syzygy** (Δλ ≈ 0° New Moon or 180° Full Moon). Gravitational forces of Sun and Moon constructively reinforce. | Maximum tidal range (highest high tides, lowest low tides). |
| `'neap'` | **Quadrature** (Δλ ≈ 90° First Quarter or 270° Third Quarter). Gravitational forces act orthogonally. | Minimum tidal range (moderate high tides, moderate low tides). |
| `'normal'` | Intermediate orbital positions between syzygy and quadrature. | Standard daily tidal fluctuations. |
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
const t = new Tempo('2026-03-03T12:00:00Z', {
geo: { lat: -33.8688, lng: 151.2093 }
});
console.log(t.term.tide); // 'spring', 'neap', or 'normal'
console.log(t.term.tides.keys); // ['spring', 'neap', 'normal']
console.log(t.term.tides.alignmentDeg); // Angular separation (0..360°)
console.log(t.term.tides.isSpringTide); // true during New or Full Moon
console.log(t.term.tides.isNeapTide); // true during 1st or 3rd Quarter
```
---
## 3. King Tides & Perigee Factor (`isKingTide` / `perigeeFactor`) {#king-tides}
A **King Tide** (Perigean Spring Tide) occurs when a Spring Tide (New or Full Moon) coincides with the Moon at or near its closest orbital approach to Earth (**Perigee**).
- **`perigeeFactor`**: Normalized metric from 0.0 (Apogee, farthest) to 1.0 (Perigee, closest).
- **`isKingTide`**: Evaluates to `true` when `isSpringTide === true` and `perigeeFactor >= 0.75`.
```typescript
if (t.term.tides.isKingTide) {
console.warn('King Tide Warning: Expect exceptionally high astronomical tides!');
console.log('Perigee Proximity Factor:', t.term.tides.perigeeFactor);
}
```
---
## 4. Local Coastal Tide Predictions & Port Calibration {#coastal-predictions}
When observer coordinates are supplied, `TidalTerm` calculates the upcoming local high and low tides based on lunar meridian transits and local hydrodynamic port lag (lunitidal interval):
| Property | Type | Description |
| :--- | :--- | :--- |
| `nextHighTide` | `Tempo \| null` | `Tempo` instance for the estimated local high tide anchored to observer coordinates. |
| `nextLowTide` | `Tempo \| null` | `Tempo` instance for the estimated local low tide. |
| `lunitidalIntervalMin` | `number \| null` | Port-specific hydrodynamic phase lag offset in minutes. |
| `regime` | `'semi-diurnal' \| 'diurnal' \| 'mixed' \| null` | Tidal cycle pattern for the region. |
```typescript
const sydney = new Tempo('2026-03-03T12:00:00Z', {
geo: { lat: -33.8688, lng: 151.2093 }
});
console.log(sydney.term.tides.nextHighTide?.iso); // e.g. "2026-03-03T15:24:10.000Z"
console.log(sydney.term.tides.nextLowTide?.iso); // e.g. "2026-03-03T21:36:46.000Z"
console.log(sydney.term.tides.regime); // 'semi-diurnal'
// Custom Port Calibration (e.g. 110-minute port lag)
const portCalibrated = new Tempo('2026-03-03T12:00:00Z', {
geo: { lat: -33.8688, lng: 151.2093, lunitidalIntervalMin: 110 }
});
console.log(portCalibrated.term.tides.lunitidalIntervalMin); // 110
```
---
## 5. Lunar Tidal Cycle Minutes (`lunarTideMinute`) {#lunar-tidal-cycle}
When geographic coordinates are supplied, `t.term.tides.lunarTideMinute` reports the current minute within the 745.2-minute semi-diurnal lunar tidal cycle (≈ 12 hours 25.2 minutes between successive lunar culminations).
---
# Document: 9-plugins/celestial.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
Civil clock time is an artificial human construct based on standardized 15° meridian bands. Physical systems on Earth—such as photovoltaic solar generators, agricultural crop lighting, maritime coastal navigation, and astronomical observations—are governed strictly by planetary physics:
1. **Solar Position**: True apparent solar noon, solar azimuth, elevation angles, and twilight boundaries.
2. **Lunar Mechanics**: Illumination fractions, moonrise/moonset events, topocentric distance, and supermoons.
3. **Gravitational Tides**: Semi-diurnal high/low water, spring/neap tide cycles, and perigean king tides.
The `@tempo-kit/plugin-celestial` plugin provides 100% offline, zero-network mathematical ephemeris calculations directly integrated with Tempo instances.
---
## 1. Photovoltaic (PV) Solar Inverter & Battery Storage Orchestration
In industrial microgrids and commercial battery energy storage systems (BESS), fixed-angle and single-axis solar arrays produce power as a function of the sun's altitude angle above the physical horizon.
Rather than relying on static clock intervals (e.g. 12:00 PM), control systems query true solar elevation and apparent solar noon to dynamically switch inverter modes between grid-export, self-consumption, and battery absorption:
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
export function evaluateInverterMode(
currentTime: string,
facilityCoordinates: { latitude: number; longitude: number }
): { mode: 'PEAK_EXPORT' | 'CHARGING' | 'STANDBY'; solarElevationDeg: number } {
const t = new Tempo(currentTime, { geo: facilityCoordinates });
const solar = t.term.solar;
const altitude = solar.altitude ?? 0;
// Peak irradiance window: solar altitude > 45°
if (altitude > 45) {
return { mode: 'PEAK_EXPORT', solarElevationDeg: Math.round(altitude) };
}
// Active generating daylight: solar altitude > 10°
if (altitude > 10) {
return { mode: 'CHARGING', solarElevationDeg: Math.round(altitude) };
}
// Low sun or night: standby mode
return { mode: 'STANDBY', solarElevationDeg: Math.round(altitude) };
}
```
---
## 2. Smart Agriculture & Greenhouse Supplemental Lighting
Commercial greenhouse automation systems target a precise **Daily Light Integral (DLI)**—the total volume of photosynthetically active radiation (PAR) received by crops each day. Supplemental LED grow lights should only illuminate when natural daylight dips below target thresholds or during specific twilight windows.
Using `t.term.solar`, environmental control engines automatically schedule lighting around exact civil twilight and golden hour boundaries:
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
export function getGreenhouseLightingPlan(
farmLat: number,
farmLng: number,
targetDate: string
) {
const noon = new Tempo(`${targetDate} 12:00:00`, {
geo: { latitude: farmLat, longitude: farmLng }
});
const solar = noon.term.solar;
return {
date: targetDate,
totalDaylightHours: ((solar.daylightDurationMs ?? 0) / 3_600_000).toFixed(1),
morningLightsOff: solar.civil.sunrise?.format('{hh}:{mi}'),
eveningLightsOn: solar.goldenHour?.start?.format('{hh}:{mi}') ?? solar.sunset?.format('{hh}:{mi}'),
nightModeAt: solar.civil.sunset?.format('{hh}:{mi}')
};
}
```
---
## 3. Maritime Shipping & Coastal Keel Clearance Windows
Deep-draft container ships and bulk cargo vessels entering shallow ports, river estuaries, or tidal locks must plan arrival times around **High Water (HW)** to ensure safe Under-Keel Clearance (UKC).
`t.term.tides` resolves tidal states, spring/neap alignment, and predicted high-tide windows from observer coordinates and port lunitidal intervals:
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
export function checkPortKeelClearance(
estimatedArrival: string,
port: { latitude: number; longitude: number; lunitidalIntervalMin: number; name: string }
) {
const arrival = new Tempo(estimatedArrival, { geo: port });
const tides = arrival.term.tides;
return {
port: port.name,
arrivalIso: arrival.format('{yyyy}-{mm}-{dd} {hh}:{mi}'),
tideState: tides.state, // 'high' | 'low' | 'flood' | 'ebb' | 'normal'
isSpringTide: tides.isSpringTide, // Maximum tidal amplitude
isKingTide: tides.isKingTide, // Perigean syzygy high water
nextHighTide: tides.nextHighTide?.format('{yyyy}-{mm}-{dd} {hh}:{mi}')
};
}
// Example: Vessel arriving near Hamburg Port (Elbe estuary)
const transit = checkPortKeelClearance('2026-09-15 14:00:00', {
name: 'Port of Hamburg',
latitude: 53.5511,
longitude: 9.9937,
lunitidalIntervalMin: 320
});
console.log(transit.nextHighTide); // '2026-09-15 17:26'
```
---
## 4. Drone Surveying & Architectural Golden Hour Scheduling
Aerial drone photogrammetry and architectural cinematography require planning flights during either the **Golden Hour** (soft, warm shadows when solar altitude is between -4° and 6°) or the **Blue Hour** (deep diffused blue hues during nautical twilight).
Rather than querying external weather websites, video production applications can calculate these windows for any GPS coordinate across the globe:
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
export function isOptimalShootingCondition(
timestamp: string,
latitude: number,
longitude: number
): { isGoldenHour: boolean; isBlueHour: boolean; sunAltitude: number } {
const flightTime = new Tempo(timestamp, { geo: { latitude, longitude } });
const solar = flightTime.term.solar;
return {
isGoldenHour: solar.isGoldenHour ?? false,
isBlueHour: solar.isBlueHour ?? false,
sunAltitude: Math.round(solar.altitude ?? 0)
};
}
```
---
## 5. Wildlife Tracking & Nocturnal Ecological Monitoring
Marine biologists and ecological field teams studying nocturnal wildlife behavior (such as sea turtle nesting, coral spawning, or bat emergence) schedule observation shifts based on the lunar cycle and moonlight illumination levels.
Using `t.term.lunar`, research software calculates illumination fractions, lunar phases, and moonrise/moonset without needing an internet connection:
```typescript
import { Tempo } from 'tempo-kit';
import { CelestialPlugin } from '@tempo-kit/plugin-celestial';
Tempo.use(CelestialPlugin);
export function getNightSurveyContext(dateIso: string, lat: number, lng: number) {
const surveyTime = new Tempo(`${dateIso} 22:00:00`, {
geo: { latitude: lat, longitude: lng }
});
const lunar = surveyTime.term.lunar;
return {
date: dateIso,
moonPhase: lunar.phase, // e.g. 'First Quarter'
illuminationPct: Math.round(lunar.illumination * 100), // e.g. 34%
isWaxing: lunar.isWaxing,
isSupermoon: lunar.isSupermoon ?? false,
moonrise: lunar.moonrise?.format('{hh}:{mi}') ?? 'None'
};
}
```
---
# Document: 9-plugins/cultural.cycles-and-traditions.md
# Astronomical, Liturgical & Traditional Cycles
`@tempo-kit/plugin-cultural` includes four standalone, zero-dependency Terms for traditional solar, ecclesiastical, seasonal rent-day, and demographic cycles.
---
## East Asian 24 Solar Terms (`JieqiTerm`)
- **Subpath**: `@tempo-kit/plugin-cultural/jieqi`
- **Keys & Aliases**: `t.term.jieqi`, `t.term.sekki` (shorthand key) · `t.term.solarTerm` (full `JieqiScope`)
- **Static Discovery**: `JIEQI_KEYS` (frozen 24-entry array from `'Chunfen'` `0°` through `'Jingzhe'` `345°`)
- **Calculation**: Self-contained Meeus Ch. 25 apparent ecliptic solar longitude solver (`15°` steps, `~0.01°` / ~10-minute transit accuracy) with zero coupling to `@tempo-kit/plugin-celestial`.
```typescript
import { Tempo } from 'tempo-kit';
import { JieqiTerm } from '@tempo-kit/plugin-cultural/jieqi';
Tempo.use(JieqiTerm);
const t = new Tempo('2026-04-06T00:00:00Z');
console.log(t.term.jieqi); // 'Qingming'
console.log(t.term.solarTerm.longitude); // 15
console.log(t.term.solarTerm.english); // 'Clear and Bright'
console.log(t.term.solarTerm.variants.cn.name); // '清明'
console.log(t.term.solarTerm.variants.jp.romanized); // 'Seimei'
console.log(t.term.solarTerm.variants.vn.name); // 'Thanh minh'
```
---
## Western Christian Liturgical Year (`LiturgicalTerm`)
- **Subpath**: `@tempo-kit/plugin-cultural/liturgical`
- **Keys & Aliases**: `t.term.liturgy`, `t.term.ecclesiastical` (shorthand key) · `t.term.liturgical` (full `LiturgicalScope`)
- **Static Discovery**: `LITURGICAL_KEYS` (`Advent`, `Christmastide`, `Epiphany`, `Ordinary Time`, `Lent`, `Triduum`, `Eastertide`, `Pentecost`)
- **Calculation**: Anonymous Gregorian Computus for Easter Sunday, Advent Sunday (4th Sunday before Dec 25), traditional liturgical color (`'purple' | 'white' | 'green' | 'red'`), and 3-year Sunday lectionary cycle (`'A' | 'B' | 'C'`, rolling over on Advent Sunday).
```typescript
import { Tempo } from 'tempo-kit';
import { LiturgicalTerm } from '@tempo-kit/plugin-cultural/liturgical';
Tempo.use(LiturgicalTerm);
const easter = new Tempo('2026-04-05T12:00:00Z');
console.log(easter.term.liturgy); // 'Eastertide'
console.log(easter.term.liturgical.color); // 'white'
console.log(easter.term.liturgical.liturgicalYear); // 'A'
console.log(easter.format('{#liturgy} (Year {#liturgy.liturgicalYear})')); // 'Eastertide (Year A)'
```
---
## Traditional Quarter & Cross-Quarter Days (`QuarterDaysTerm`)
- **Subpath**: `@tempo-kit/plugin-cultural/quarter-days`
- **Keys & Aliases**: `t.term.qday`, `t.term.crossQuarter` (shorthand key) · `t.term.quarterDay` (full `QuarterDayScope`)
- **Traditions**:
- `'english'` *(default)*: *Lady Day* (`Mar 25`), *Midsummer* (`Jun 24`), *Michaelmas* (`Sep 29`), *Christmas* (`Dec 25`)
- `'scottish'`: *Candlemas* (`Feb 2`), *Whitsunday* (`May 15`), *Lammas* (`Aug 1`), *Martinmas* (`Nov 11`)
- `'celtic'`: *Imbolc* (`Feb 1`), *Beltane* (`May 1`), *Lughnasadh* (`Aug 1`), *Samhain* (`Nov 1`)
Models **contiguous periods** between quarter days so `.span.remaining` and `.span.progress` report exact time until the next quarter/rent day.
```typescript
import { Tempo } from 'tempo-kit';
import { QuarterDaysTerm, createQuarterDaysTerm } from '@tempo-kit/plugin-cultural/quarter-days';
Tempo.use(QuarterDaysTerm);
const t = new Tempo('2026-07-01T12:00:00Z');
console.log(t.term.qday); // 'Midsummer'
console.log(t.term.quarterDay.dateLabel); // 'Jun 24'
// Per-instance tradition override:
const celtic = new Tempo('2026-05-10T12:00:00Z', {
pluginOptions: { quarterDays: { tradition: 'celtic' } },
});
console.log(celtic.term.qday); // 'Beltane'
// Or configure a custom default globally:
// Tempo.use(createQuarterDaysTerm({ tradition: 'scottish' }));
```
---
## Demographic Generations (`GenerationTerm`)
- **Subpath**: `@tempo-kit/plugin-cultural/generation`
- **Keys & Aliases**: `t.term.gen` (shorthand key) · `t.term.generation` (full `GenerationScope`)
- **Static Discovery**: `GENERATION_KEYS` (`Greatest`, `Silent`, `Baby Boomer`, `Gen X`, `Millennial`, `Gen Z`, `Gen Alpha`, `Gen Beta`)
- **Open-Ended Spans**: Historical cohorts return a closed `TermSpan`; the latest open-ended cohort (`Gen Beta`, `2025–null`) returns an `OpenTermSpan` with `end: null`, `total: null`, `remaining: null`, `progress: null`, and live `start` / `elapsed`.
```typescript
import { Tempo } from 'tempo-kit';
import { GenerationTerm, createGenerationTerm } from '@tempo-kit/plugin-cultural/generation';
Tempo.use(GenerationTerm);
console.log(new Tempo('1990-06-01T00:00:00Z').term.gen); // 'Millennial'
const beta = new Tempo('2026-06-01T00:00:00Z').term.generation;
console.log(beta.key, beta.endYear, beta.span.end); // 'Gen Beta' null null
```
---
# Document: 9-plugins/cultural.index.md

# @tempo-kit/plugin-cultural
The **Cultural Plugin** provides traditional, historical, and lunisolar calendar Terms for [Tempo](https://github.com/magmacomputing/magma/tree/main/packages/tempo) — combining Western & East Asian zodiacs with `Temporal`-native Japanese Imperial Eras, Islamic Hijri, and Hebrew calendars.
---
## Key Features
- **`ZodiacTerm`** (`#zdc`, `#zodiac`, `#sunSign`, `#starSign`) — Western Tropical Zodiac signs with symbols, emojis, traits, shorthand navigation, ordinals, and formatting.
- **`EasternTerm`** (`#sign`, `#shengxiao`, `#lunarSign`, `#eastern`) — East Asian Sexagenary Zodiac cycle with 5 elements, Yin/Yang polarity, and regional variants (`cn`, `jp`, `kr`, `vn`).
- **`NengoTerm`** (`#nengo`, `#era`, `#wareki`) — Japanese Imperial Eras (*Meiji*, *Taishō*, *Shōwa*, *Heisei*, *Reiwa*) powered by `Temporal`'s `'japanese'` calendar with kanji, ASCII codes (`R8`), `元年` formatting, and open-ended `OpenTermSpan` (`end: null`) for the active *Reiwa* era.
- **`HijriTerm`** (`#hijri`, `#islamic`, `#islamicMonth`) — Islamic Hijri months powered by `Temporal` (`'islamic-umalqura'`, `'islamic-civil'`, `'islamic-tbla'`) with Arabic script, sacred-month flags, and exact month spans.
- **`HebrewTerm`** (`#hebrew`, `#hebrewMonth`) — Hebrew lunisolar months powered by `Temporal`'s `'hebrew'` calendar with Hebrew script, automatic Metonic leap-year `Adar I` / `Adar II` resolution, and exact month spans.
- **`JieqiTerm`** (`#jieqi`, `#sekki`, `#solarTerm`) — East Asian 24 Solar Terms computed via a self-contained Meeus solar longitude solver with `cn` / `jp` / `kr` / `vn` variants.
- **`LiturgicalTerm`** (`#liturgy`, `#ecclesiastical`, `#liturgical`) — Western Christian Liturgical seasons via Gregorian Computus with liturgical colors and 3-year Sunday lectionary cycle (`A` / `B` / `C`).
- **`QuarterDaysTerm`** (`#qday`, `#crossQuarter`, `#quarterDay`) — Contiguous English, Scottish, and Celtic quarter/cross-quarter day periods.
- **`GenerationTerm`** (`#gen`, `#generation`) — Pew Research demographic cohorts (or custom ranges) with open-ended `OpenTermSpan` for the active cohort.
- **`createCalendarTerm`** (`@tempo-kit/plugin-cultural/calendar`) — Generic zero-table factory unlocking any `Temporal` calendar on demand without crowding `t.term.*`.
- **Opt-In Global Calendar Terms** (subpath imports, keeping `CulturalPlugin` lean):
- **`PersianTerm`** (`@tempo-kit/plugin-cultural/persian`, `#persian`, `#jalali`, `#shamsi`) — Solar Hijri calendar with Persian script and seasonal alignment.
- **`IndianTerm`** (`@tempo-kit/plugin-cultural/indian`, `#indian`, `#saka`) — Indian National (Saka) civil calendar with Devanagari script.
- **`EthiopianTerm` & `CopticTerm`** (`.../ethiopian`, `.../coptic`) — 13-month calendars with Ge'ez / Coptic script and epagomenal month flags.
- **`BuddhistTerm`** (`@tempo-kit/plugin-cultural/buddhist`, `#buddhist`, `#thai`) — Thai Solar Buddhist Era (`year + 543`) with Thai month names and abbreviations.
- **`ChineseLunarTerm`** (`@tempo-kit/plugin-cultural/chinese-lunar`, `#nongli`, `#chineseMonth`, `#chineseLunar`) — Chinese (`'chinese'`) and Korean (`'dangi'`) lunisolar months with intercalary leap months (`M01L`–`M12L`) and 60-year Sexagenary `ganzhi` stems & branches.
- **Granular Tree-Shakeable Subpaths**: Import the full `CulturalPlugin` bundle or individual terms via `@tempo-kit/plugin-cultural/{zodiac,eastern,nengo,hijri,hebrew,jieqi,liturgical,quarter-days,generation,calendar,persian,indian,ethiopian,coptic,buddhist,chinese-lunar}`.
> [!NOTE]
> `EasternTerm` defaults to **Gregorian year boundaries** (`{yyyy}-01-01` → next year's `01-01`). For exact Chinese New Year transitions, register `createEasternTerm({ boundary: 'lunisolar' })`.
---
## Installation
```bash
npm install tempo-kit @tempo-kit/plugin-cultural
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { CulturalPlugin } from '@tempo-kit/plugin-cultural';
Tempo.use(CulturalPlugin);
const t = new Tempo('2026-04-05T12:00:00Z');
console.log(t.term.zdc); // 'Aries'
console.log(t.term.zodiac.emoji); // '♈'
console.log(t.term.sign); // 'Horse'
console.log(t.term.shengxiao.element); // 'Fire'
console.log(t.term.era.formatted); // '令和8年'
console.log(t.term.hijri); // 'Shawwal'
console.log(t.term.hebrew); // 'Nisan'
```
### Granular Term Imports
```typescript
import { Tempo } from 'tempo-kit/core';
import { NengoTerm } from '@tempo-kit/plugin-cultural/nengo';
import { HijriTerm, createHijriTerm } from '@tempo-kit/plugin-cultural/hijri';
import { HebrewTerm } from '@tempo-kit/plugin-cultural/hebrew';
Tempo.use([NengoTerm, HijriTerm, HebrewTerm]);
// Or configure an alternate Islamic calendar variant:
// Tempo.use(createHijriTerm({ calendar: 'islamic-civil' }));
```
### Side-Effect Auto-Registration
```typescript
import '@tempo-kit/plugin-cultural/install';
```
### Open-Ended Spans (`OpenTermSpan`)
Active or unbounded eras (such as *Reiwa* in `NengoTerm`) use `null` for unbounded endpoints, mirroring `Tempo.Interval`:
- **Open end (`end: null`)**: `total`, `remaining`, and `progress` are `null`, while `start` and `elapsed` remain live.
- **Open start (`start: null`)**: `total`, `elapsed`, and `progress` are `null`, while `end` and `remaining` remain live.
- **Closed historical eras**: Return a full closed `TermSpan`.
---
## Topic Guides
Explore detailed guides on each calendar system and production integration patterns:
- **[Western & Eastern Zodiac Terms](./cultural.zodiac-and-eastern.md)**: `ZodiacTerm` signs & navigation, `EasternTerm` 60-year sexagenary cycle, regional variants (`cn`/`jp`/`kr`/`vn`), and Gregorian year boundaries.
- **[Temporal-Native Calendars (Nengō, Hijri & Hebrew)](./cultural.temporal-calendars.md)**: Japanese Imperial Eras (`NengoTerm` & `OpenTermSpan`), Islamic Hijri variants (`HijriTerm`), and Hebrew Metonic leap-year months (`HebrewTerm`).
- **[Astronomical, Liturgical & Traditional Cycles](./cultural.cycles-and-traditions.md)**: 24 Solar Terms (`JieqiTerm`), Western Liturgical seasons (`LiturgicalTerm`), English/Scottish/Celtic Quarter Days (`QuarterDaysTerm`), and demographic cohorts (`GenerationTerm`).
- **[Use Cases & Production Patterns](./cultural.use-cases-and-patterns.md)**: Regional zodiac localization, Wareki document stamping, Ramadan campaign tracking, Hebrew leap-year scheduling, and seasonal/liturgical cycle recipes.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/cultural.temporal-calendars.md
# Use Cases & Production Patterns
`@tempo-kit/plugin-cultural` decouples cultural and traditional calendar Terms from `tempo-kit`'s core bundle while providing full Tempo Term capabilities (shorthand navigation, ordinals, formatting tokens, and `.span` progress metrics).
---
## 1. Localized East Asian Zodiac Badges (`cn` / `jp` / `kr` / `vn`)
### The Challenge
East Asian New Year campaigns and localization pipelines share the 12-year zodiac animal cycle (paired with the 5 elements in the 60-year sexagenary cycle), but regional audiences expect localized animal names and characters—such as **Cat (`Mão / Mèo`)** instead of **Rabbit** in Vietnam, **Sheep** instead of **Goat** in Japan/Korea, and **Wild Boar** instead of **Pig** in Japan.
> [!NOTE]
> `EasternTerm` derives its animal, element, and `.span` boundaries (`{yyyy}-01-01` → next year's `01-01`) from the **Gregorian calendar year** (`t.yy`), not the lunisolar New Year boundary. Dates in January or early February prior to Lunar New Year will resolve to that Gregorian year's sign.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { EasternTerm } from '@tempo-kit/plugin-cultural/eastern';
Tempo.use(EasternTerm);
const jpDate = new Tempo('2019-06-01', { locale: 'ja-JP' });
console.log(jpDate.term.sign); // 'Wild Boar'
console.log(jpDate.term.shengxiao.emoji); // '🐗'
console.log(jpDate.term.shengxiao.variants.jp); // { animal: 'Wild Boar', emoji: '🐗', character: '亥', romanized: 'Inoshishi' }
const vnDate = new Tempo('2023-06-01', { locale: 'vi-VN' });
console.log(vnDate.term.sign); // 'Cat'
console.log(vnDate.term.shengxiao.variants.vn); // { animal: 'Cat', emoji: '🐈', character: 'Mão / Mèo' }
```
---
## 2. Western Tropical Zodiac Navigation & Formatting
### The Challenge
Lifestyle, editorial, and social platforms often need to compute sign transitions, render formatted badges, or jump to the start of an astrological window without hardcoding month/day lookup tables.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { ZodiacTerm } from '@tempo-kit/plugin-cultural/zodiac';
Tempo.use(ZodiacTerm);
const t = new Tempo('2026-04-05');
console.log(t.format('{#zdc.emoji} {#zdc} ({#zdc.symbol})')); // '♈ Aries (Ram)'
console.log(t.term.zodiac.span.start.format('{yyyy}-{mm}-{dd}')); // '2026-03-21'
// Jump to the next sign boundary
const nextTaurus = t.set('#zdc.>taurus');
console.log(nextTaurus.format('{yyyy}-{mm}-{dd}')); // '2026-04-20'
```
---
## 3. Japanese Wareki Document & Invoice Stamping (`NengoTerm`)
### The Challenge
Japanese government filings, receipts, and legal contracts require Imperial Era (*Wareki*) dates (e.g. `令和8年5月15日` or compact `R8.05.15`), including `元年` for year 1 of an era, while safely distinguishing closed historical eras from the open-ended active *Reiwa* era.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { NengoTerm } from '@tempo-kit/plugin-cultural/nengo';
Tempo.use(NengoTerm);
function formatWarekiInvoiceDate(t: Tempo): string {
const { formatted, span } = t.term.era;
const status = span.end === null
? 'current era'
: `ended ${span.end.subtract({ days: 1 }).format('{yyyy}-{mm}-{dd}')}`;
return `${formatted}${t.mm}月${t.dd}日 (${status})`;
}
const invoice = new Tempo('2026-05-15T12:00:00', { timeZone: 'Asia/Tokyo' });
console.log(formatWarekiInvoiceDate(invoice));
// '令和8年5月15日 (current era)'
const historical = new Tempo('2019-04-30T12:00:00', { timeZone: 'Asia/Tokyo' });
console.log(formatWarekiInvoiceDate(historical));
// '平成31年4月30日 (ended 2019-04-30)'
```
---
## 4. Ramadan & Hijri Campaign Window Tracking (`HijriTerm`)
### The Challenge
Regional e-commerce, fintech, and hospitality platforms in MENA and Southeast Asia adjust promotions, operating hours, and support SLAs during *Ramadan* and the four sacred months—requiring accurate month boundaries and remaining-time indicators without maintaining manual yearly lookup tables.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { HijriTerm } from '@tempo-kit/plugin-cultural/hijri';
Tempo.use(HijriTerm);
const now = new Tempo('2026-03-01T12:00:00Z');
const { key, year, day, arabic, isSacred, span } = now.term.islamic;
if (key === 'Ramadan') {
console.log(`Day ${day} of ${key} ${year} (${arabic})`);
// 'Day 12 of Ramadan 1447 (رمضان)'
console.log(`Window: ${span.start.format('{yyyy}-{mm}-{dd}')} → ${span.end.format('{yyyy}-{mm}-{dd}')}`);
// 'Window: 2026-02-18 → 2026-03-20'
console.log(`Progress: ${Math.round(span.progress * 100)}%`);
// 'Progress: 38%'
}
console.log('Sacred month?', isSacred); // false
```
---
## 5. Hebrew Leap-Year Event & Calendar Scheduling (`HebrewTerm`)
### The Challenge
Community portals, kosher-certification trackers, and Jewish holiday calendars must distinguish *Adar I* (`M05L`) from *Adar II* (`M06`) in 13-month Metonic leap years (e.g. `5784`), where Purim and annual memorials fall in *Adar II* rather than *Adar I*.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { HebrewTerm } from '@tempo-kit/plugin-cultural/hebrew';
Tempo.use(HebrewTerm);
function describeAdar(t: Tempo): string {
const { key, year, isLeapYear, hebrew } = t.term.hebrewMonth;
return `${key} ${year} (${hebrew}) — ${isLeapYear ? '13-month leap year' : '12-month common year'}`;
}
console.log(describeAdar(new Tempo('2024-02-15T12:00:00Z')));
// 'Adar I 5784 (אדר א׳) — 13-month leap year'
console.log(describeAdar(new Tempo('2024-03-15T12:00:00Z')));
// 'Adar II 5784 (אדר ב׳) — 13-month leap year'
console.log(describeAdar(new Tempo('2025-03-05T12:00:00Z')));
// 'Adar 5785 (אדר) — 12-month common year'
```
---
## 6. East Asian Solar Terms, Liturgical Theming & Rent Quarter Days
### The Challenge
Seasonal retail, agricultural schedules, church/parish portals, UK/Scottish property lease engines, and demographic analytics each rely on domain-specific calendar boundaries that shift annually or follow historical legal conventions.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { JieqiTerm } from '@tempo-kit/plugin-cultural/jieqi';
import { LiturgicalTerm } from '@tempo-kit/plugin-cultural/liturgical';
import { QuarterDaysTerm } from '@tempo-kit/plugin-cultural/quarter-days';
import { GenerationTerm } from '@tempo-kit/plugin-cultural/generation';
Tempo.use([JieqiTerm, LiturgicalTerm, QuarterDaysTerm, GenerationTerm]);
const t = new Tempo('2026-04-05T12:00:00Z');
// 24 Solar Terms (Qingming festival window)
console.log(t.term.jieqi, t.term.solarTerm.variants.cn.name); // 'Qingming 清明'
// Liturgical UI accent color & Sunday lectionary cycle
console.log(t.term.liturgy, t.term.liturgical.color, t.term.liturgical.liturgicalYear);
// 'Eastertide white A'
// English rent quarter-day window (Lady Day Mar 25 -> Midsummer Jun 24)
console.log(t.term.qday, t.term.quarterDay.span.end.format('{yyyy}-{mm}-{dd}'));
// 'Lady Day 2026-06-24'
// Demographic cohort segmentation
console.log(new Tempo('1990-06-01T00:00:00Z').term.gen); // 'Millennial'
console.log(t.term.gen, t.term.generation.span.end); // 'Gen Beta' null
```
---
# Document: 9-plugins/cultural.zodiac-and-eastern.md
# Design Strategy & Deliberate Omissions
Why Tempo Chose `{token:modifier}` Over Historical Dialects
The `@tempo-kit/plugin-dialects` plugin exists to provide complete interoperability and zero-downtime migration paths for codebases written in **Moment.js**, **Day.js**, **Luxon**, **date-fns**, **POSIX `strftime`**, **PHP**, and **SQL `TO_CHAR`**.
However, when engineering Tempo's native formatting engine, we deliberately chose **not** to adopt any single historical token system. Decades of formatting history have accumulated conflicting token semantics, capitalization traps, and combinatorial token explosions that frequently cause catastrophic production bugs.
This document outlines the architectural principles behind Tempo's `{token:modifier}` syntax and explains the specific dialect features we deliberately chose to omit.
---
## 🏛️ Part A: The Token:Modifier Design Strategy
Tempo's format syntax is founded on four core principles:
### 1. The All-Lowercase Principle: Eliminating the Capitalization Trap
In historical dialects, a single shift-key difference changes the entire semantic target of a format string. This is the single largest source of date-formatting bugs in modern software:
* **Month vs. Minute (`MM` vs `mm`)**: In Moment, LDML, and SQL, `MM` is month and `mm` is minute. An accidental typo like `HH:MM:ss` silently formats the month where minutes should appear.
* **The New Year Billing Catastrophe (`YYYY` vs `yyyy`)**: In Unicode LDML specifications, `yyyy` represents the standard calendar year, while `YYYY` represents a **week-numbering year**. Implementations diverge significantly: Luxon uses `kkkk` for the ISO week-numbering year, while date-fns throws an error on `YYYY` by default unless its `useAdditionalWeekYearTokens` option is explicitly enabled. Under ISO week rules, an erroneous format mask using a week-numbering year like `YYYY-MM-dd` outputs `2026-12-31` on December 31, 2025 because that day belongs to Week 1 of 2026. This subtle discrepancy has repeatedly broken payment gateways, reporting systems, and billing pipelines across the tech industry.
* **Day of Month vs. Day of Week (`D` vs `d`)**: In Moment, `D` is day of month (`1-31`) and `d` is day of week (`0-6`). In LDML, `d` is day of month (`1-31`) and `e` / `c` is day of week.
**The Tempo Solution**:
All primary Tempo format tokens are **strictly lowercase** and uniquely named:
* `{yyyy}`: 4-digit calendar year (`2026`)
* `{yy}`: 2-digit calendar year (`26`)
* `{yow}`: 4-digit ISO week-numbering year (`2026`)
* `{mm}`: Zero-padded month (`01`-`12`)
* `{mi}`: Zero-padded minute (`00`-`59`)
* `{dd}`: Zero-padded day of month (`01`-`31`)
* `{hh}`: 24-hour clock (`00`-`23`)
* `{h12}`: 12-hour clock (`01`-`12`)
* `{ss}`: Zero-padded second (`00`-`59`)
You never need to remember whether a token was uppercase or lowercase. Capitalization in Tempo is reserved strictly for modifier transformations (e.g. `:upper`, `:lower`, `:title`).
---
### 2. Getter-to-Token Symmetry: Zero Context Switching
In legacy libraries, there is a total disconnect between how you read a property in code and how you format it in a template:
| Concept | Native JS / Moment Method | Legacy Format Token | Tempo Getter Property | Native Tempo Format Token |
| :--- | :--- | :--- | :--- | :--- |
| **Year** | `d.getFullYear()` | `YYYY` / `yyyy` / `%Y` | `t.yy` | `{yyyy}` (`{yy}` for 2-digit) |
| **Month** | `d.getMonth() + 1` | `MM` / `%m` / `m` | `t.mm` | `{mm}` |
| **Day** | `d.getDate()` | `DD` / `dd` / `%d` | `t.dd` | `{dd}` |
| **Hour (24h)** | `d.getHours()` | `HH` / `%H` / `H` | `t.hh` | `{hh}` |
| **Minute** | `d.getMinutes()` | `mm` / `%M` / `i` | `t.mi` | `{mi}` |
| **Second** | `d.getSeconds()` | `ss` / `%S` / `s` | `t.ss` | `{ss}` |
| **Millisecond** | `d.getMilliseconds()` | `SSS` / `%f` / `v` | `t.ms` | `{ms}` |
| **ISO Week Year** | `d.isoWeekYear()` | `GGGG` / `YYYY` / `%G` | `t.yow` | `{yow}` |
| **ISO Week** | `d.isoWeek()` | `WW` / `ww` / `%V` | `t.woy` | `{woy}` |
| **Weekday** | `d.isoWeekday()` | `E` / `%u` / `N` | `t.dow` | `{dow}` |
When you learn Tempo's instance properties, you have already learned the format tokens. There is zero mental translation required between writing business logic (`if (t.hh >= 12)`) and writing format strings (`"{hh}:{mi}"`). Note that while `t.yy` yields the full year number in code, `{yyyy}` formats the 4-digit year and `{yy}` formats the 2-digit year.
---
### 3. Composable Modifiers vs. Combinatorial Token Explosion
Historical dialects solve formatting variations by inventing hundreds of arbitrary, single-purpose tokens:
* **LDML**: `M`, `MM`, `MMM`, `MMMM`, `MMMMM`, `L`, `LL`, `LLL`, `LLLL`, `LLLLL`
* **POSIX `strftime`**: `%b`, `%B`, `%h`, `%m`, `%-m`, `%_m`, `%d`, `%-d`, `%e`, `%j`
* **Moment**: `D`, `DD`, `Do`, `DDD`, `DDDD`, `DDDo`, `d`, `dd`, `ddd`, `dddd`, `do`
Developers cannot realistically memorize all these tokens, leading to constant documentation lookups.
**The Tempo Solution**:
Tempo decouples the **semantic data token** from its **presentation modifier**. Modifiers are composable and chainable using a colon (`:`):
| Modifiers Applied | Expression | Output (for 2026-10-24 15:05:09) | Description |
| :--- | :--- | :--- | :--- |
| *None (default)* | `{mon}` | `October` | Base token (capitalized name) |
| `:upper` | `{mon:upper}` | `OCTOBER` | Forced uppercase |
| `:lower` | `{mon:lower}` | `october` | Forced lowercase |
| `:short` | `{mon:short}` | `Oct` | Abbreviated name (alias: `{mmm}`) |
| `:locale` | `{mon:locale}` | `octobre` (in French) | Full localized name |
| `:locale:title` | `{mon:locale:title}` | `Octobre` | Localized name with title-casing |
| `:ord` | `{dd:ord}` | `24th` | Ordinal suffix |
| `:raw` | `{mi:raw}` | `5` | Unpadded number |
| `:space` | `{dd:space}` | ` 4` (for day 4) | Space-padded instead of zero-padded |
| `:` | `{yyyy:-2}` | `26` | Sliced to last 2 digits |
| `:roman` | `{mm:roman}` | `X` | Roman numeral representation |
| `:roman:lower` | `{mm:roman:lower}` | `x` | Lowercase Roman numeral |
Instead of memorizing dozens of distinct tokens, developers learn a small set of orthogonal modifiers (`:ord`, `:raw`, `:upper`, `:locale`, `:space`) that can be applied consistently across **any** token.
---
### 4. Braced Architecture vs. Literal Escaping Nightmares
In historical libraries, arbitrary literal text embedded in format strings is notoriously fragile:
* **Moment / Day.js**: Requires square brackets (`[Recorded on] YYYY-MM-DD`). Forgetting brackets results in `Recorded on` converting characters like `d`, `e`, and `o` into date parts. Escaping an actual bracket requires `[\[nested\]]`.
* **Unicode LDML**: Requires single quotes (`'Recorded on' yyyy-MM-dd`). Literal single quotes are doubled (`'It''s time'`).
* **Go `time.Format`**: Has **no escape mechanism whatsoever**. Literal text containing Go reference tokens (`Jan`, `Mon`, `1`, `2`, `02`, `2006`) cannot be escaped and will unpredictably mutate.
* **POSIX `strftime`**: A literal percent sign is written as `%%`.
**The Tempo Solution**:
In Tempo, **all text outside curly braces is literal by default**:
```typescript
t.format("Recorded on {yyyy}-{mm}-{dd} at {hh}:{mi}!");
// "Recorded on 2026-10-24 at 15:30!"
```
To print literal braces, simply double them: {{ produces { and }} produces }. No quotes, brackets, or backslash escapes needed.
---
## 🚫 Part B: Deliberate Omissions & Architectural Boundaries
When building the `@tempo-kit/plugin-dialects` compatibility engine, we identified several legacy dialect behaviors that we deliberately chose **not** to adopt into native Tempo or promote as best practices:
### 1. Non-ISO Locale Week-Numbering Years (Moment `gggg` / `gg`)
* **The Legacy Behavior**: Moment's `gggg` and `gg` compute week-numbering years based on the locale's first day of the week (e.g. Sunday in the US, Monday in ISO, Saturday in the Middle East). In contrast, PHP `o` and POSIX `%G` strictly compute the ISO 8601 week-numbering year, which Tempo directly supports via `{yow}`.
* **Why We Omitted It**: Locale-dependent week-year calculations lack an unambiguous international standard. In the US, week 1 is often defined simply as the week containing January 1st, whereas ISO 8601 requires week 1 to contain the first Thursday (or 4 days in January). This divergence creates non-deterministic calendar drift across client machines depending on their browser locale. Tempo anchors strictly to the international ISO 8601 standard (`{yow}`, `{woy}`, `{dow}`) by default, guaranteeing consistent results across all runtime environments, while allowing explicit opt-in to locale-based week numbering via `{yow:locale}` and `{woy:locale}`.
### 2. Confusing 1–24 and 0–11 Hour Systems (LDML `k` / `K`)
* **The Legacy Behavior**: LDML defines `k` (hours 1–24, where midnight is `24`) and `K` (hours 0–11 for 12-hour clocks, where midnight is `0` AM and noon is `0` PM).
* **Why We Omitted It**: Representing midnight as `24:00:00` or noon as `0:00 PM` is widely recognized as a source of confusion that causes parsing edge cases and serialization bugs. Tempo provides standard 24-hour (`{hh}`) and standard 12-hour (`{h12}`). When localized display conventions are required, applying `:locale` (e.g. `{hh:locale}`) queries the underlying ECMAScript `Intl` engine to seamlessly adopt the target locale's preferred `hourCycle` (`h11`, `h12`, `h23`, or `h24`).
### 3. Duplicate Standalone vs. Format Inflections (LDML `LLLL` vs `MMMM`, `cccc` vs `EEEE`)
* **The Legacy Behavior**: In inflected languages (such as Russian, Polish, or Finnish), month and weekday names change form depending on whether they appear alone (nominative case: `LLLL`, `cccc`) or alongside a day number (genitive case: `MMMM`, `EEEE`).
* **Why We Omitted It**: Doubling the format token surface (two parallel token hierarchies for every month and weekday) burdens developers with linguistic trivia. Instead of separate token families, Tempo uses its orthogonal `:genitive` modifier (`{mon:genitive}`, `{mmm:genitive}`, `{wkd:genitive}`, `{www:genitive}`) backed by ECMAScript `Intl.DateTimeFormat`, keeping `{mon}` and `{wkd}` clean for standalone nominative use. `:genitive` inflects month names; for weekdays, it returns the locale's date-context form, which can be nominative (for example, `понедельник` for Monday in `ru-RU`).
### 4. Mnemonic Reference Date Formatting (Go `time.Format`)
* **The Legacy Behavior**: Go formats dates using a magic reference timestamp: `Mon Jan 2 15:04:05 MST 2006` (`1 2 3 4 5 6 -0700`).
* **Why We Omitted It**: While memorable in isolation, reference timestamps break down as soon as format masks include arbitrary words containing reference numbers (e.g. `ref1`, `page2`, `step3`) because Go lacks an escape syntax. In Tempo, braced tokens eliminate any possibility of token-literal collision.
### 5. Hardcoded Business / Fiscal Quarter Assumptions
* **The Legacy Behavior**: Many SQL engines and reporting dialects hardcode assumptions that quarters strictly align to Gregorian three-month boundaries (Q1 = Jan–Mar, Q2 = Apr–Jun, etc.).
* **Why We Omitted It**: In real-world enterprise applications, fiscal years, tax cycles, and academic quarters frequently start on arbitrary months (e.g. July 1st in Australia, April 1st in the UK/India, October 1st for the US federal government). Rather than baking inflexible Gregorian quarter tables into core tokens, Tempo encapsulates specialized domain concepts into modular Terms (`#quarter`, `#fiscalYear`). This allows developers to configure custom fiscal calendars without breaking standard date formatting.
---
## 📊 Summary Comparison
| Feature / Trait | Legacy Dialects (LDML, Moment, strftime) | Native Tempo Approach |
| :--- | :--- | :--- |
| **Case Sensitivity** | Critical (typos silently alter data targets) | All lowercase primary tokens (`{yyyy}`, `{mm}`, `{dd}`, `{hh}`) |
| **API Alignment** | Methods and tokens use completely different vocabularies | Direct mirror (`t.yy` $\longleftrightarrow$ `{yyyy}` / `{yy}`, `t.mm` $\longleftrightarrow$ `{mm}`) |
| **Variations & Styling**| Hundreds of arbitrary single-character tokens | Orthogonal, chainable modifiers (`:upper`, `:lower`, `:ord`, `:roman`, `:locale`) |
| **Literal Text** | Requires quotes (`'...'`), brackets (`[...]`), or is unescapable (Go) | Literal by default; doubled braces ({{, }}) for escape |
| **Week-Year Standard**| Mixes ISO and divergent locale-based week years | Anchored strictly to deterministic ISO 8601 by default (`{yow}`, `{woy}`), with explicit `:locale` opt-in (`{yow:locale}`, `{woy:locale}`) |
| **Grammatical Inflection**| Duplicate token families (`LLLL` vs `MMMM`, `cccc` vs `EEEE`) | Orthogonal `:genitive` modifier backed by `Intl` (`{mon:genitive}` inflects months; `{wkd:genitive}` returns the date-context weekday form) |
| **Domain Terms** | Rigid, static token sets | Extensible Terms (`#quarter`, `#isoWeek`, `#dayOfYear`) |
---
> [!TIP]
> **Use Dialects for Migration, Native Tempo for Greenfield**
> While `@tempo-kit/plugin-dialects` provides extensive, high-fidelity compatibility for standard legacy masks, we recommend standardizing on native Tempo `{token}` syntax for new development to maximize clarity, performance, and maintainability.
---
# Document: 9-plugins/dialects.index.md

# @tempo-kit/plugin-dialects
The **Dialects Plugin** enables Tempo to seamlessly format and parse dates using established external formatting standards, including **Unicode LDML / UTS #35 (Luxon, date-fns)**, **POSIX `strftime` (C, Python, Linux)**, **Moment.js / Day.js**, and **Oracle / SQL `TO_CHAR` (PostgreSQL, Snowflake, Redshift)**.
It provides transparent drop-in compatibility shims, multi-candidate fallback parsing, an automated `.explain()` ingestion engine, `.export()` for emitting dialect models from Tempo tokens, and `.convert()` for direct bidirectional transpilation between external ecosystems.
---
## Key Features
- **Drop-In Formatter Compatibility**: `t.toFormat(mask)` (Luxon), `t.dialects.strftime(mask)` (POSIX), `t.dialects.oracle(mask)` (SQL), `t.dialects.moment(mask)` (Moment/Day.js), and more.
- **Multi-Candidate Fallback Parsing**: `Tempo.fromFormats(input, masks[])` tries candidates in order and returns on first successful match.
- **Automated Dialect Ingestion**: `.explain(mask)` translates any legacy format mask into equivalent native Tempo `{token}` syntax with reasoning metadata.
- **Bidirectional Transpilation**: `.convert(mask, from, to)` converts format strings directly between any two supported dialects.
- **9 Supported Dialects**: LDML (Luxon/date-fns), strftime (POSIX/C/Python), Moment/Day.js, Oracle/SQL, PHP, Go, MySQL, .NET, and Spreadsheet (Excel/Sheets).
- **Lazy-Evaluated & Immutable**: Zero overhead until invoked; `Tempo.dialects` is recursively frozen against tampering.
---
## Installation
```bash
npm install @tempo-kit/plugin-dialects
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
const t = new Tempo('2026-10-24T15:30:45');
// Format using external dialect masks
console.log(t.format('yyyy-MM-dd HH:mm:ss', { dialect: DIALECT.Ldml })); // "2026-10-24 15:30:45"
console.log(t.format('%Y-%m-%d %H:%M:%S', { dialect: DIALECT.Strftime })); // "2026-10-24 15:30:45"
console.log(t.format('[Recorded on] MMMM Do YYYY', { dialect: DIALECT.Moment })); // "Recorded on October 24th 2026"
```
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-dialects/install';
const t = new Tempo('2026-10-24T15:30:45');
console.log(t.toFormat('dd LLL yyyy')); // "24 Oct 2026"
```
---
## Supported Dialects
| Dialect Identifier | Canonical Constant | Common Aliases | Format Example | Primary Ecosystems |
| :--- | :--- | :--- | :--- | :--- |
| `'ldml'` | `DIALECT.Ldml` | `'luxon'`, `'datefns'`, `'cldr'` | `yyyy-MM-dd HH:mm:ss.SSS` | Luxon, date-fns, CLDR, Unicode UTS #35 |
| `'strftime'` | `DIALECT.Strftime` | `'posix'`, `'c'`, `'python'` | `%Y-%m-%d %H:%M:%S` | POSIX C, Python datetime, Linux Syslog |
| `'moment'` | `DIALECT.Moment` | `'dayjs'` | `YYYY-MM-DD HH:mm:ss` | Moment.js, Day.js |
| `'oracle'` | `DIALECT.Oracle` | `'sql'`, `'postgres'`, `'postgresql'`, `'snowflake'`, `'redshift'`, `'to_char'` | `YYYY-MM-DD HH24:MI:SS` | Oracle, PostgreSQL, Snowflake, AWS Redshift |
| `'php'` | `DIALECT.Php` | `'laravel'`, `'wordpress'` | `Y-m-d H:i:s` | PHP, Laravel, WordPress, Symfony |
| `'go'` | `DIALECT.Go` | `'golang'` | `2006-01-02 15:04:05` | Go (`time.Format`, `time.Parse`) |
| `'mysql'` | `DIALECT.Mysql` | `'mariadb'` | `%Y-%m-%d %H:%i:%s` | MySQL, MariaDB (`DATE_FORMAT`) |
| `'dotnet'` | `DIALECT.DotNet` | `'csharp'`, `'.net'`, `'c#'` | `yyyy-MM-dd HH:mm:ss.fff` | .NET, C#, PowerShell (`DateTime.ToString`) |
| `'sheet'` | `DIALECT.Sheet` | `'spreadsheet'`, `'excel'`, `'sheets'` | `yyyy-mm-dd hh:mm:ss AM/PM` | Microsoft Excel, Google Sheets, LibreOffice Calc |
> [!TIP]
> **Native Tempo Syntax is Optimal**
> While the Dialects plugin provides seamless interoperability with legacy format masks, **native Tempo braced syntax (`{token}`) remains the most performant, lightweight, and expressive choice**. Native Tempo syntax runs in Core with zero plugin dependencies, and provides rich capabilities unavailable in external token systems—including custom Terms, dynamic dot namespaces (`{geo.city}`), localized modifiers (`{dow:locale}`, `{hh:locale:raw}`), and regional `{intl.*}` property interpolation.
---
## API Reference
The Dialects plugin mounts cohesive static tools onto `Tempo.dialects`, instance utilities onto `t.dialects`, and attaches convenience shims directly onto `Tempo`:
| API / Method | Target | Input | Returns | Description |
| :--- | :--- | :--- | :--- | :--- |
| **`t.toFormat(mask, options?)`** | Instance | Format mask string, options | `string` | **Luxon Drop-In Formatter**. Formats the instance using LDML (or explicit dialect). |
| **`t.dialects.ldml(mask)`** | Instance | Unicode LDML mask | `string` | Fast-path formatter for Unicode LDML / Luxon / date-fns masks. |
| **`t.dialects.strftime(mask)`** | Instance | POSIX strftime mask | `string` | Fast-path formatter for POSIX strftime specifiers (`%Y`, `%m`, `%d`, etc.). |
| **`t.dialects.oracle(mask)`** | Instance | Oracle / SQL mask | `string` | Fast-path formatter for Oracle / PostgreSQL / Snowflake format models (`YYYY`, `HH24`, `MI`, etc.). |
| **`t.dialects.sql(mask)`** | Instance | SQL / Oracle mask | `string` | Convenience alias for `t.dialects.oracle(mask)`. |
| **`t.dialects.php(mask)`** | Instance | PHP date mask | `string` | Fast-path formatter for PHP `date()` specifiers (`Y`, `m`, `d`, `H`, `i`, `s`, etc.). |
| **`t.dialects.go(mask)`** | Instance | Go reference mask | `string` | Fast-path formatter for Go reference time layout (`2006`, `01`, `02`, `15`, `04`, `05`). |
| **`t.dialects.mysql(mask)`** | Instance | MySQL format mask | `string` | Fast-path formatter for MySQL / MariaDB `DATE_FORMAT` specifiers (`%Y`, `%m`, `%d`, `%H`, `%i`, `%s`, etc.). |
| **`t.dialects.dotnet(mask)`** | Instance | .NET format mask | `string` | Fast-path formatter for .NET / C# `DateTime.ToString` custom format strings (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`, `fff`, etc.). |
| **`t.dialects.sheet(mask)`** | Instance | Spreadsheet mask | `string` | Fast-path formatter for Excel / Google Sheets custom format strings (`yyyy`, `mm`, `dd`, `hh`, `ss`, `AM/PM`, etc.). |
| **`t.dialects.format(mask, dialect?)`** | Instance | Mask, dialect identifier | `string` | Generic dialect instance formatter with auto-detection for `%`, Go, SQL, MySQL, .NET, and Sheet specifiers. |
| **`t.dialects.explain(mask, dialectOrOptions?)`** | Instance | External format mask, dialect name or `{ dialect }` | `ExplainResult` | Analyzes mask and returns equivalent native Tempo `{token}` pattern and metadata. |
| **`t.dialects.export(pattern, dialectOrOptions?)`** | Instance | Native Tempo pattern, target dialect name or `{ dialect }` | `ExportResult` | Exports a native Tempo `{token}` pattern into an external dialect format model. |
| **`t.dialects.convert(mask, toOrOptions)`** / **`convert(mask, from, to)`** | Instance | Mask, target dialect, or `{ from, to }` options | `ConvertResult` | Converts a format mask directly from one dialect to another (source dialect auto-inferred if omitted). |
| **`Tempo.fromFormat(input, mask, options?)`** | Static | Date string, mask, options | `Tempo` | **Luxon Drop-In Parser**. Parses an input string using an LDML mask (or auto-detected dialect). |
| **`Tempo.fromFormats(input, masks[], options?)`** | Static | Date string, candidate masks | `Tempo` | Multi-candidate fallback parser with auto-dialect detection (first matching mask succeeds). |
| **`Tempo.dialects.parse(input, mask, dialect?)`** | Static | Date string, mask, dialect | `Tempo` | Explicit dialect parser. |
| **`Tempo.dialects.fromFormats(input, masks[], ...)`**| Static | Date string, candidate masks | `Tempo` | Explicit multi-candidate fallback parser. |
| **`Tempo.dialects.explain(mask, dialectOrOptions?)`** | Static | External format mask, dialect name or `{ dialect }` | `ExplainResult` | AST analyzer translating legacy masks into native Tempo `{token}` syntax. |
| **`Tempo.dialects.export(pattern, dialectOrOptions?)`** | Static | Native Tempo pattern, target dialect name or `{ dialect }` | `ExportResult` | Exports a native Tempo `{token}` pattern into an external dialect format model. |
| **`Tempo.dialects.convert(mask, toOrOptions)`** / **`convert(mask, from, to)`** | Static | Mask, target dialect, or `{ from, to }` options | `ConvertResult` | Transpiles a format mask directly between dialects (source dialect auto-inferred if omitted). |
### Performance & Lazy Evaluation
1. **Pre-Compiled Formatters**: Formatting masks are tokenized and compiled into high-speed closure interpolators on first run and cached in memory. Subsequent executions bypass tokenization and compilation overhead, evaluating directly through cached closures.
2. **Lazy-Evaluated Namespace**: Accessing `t.dialects` utilizes Tempo's zero-overhead proxy pattern, consuming zero CPU cycles until explicitly invoked on an instance.
3. **Immutable Static Namespace**: `Tempo.dialects` is recursively frozen via `deepFreeze()` to protect the host class against runtime tampering.
---
## Topic Guides
To explore technical deep-dives, token compatibility matrices, and production patterns, consult the dedicated guides below:
- **[Design Strategy & Deliberate Omissions](./dialects.design-philosophy-and-omissions.md)**: Why Tempo engineered `{token:modifier}` over historical dialects, benefits of all-lowercase tokens and getter symmetry, and why specific legacy features were omitted.
- **[Migration & Legacy Compatibility](./dialects.migration-and-compatibility.md)**: Resolving the `YYYY` vs `yyyy` year trap, handling bracketed/quoted escaping, using `.explain()` for automated codemods, and performance benchmarks.
- **[Token Specification & Cross-Ecosystem Matrix](./dialects.token-specification.md)**: Exhaustive token lookup table mapping LDML, Moment, strftime, and native Tempo tokens across years, months, days, sub-seconds, and timezones.
- **[Production Use Cases & Architectural Patterns](./dialects.use-cases-and-patterns.md)**: Multi-candidate webhook ingestion pipelines, enterprise POSIX syslog formatting, and zero-downtime gradual modernization recipes.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/dialects.migration-and-compatibility.md
# Migration & Legacy Compatibility
The `@tempo-kit/plugin-dialects` plugin is engineered to provide frictionless, zero-downtime migration paths for codebases transitioning to Tempo from **Moment.js**, **Day.js**, **Luxon**, or **date-fns**, as well as legacy backend systems that emit standard **POSIX `strftime`** specifiers.
---
## The Migration Challenge: Token Traps & Gotchas
Directly porting format strings between date libraries without validation often introduces subtle production regressions due to conflicting token semantics across ecosystems:
### 1. The Year Trap: `YYYY` vs `yyyy`
One of the most dangerous formatting bugs in modern web applications occurs during late December and early January:
* **In Moment.js & Day.js**: `YYYY` represents the standard calendar year (e.g. `2026`).
* **In Unicode LDML (Luxon, date-fns)**: `yyyy` represents the calendar year, while `YYYY` represents the **ISO week-numbering year**.
* **The Pitfall**: Formatting `2025-12-31` with `YYYY` under LDML outputs `2026` because December 31st belongs to the first week of 2026. This has historically caused catastrophic financial and billing errors.
* **The Tempo Solution**: Tempo Core uses `{yyyy}` for the 4-digit calendar year and `{yow}` for the ISO week-numbering year. The Dialects plugin automatically normalizes these semantics when evaluating legacy masks.
### 2. Month vs Minute: `MM` vs `mm` vs `mi`
In legacy libraries, uppercase `MM` designates months, while lowercase `mm` designates minutes. Accidental capitalization (e.g., `HH:MM:ss`) prints the month instead of the minute.
Tempo solves this ambiguity at the foundational syntax level:
* `{mm}`: Zero-padded month (`01-12`)
* `{mi}`: Zero-padded minute (`00-59`)
* `{mon}`: Full month name (`October`)
* `{mmm}`: Short month name (`Oct`)
### 3. Escaping Literals: Quotes vs Brackets
Different ecosystems handle arbitrary literal text within format strings inconsistently:
| Ecosystem | Literal Escaping Syntax | Example | Escaping Quotes / Brackets |
| :--- | :--- | :--- | :--- |
| **Tempo Core** | Braced tokens; all outer text is literal | `Recorded on {yyyy}-{mm}-{dd}` | {{ → {, }} → } |
| **Moment.js / Day.js** | Square brackets `[...]` | `[Recorded on] YYYY-MM-DD` | `[\[literal\]]` |
| **Unicode LDML** | Single quotes `'...'` | `'Recorded on' yyyy-MM-dd` | `''` (two single quotes) |
| **POSIX `strftime`** | Direct text; `%` prefixes tokens | `Recorded on %Y-%m-%d` | `%%` produces `%` |
---
## Automated Migration Engine: `Tempo.dialects.explain()`
To eliminate guesswork and avoid manual regex translation, the Dialects plugin includes a built-in static AST analyzer: `Tempo.dialects.explain()`.
It inspects any legacy format mask, auto-detects or confirms the originating dialect, and translates it into the equivalent native Tempo `{token}` pattern alongside a token-by-token metadata breakdown:
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
// 1. Analyze a legacy Moment.js mask with bracketed literals and ordinals
const analysis = Tempo.dialects.explain('[Report for] MMMM Do, YYYY [at] hh:mm A', DIALECT.Moment);
console.log(analysis.pattern);
// Output: "Report for {mon} {dd:ord}, {yyyy} at {h12}:{mi} {mer:upper}"
console.log(analysis.dialect);
// Output: "moment"
// Inspect the mapped token array
console.log(analysis.tokens);
// [
// { source: 'MMMM', tempo: '{mon}', desc: 'Full month name (e.g. October)' },
// { source: 'Do', tempo: '{dd:ord}', desc: 'Day of month with ordinal suffix (1st-31st)' },
// { source: 'YYYY', tempo: '{yyyy}', desc: '4-digit year' },
// { source: 'hh', tempo: '{h12}', desc: '12-hour clock (01-12)' },
// { source: 'mm', tempo: '{mi}', desc: 'Zero-padded minute (00-59)' },
// { source: 'A', tempo: '{mer:upper}', desc: 'AM/PM marker (uppercase)' }
// ]
```
### Programmatic Mask Upgrades in Build Pipelines
You can use `explain()` in a code-mod or lint rule to audit and rewrite legacy format strings across your codebase:
```typescript
function migrateLegacyMask(legacyMask: string, dialect?: string): string {
const result = Tempo.dialects.explain(legacyMask, dialect);
return result.pattern;
}
// Convert Luxon masks to native Tempo
const modernPattern = migrateLegacyMask("yyyy-MM-dd 'T' HH:mm:ss.SSS zzzz", 'ldml');
console.log(modernPattern);
// Output: "{yyyy}-{mm}-{dd} T {hh}:{mi}:{ss}.{ms} {tz:long}"
```
---
## Exporting Dialect Models: `Tempo.dialects.export()`
To emit external dialect masks from canonical Tempo patterns (for example, generating SQL/Oracle `TO_CHAR` format models or POSIX `strftime` masks from shared application templates), use `Tempo.dialects.export()`:
```typescript
// Export canonical Tempo pattern to Oracle / SQL TO_CHAR model
const oracleExport = Tempo.dialects.export('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}', 'oracle');
console.log(oracleExport.pattern);
// Output: "YYYY-MM-DD HH24:MI:SS"
// Export to POSIX strftime
const posixExport = Tempo.dialects.export('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}', 'strftime');
console.log(posixExport.pattern);
// Output: "%Y-%m-%d %H:%M:%S"
```
Any tokens that cannot be directly mapped to the target ecosystem are tracked in `unsupported`.
---
## Universal Cross-Dialect Conversion: `Tempo.dialects.convert()`
With Tempo serving as an Intermediate Representation (IR), you can convert format masks directly between any supported external ecosystems in a single call:
```typescript
// Convert POSIX strftime directly to Oracle / SQL TO_CHAR
const sqlMask = Tempo.dialects.convert('%Y-%m-%d %H:%M:%S', 'strftime', 'oracle');
console.log(sqlMask.pattern);
// Output: "YYYY-MM-DD HH24:MI:SS"
// Convert Moment.js directly to POSIX strftime
const posixMask = Tempo.dialects.convert('YYYY-MM-DD HH:mm:ss', 'moment', 'strftime');
console.log(posixMask.pattern);
// Output: "%Y-%m-%d %H:%M:%S"
// Auto-detect source dialect
const toLdml = Tempo.dialects.convert('%Y-%m-%d', 'ldml');
console.log(toLdml.pattern);
// Output: "yyyy-MM-dd"
```
---
## Drop-In API Compatibility Shims
For large codebases where updating thousands of call sites simultaneously is impractical, installing `DialectsPlugin` attaches drop-in convenience methods directly onto `Tempo`:
### 1. Luxon Drop-In: `t.toFormat()`
Existing Luxon format invocations can be ported by replacing the instance with `Tempo` without changing the formatting calls:
```typescript
const t = new Tempo('2026-10-24T15:30:45');
// Luxon drop-in instance method
console.log(t.toFormat('dd LLL yyyy'));
// Output: "24 Oct 2026"
console.log(t.toFormat("'Time:' HH:mm:ss"));
// Output: "Time: 15:30:45"
```
### 2. Static Parsers: `Tempo.fromFormat()` & `Tempo.fromFormats()`
```typescript
// Parse a single known format
const t1 = Tempo.fromFormat('24/10/2026', 'dd/MM/yyyy');
console.log(t1.iso); // "2026-10-24T00:00:00+..."
// Multi-candidate fallback parsing (evaluates candidates until a match succeeds)
const t2 = Tempo.fromFormats('10/24/2026 15:30', [
'yyyy-MM-dd HH:mm',
'dd/MM/yyyy HH:mm',
'MM/dd/yyyy HH:mm'
]);
console.log(t2.dd); // 24
console.log(t2.mm); // 10
```
---
## Performance Comparison: Native Tempo vs Dialects
While `@tempo-kit/plugin-dialects` is highly optimized with an internal compiled closure cache, **native Tempo `{token}` syntax remains significantly faster**:
```
┌────────────────────────────────────────────────────────────────────────┐
│ Formatting Performance Comparison (100,000 Iterations) │
├────────────────────────────────────────────────────────────────────────┤
│ Native Tempo Core ({yyyy}-{mm}-{dd}) ████████████████████ 1.8x - 2.5x│
│ Dialects LDML (yyyy-MM-dd) ██████████ Cached │
│ Dialects strftime (%Y-%m-%d) █████████ Cached │
│ Moment.js Library (Legacy Reference) ████ Baseline │
└────────────────────────────────────────────────────────────────────────┘
```
### Why Native Syntax is Faster
1. **Zero Intermediate Token Mapping**: Native Tempo tokens map directly to Temporal ZonedDateTime getters (`zdt.year`, `zdt.month`, `zdt.day`) inside Core.
2. **Zero Regex Dialect Routing**: External masks require regex tokenization and token AST resolution before execution.
3. **No Plugin Overhead**: Native formatting requires zero plugins loaded into memory, keeping bundle size minimal.
### Recommended Migration Strategy
1. **Phase 1 (Immediate)**: Install `@tempo-kit/plugin-dialects`. Keep existing format strings untouched using `t.format(mask, { dialect })`, `t.toFormat()`, and `Tempo.fromFormat()`.
2. **Phase 2 (Automated Audit)**: Run `Tempo.dialects.explain()` across your format strings to generate native `{token}` equivalents.
3. **Phase 3 (Optimization)**: Transition critical hot-paths and high-throughput logging routines to native Tempo format patterns for peak throughput.
---
# Document: 9-plugins/dialects.token-specification.md
# Production Use Cases & Architectural Patterns
This guide showcases concrete, real-world architectural patterns where `@tempo-kit/plugin-dialects` solves non-trivial integration and migration challenges in production environments.
---
## 1. Heterogeneous Third-Party Webhook Ingestion
### Problem Statement
In multi-tenant SaaS platforms or marketplace integrations (e.g. Shopify, Stripe, FedEx, Salesforce), inbound webhooks and partner API payloads arrive with wildly inconsistent date formats. Some send standard ISO 8601 strings, others omit seconds, some use European `dd/MM/yyyy`, and others emit legacy 12-hour AM/PM formats (`MM/dd/yyyy hh:mm a`). Hand-coding nested try/catch blocks for each vendor is fragile and expensive.
### Architectural Solution
Use `Tempo.dialects.fromFormats()` with an ordered list of candidate masks. The parser executes a high-speed layout matcher across candidate formats, returning a validated `Tempo` instance on the first matching signature.
```
Incoming Webhook Payload
│
▼
┌────────────────────────────────────────────────────────┐
│ Candidate Mask Fallback Array │
│ 1. "yyyy-MM-dd HH:mm:ss" │
│ 2. "yyyy-MM-ddTHH:mm:ssZ" │
│ 3. "dd/MM/yyyy HH:mm" │
│ 4. "MM/dd/yyyy hh:mm a" │
│ 5. "yyyy-MM-dd" │
└────────────────────────────────────────────────────────┘
│
▼
Validated Immutable Tempo Instance (Normalized to UTC)
```
### Production Implementation
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
// Define candidate formats ordered by descending specificity
const WEBHOOK_CANDIDATE_MASKS = [
'yyyy-MM-dd HH:mm:ss',
'yyyy-MM-ddTHH:mm:ssZ',
'dd/MM/yyyy HH:mm',
'MM/dd/yyyy hh:mm a',
'yyyy-MM-dd'
];
/**
* Ingests external webhook timestamps into normalized UTC Tempo instances.
*/
export function normalizeExternalTimestamp(rawTimestamp: string): Tempo {
const parsed = Tempo.dialects.fromFormats(rawTimestamp, WEBHOOK_CANDIDATE_MASKS, {
dialect: DIALECT.Ldml,
timeZone: 'UTC'
});
if (!parsed.isValid) {
throw new Error(`[Webhook Ingestion] Unrecognized timestamp signature: "${rawTimestamp}"`);
}
return parsed;
}
// 1. Standard ISO with space
const t1 = normalizeExternalTimestamp('2026-10-24 15:30:45');
console.log(t1.iso); // "2026-10-24T15:30:45Z"
// 2. European format without seconds
const t2 = normalizeExternalTimestamp('24/10/2026 15:30');
console.log(t2.iso); // "2026-10-24T15:30:00Z"
// 3. US 12-hour format with AM/PM
const t3 = normalizeExternalTimestamp('10/24/2026 03:30 pm');
console.log(t3.iso); // "2026-10-24T15:30:00Z"
```
---
## 2. Enterprise Syslog & Audit Trail Compliance (POSIX `strftime`)
### Problem Statement
Enterprise security architectures and cloud logging daemons (Fluentd, Logstash, AWS CloudWatch, Datadog) require timestamps that strictly adhere to legacy POSIX standards—such as **RFC 3164 BSD Syslog** (`Oct 24 15:30:45`) or **RFC 5424 High-Precision Structured Syslog** (`2026-10-24T15:30:45.123456Z`). Writing manual string concatenation for padding, localized month abbreviations, and microsecond extraction is error-prone and hard to maintain.
### Architectural Solution
Use `t.format(mask, { dialect: DIALECT.Strftime })` to emit exact POSIX-compliant specifiers (`%b`, `%e`, `%H`, `%M`, `%S`, `%f`). The pre-compiled format cache evaluates these specs directly against the underlying high-resolution timestamp.
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
export class SecurityAuditLogger {
/**
* Formats a legacy RFC 3164 BSD Syslog header: "Mmm dd hh:mm:ss"
* e.g. "Oct 24 15:30:45"
*/
static formatRFC3164(tempo: Tempo): string {
return tempo.format('%b %e %H:%M:%S', { dialect: DIALECT.Strftime });
}
/**
* Formats an RFC 5424 High-Precision Audit Timestamp with microsecond precision:
* e.g. "2026-10-24T15:30:45.123456Z"
*/
static formatRFC5424(tempo: Tempo): string {
return tempo.format('%Y-%m-%dT%H:%M:%S.%fZ', { dialect: DIALECT.Strftime });
}
}
// Example Execution
const eventTime = new Tempo('2026-10-24T15:30:45.123456Z', { timeZone: 'UTC' });
console.log(SecurityAuditLogger.formatRFC3164(eventTime));
// Output: "Oct 24 15:30:45"
console.log(SecurityAuditLogger.formatRFC5424(eventTime));
// Output: "2026-10-24T15:30:45.123456Z"
```
---
## 3. Zero-Downtime Gradual Modernization Pipeline
### Problem Statement
A large enterprise frontend and backend codebase has thousands of legacy call sites using Moment.js (`moment(d).format('YYYY-MM-DD')`) or Luxon (`DateTime.fromISO(d).toFormat('dd LLL yyyy')`). Migrating every call site at once is too risky and creates massive merge conflicts across engineering teams.
### Architectural Solution
Deploy a three-stage migration pipeline:
1. **Stage 1 (Shim Layer)**: Replace Moment / Luxon imports with Tempo. The plugin's attached shims (`t.toFormat()`, `Tempo.fromFormat()`) fulfill all existing method calls transparently without requiring changes to format masks.
2. **Stage 2 (Automated Code-Mod via `explain`)**: Use `Tempo.dialects.explain()` in an automated CI lint rule or codemod script to inspect each format string and automatically rewrite it to native Tempo `{token}` syntax.
3. **Stage 3 (Native Runtime)**: Once all masks are converted to native syntax, remove the dialect layer for zero-dependency peak throughput.
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
// Stage 1: Legacy call sites continue working unchanged via shims
const now = new Tempo('2026-10-24T15:30:45');
console.log(now.toFormat('dd LLL yyyy')); // "24 Oct 2026"
// Stage 2: Automated inspection and translation tool
export function auditAndMigrateFormatMask(legacyMask: string, dialect: string) {
const explained = Tempo.dialects.explain(legacyMask, dialect);
return {
sourceMask: legacyMask,
nativeTempoPattern: explained.pattern,
tokenCount: explained.tokens.length,
readyForCore: true
};
}
const migrationResult = auditAndMigrateFormatMask('YYYY-MM-DD [at] hh:mm:ss A', DIALECT.Moment);
console.log(migrationResult.nativeTempoPattern);
// Output: "{yyyy}-{mm}-{dd} at {h12}:{mi}:{ss} {mer:upper}"
// Stage 3: Direct native format execution (Core only, zero plugin overhead)
console.log(now.format(migrationResult.nativeTempoPattern, { dialect: null }));
// Output: "2026-10-24 at 03:30:45 PM"
```
---
## 4. Cross-Ecosystem Format Transpilation (`.convert()` & `.export()`)
### Problem Statement
In distributed architectures, different subsystems require different date token conventions. For example, a React frontend may define display masks in Moment or Luxon format, an Oracle or PostgreSQL database query requires `TO_CHAR(..., 'YYYY-MM-DD HH24:MI:SS')`, and a Linux syslog forwarder uses POSIX `strftime` (`%Y-%m-%d %H:%M:%S`). Maintaining synchronized format strings across these boundaries manually leads to subtle drift and formatting bugs.
### Architectural Solution
Use Tempo as a format Intermediate Representation (IR). You can either convert legacy masks directly between ecosystems via `.convert()`, or define application templates in canonical Tempo syntax and export target masks dynamically with `.export()`.
```typescript
import { Tempo } from 'tempo-kit';
import { DialectsPlugin, DIALECT } from '@tempo-kit/plugin-dialects';
Tempo.use(DialectsPlugin);
// 1. Cross-compile frontend Moment mask directly to database TO_CHAR model
const clientMask = 'YYYY-MM-DD HH:mm:ss';
const sqlModel = Tempo.dialects.convert(clientMask, DIALECT.Moment, DIALECT.Oracle);
console.log(sqlModel.pattern);
// Output: "YYYY-MM-DD HH24:MI:SS"
// 2. Export canonical backend template to POSIX syslog and SQL models
const canonicalMask = '{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}';
const syslogFormat = Tempo.dialects.export(canonicalMask, DIALECT.Strftime);
console.log(syslogFormat.pattern);
// Output: "%Y-%m-%d %H:%M:%S"
const dbFormat = Tempo.dialects.export(canonicalMask, DIALECT.Oracle);
console.log(dbFormat.pattern);
// Output: "YYYY-MM-DD HH24:MI:SS"
```
---
# Document: 9-plugins/geo.cultural-sync.md
# Cultural Locale Synchronization
This guide explores the cultural synchronization engine in `@tempo-kit/plugin-geo`, linking physical geography with localized language, date formatting, and regional calendar conventions.
---
## 1. The Challenge of Geographic Formatting
When a user travels or logs in from another country (e.g. from London to Tokyo or Cairo), updating their `timeZone` alone is often insufficient:
- Updating timezone shifts the clock time, but date formatting and day names might still remain in the home language (`en-US`).
- Setting a cultural locale (`ar-EG`, `ja-JP`, `de-DE`, `fr-FR`) ensures month names, day names, relative periods ("yesterday", "tomorrow"), and calendar numbering conventions match the observer's physical territory.
---
## 2. Automatic Cultural Sync (`t.geoLocate({ setLocale })`)
When calling `t.geoLocate()`, the `setLocale` option controls how the BCP 47 locale is synchronized with physical geography:
- **`'native'`**: Converts to the primary native language and culture of the territory (e.g. `ar-EG` in Egypt, `ja-JP` in Japan).
- **`true` / `'regional'`** *(default)*: Preserves the caller's source language while adapting regional calendar rules (e.g. `en-US` + `EG` → `en-EG`).
- **Custom BCP 47 string**: Explicit override (e.g. `'fr-EG'`).
- **`false` / `'none'`**: Opts out of locale synchronization.
```typescript
import { Tempo } from 'tempo-kit';
import { GeoPlugin } from '@tempo-kit/plugin-geo';
Tempo.use(GeoPlugin);
const t = new Tempo('2026-06-21T12:00:00Z', {
geo: { lat: 30.0444, lng: 31.2357, country: 'EG' } // Cairo, Egypt
});
// 1. Native Cultural Sync: adopts Egypt's primary native language (Arabic)
const localizedNative = await t.geoLocate({ setLocale: 'native' });
console.log(localizedNative.tz); // 'Africa/Cairo'
console.log(localizedNative.locale); // 'ar-EG'
console.log(localizedNative.format({ dateStyle: 'full' })); // 'الأحد، ٢١ يونيو ٢٠٢٦'
// 2. Regional Adaptation (default): keeps English language, adapts Egyptian calendar/weekend
const localizedRegional = await t.geoLocate({ setLocale: true });
console.log(localizedRegional.locale); // 'en-EG'
console.log(localizedRegional.format({ dateStyle: 'full' })); // 'Sunday, 21 June 2026'
```
### Call-Site Preference Priority
Explicit caller preferences always take absolute precedence:
```typescript
// Explicit custom BCP 47 tag
const custom = await t.geoLocate({ setLocale: 'fr-EG' });
console.log(custom.locale); // 'fr-EG'
```
---
## 3. Pure Cultural Locale Inference (`resolveCulturalLocale`)
`resolveCulturalLocale` maps geographic coordinates, ISO country codes, or bounding territories to a standard BCP 47 locale tag:
```typescript
import { resolveCulturalLocale } from '@tempo-kit/plugin-geo';
// From geographic coordinate objects
console.log(resolveCulturalLocale({ lat: 35.6762, lng: 139.6503 })); // 'ja-JP' (Tokyo)
console.log(resolveCulturalLocale({ lat: 52.5200, lng: 13.4050 })); // 'de-DE' (Berlin)
console.log(resolveCulturalLocale({ lat: 48.8566, lng: 2.3522 })); // 'fr-FR' (Paris)
console.log(resolveCulturalLocale({ lat: -33.8688, lng: 151.2093 })); // 'en-AU' (Sydney)
// From country code directly
console.log(resolveCulturalLocale({ countryCode: 'BR' })); // 'pt-BR'
console.log(resolveCulturalLocale({ countryCode: 'IT' })); // 'it-IT'
```
---
## 4. Internationalization Synergy with `@magmacomputing/library`
`resolveCulturalLocale` leverages `getLC()` from `#library/international.library.js`. It validates and memoizes `Intl.Locale` instances, applying defensive normalization to avoid runtime locale tag errors across different JavaScript runtimes.
---
# Document: 9-plugins/geo.index.md

# @tempo-kit/plugin-geo
A dedicated Community plugin for the [Tempo](https://github.com/magmacomputing/magma) ecosystem providing universal geolocation lookup, forward and reverse geocoding gateway, pluggable provider architecture, cultural locale synchronization, and multi-tenant bounded coordinate caching.
For geometric GIS math, Great-Circle navigation, and impossible travel anomaly detection, see [`@tempo-kit/plugin-spatial`](./spatial.index.md).
---
## Key Features
- **Universal Geolocation Lookup**: Hardware GPS (browser) or IP-based server lookup via `Tempo.geo.lookup()`, cached for 24h.
- **Forward & Reverse Geocoding**: `Tempo.geo.forward(query)` converts place names to coordinates; `Tempo.geo.reverse(coords)` resolves locality metadata.
- **Pluggable Provider Architecture**: Swap geocoding backends (`OpenStreetMapProvider`, `IpApiProvider`, `MockGeoProvider`) or supply a custom provider via `Tempo.geo.setProvider()`.
- **Cultural Locale Synchronization**: `t.geoLocate({ setLocale: 'native' })` automatically infers BCP-47 locale from resolved country and territory.
- **Multi-Tenant Bounded Caching**: Partitioned coordinate storage with 24h TTL and tenant-isolated keys via `Tempo.geo.set()` / `Tempo.geo.get()`.
- **Immutable Namespace**: `Tempo.geo` is recursively frozen—tamper-proof and zero-mutation.
---
## Installation
```bash
npm install @tempo-kit/plugin-geo
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { GeoPlugin } from '@tempo-kit/plugin-geo';
Tempo.use(GeoPlugin);
// Universal Geolocation Lookup (cached for 24h)
const lookup = await Tempo.geo.lookup();
console.log(lookup.lat, lookup.lng, lookup.city);
// Enrich a Tempo instance with physical reality and native cultural locale
const t = new Tempo('2026-06-21T12:00:00Z', {
geo: { lat: 30.0444, lng: 31.2357, country: 'EG' } // Cairo, Egypt
});
const localTime = await t.geoLocate({ setLocale: 'native' });
console.log(localTime.geo?.latitude, localTime.geo?.longitude);
console.log(localTime.locale); // 'ar-EG'
console.log(localTime.format({ dateStyle: 'full' })); // 'الأحد، ٢١ يونيو ٢٠٢٦' (Arabic Egyptian culture)
```
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-geo/install';
```
### Reverse Geocoding and Instance Enrichment
```typescript
import { Tempo } from 'tempo-kit';
import { GeoPlugin } from '@tempo-kit/plugin-geo';
Tempo.use(GeoPlugin);
// Reverse geocode coordinates to place details (using built-in lookup or custom GeoProvider)
const place = await Tempo.geo.reverse({ lat: -33.8688, lng: 151.2093 });
console.log(place?.city, place?.country); // Sydney, AU
// Or enrich an existing instance via t.geoLocate({ reverse: true })
const t = new Tempo({ geo: { lat: -33.8688, lng: 151.2093 } });
const enriched = await t.geoLocate({ reverse: true });
console.log(enriched.geo?.city, enriched.geo?.country); // Sydney, AU
```
---
## API Reference
### Which Method Should I Choose?
| Goal | Method to Use | Input | Output |
| :--- | :--- | :--- | :--- |
| **"Where is this machine / user right now?"** | `await Tempo.geo.lookup({ refresh: true })` | None / `{ refresh: true }` | Fresh `{ latitude, longitude, city, ... }` |
| **"Convert place name / address to coordinates"** | `await Tempo.geo.forward("Paris")` | Address query string | `{ latitude, longitude, ... }` |
| **"Convert GPS coordinates to street / city / country"** | `await Tempo.geo.reverse({ lat, lng })` | Coordinate object | `{ city, country, ... }` |
| **"Extract or safely normalize coordinates from any input"** | `await Tempo.geo.resolve(input)` | Instance, config, or object | Canonical `{ latitude, longitude, ... }` |
| **"Localize a Tempo instance with timezone & cultural calendar"** | `await t.geoLocate()` | Existing `Tempo` instance | New enriched `Tempo` instance |
### Comprehensive `Tempo.geo` API Surface
| Method / Property | Category | Description |
| :--- | :--- | :--- |
| `Tempo.geo.lookup(opts?)` | Lookup | Universal geolocation lookup (browser hardware GPS or server IP lookup) cached for 24h. Supports `{ refresh: true }`. |
| `Tempo.geo.forward(query, opts?)` | Geocoding | Forward geocodes place query string to coordinates using active provider. |
| `Tempo.geo.reverse(coords, opts?)` | Geocoding | Reverse geocodes coordinates to locality/address metadata (`city`, `country`, `displayName`, etc.) using active provider. |
| `Tempo.geo.setProvider(provider)` | Provider Gateway | Sets custom geolocation/geocoding provider gateway (e.g. OpenStreetMap, Mapbox, internal IP proxy). |
| `Tempo.geo.getProvider()` | Provider Gateway | Retrieves the active custom geolocation provider. |
| `Tempo.geo.resolve(input, opts?)` | Utility | Asynchronously resolves coordinates from an instance, configuration, or ambient storage cache. |
| `Tempo.geo.coerce(input)` | Geometry | Pure function normalizing various coordinate formats (`lat/lng`, `latitude/longitude`, tuples, etc.) into a canonical `GeoConfig`. |
| `resolveCulturalLocale(locale?, country?, mode?)` | Cultural Sync | Standalone function resolving synchronized BCP 47 locale from current locale and ISO country code/name. |
| `Tempo.geo.get(keyOrOpts?)` | Storage | Reads stored coordinates for the specified tenant/IP or ambient default. |
| `Tempo.geo.set(coords, ttl?, keyOrOpts?)` | Storage | Sets coordinates in storage with an optional custom TTL (default: 24h) and multi-tenant partitioning. |
| `Tempo.geo.clear(keyOrOpts?)` | Storage | Purges stored coordinates from storage. |
| `Tempo.geo.current` | Storage | **Read-only getter** returning the active global/ambient coordinates snapshot (`getStashedGeo() ?? Tempo.config.geo`). |
| `Tempo.geo.server(opts?)` | Low-Level | Low-level server-side IP geolocation handler. |
| `Tempo.geo.browser(opts?)` | Low-Level | Low-level browser Geolocation API handler. |
### Fluent Instance Methods
| Instance Method | Description |
| :--- | :--- |
| `t.geoLocate(opts?)` | Asynchronously resolves physical location (with optional reverse geocoding `{ reverse: true }` and cultural locale synchronization `{ setLocale: true }`) and returns a new enriched `Tempo` instance. |
| `t.geoLookup(opts?)` | Resolves coordinates for this instance via explicit coordinates or automatic IP/hardware lookup. |
### Security & Immutability
In keeping with Tempo's strict immutability principles, the `Tempo.geo` namespace is fully locked down:
- **Deeply Frozen**: The entire `Tempo.geo` namespace and attached utilities are recursively frozen via `deepFreeze`.
- **Tamper-Proof**: Protected against reassignment or monkey-patching.
- **Pure Instance Operations**: Instance methods like `t.geoLocate()` return new, enriched `Tempo` instances, preserving the immutability of the original instance.
---
## Topic Guides
Explore detailed guides on specific capabilities:
- **[Provider Gateway & Geocoding](./geo.provider-gateway.md)**: Forward geocoding, reverse geocoding, custom geocoding providers (`OpenStreetMapProvider`, `IpApiProvider`, `MockGeoProvider`), and call-site overrides.
- **[Cultural Synchronization](./geo.cultural-sync.md)**: Automatic cultural locale inference (`setLocale: true` / `'native'`), territorial language resolution, and internationalization synergy.
- **[Storage & Multi-Tenant Caching](./geo.storage-and-caching.md)**: Ambient coordinate caching, 24h TTL `BoundedCache`, tenant isolation, and server vs. client operational warnings.
- **[Production Use Cases & Architectural Patterns](./geo.use-cases-and-patterns.md)**: Multi-tenant SaaS localization, pluggable geocoding gateways, isolated tenant storage caching, and server edge middleware.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/geo.provider-gateway.md
# Storage & Multi-Tenant Caching
This guide covers coordinate persistence, 24-hour TTL caching, multi-tenant partitioning, and critical operational warnings when using `@tempo-kit/plugin-geo`.
---
## 1. Ambient Storage & 24-Hour Bounded Cache
To prevent redundant network requests, `Tempo.geo.lookup()` automatically caches coordinates for 24 hours using `BoundedCache` from `tempo-kit/library`.
```typescript
import { Tempo } from 'tempo-kit';
import { GeoPlugin } from '@tempo-kit/plugin-geo';
Tempo.use(GeoPlugin);
// First call performs network lookup & caches result
const coords = await Tempo.geo.lookup();
// Subsequent calls return the cached snapshot instantaneously
const cached = await Tempo.geo.lookup();
// Force fresh network lookup by bypassing cache
const fresh = await Tempo.geo.lookup({ refresh: true });
// Read ambient active snapshot synchronously
console.log(Tempo.geo.current);
```
---
## 2. Multi-Tenant Partitioning (`keyOrOpts`)
::: danger Multi-Tenant Isolation
**Unpartitioned ambient storage is shared. In multi-tenant environments, always use unique tenant keys or instance-level options.**
:::
In a shared backend process handling concurrent requests for different tenants, storing coordinates under the global ambient key will cause tenants to overwrite each other.
### Solution A: Keyed Partitioning
Pass a tenant identifier or user ID:
```typescript
// Store coordinates for Tenant Alpha
Tempo.geo.set(tenantACoords, undefined, 'tenant-alpha');
// Read coordinates for Tenant Alpha
const alphaCoords = Tempo.geo.get('tenant-alpha');
// Clear coordinates for Tenant Alpha
Tempo.geo.clear('tenant-alpha');
```
Under the hood, storage keys are partitioned under `_magma_geo_:`, ensuring strict multi-tenant isolation.
### Solution B: Instance-Level Scoping (Recommended)
Attach coordinates directly to `Tempo` instances:
```typescript
const tenantTime = new Tempo(date, { geo: tenantCoords });
```
Instance-level coordinates are local, immutable, and never touch shared memory or global caches.
---
## 3. Server IP vs. Client Location Operational Warnings
::: warning Server IP vs. User Location
**Ambient IP lookup on a server resolves the SERVER's location, NOT the user's location.**
:::
- In a server environment (Node.js, Deno, Bun, Edge runtimes), calling `Tempo.geo.lookup()` without an explicit IP queries the **server datacenter's public outbound IP address**.
- If your server runs in AWS `us-east-1` (Virginia) and an Australian user hits your API, calling ambient `Tempo.geo.lookup()` will resolve to Virginia!
- **Best Practice for Backends**:
- Always extract the client IP from trusted reverse proxy headers (e.g., `X-Forwarded-For`, `CF-Connecting-IP`) and pass it explicitly:
```typescript
const userCoords = await Tempo.geo.lookup({ ip: clientIp });
const userTime = new Tempo(date, { geo: userCoords });
```
- Or receive explicit GPS/browser coordinates from the frontend client request payload.
---
# Document: 9-plugins/geo.use-cases-and-patterns.md
# Business Days & SLA Arithmetic
The **Regional Holidays Plugin** extends Tempo with robust business day operations and SLA (Service Level Agreement) working hours arithmetic under the `t.holidays` namespace.
---
## Determining Working Business Days
A date is considered a **business day** if:
1. It does not fall on a weekend day (according to the cultural locale weekend definition in `tempo.intl.info.weekend`, defaulting to Saturday/Sunday).
2. It does not fall on a recognized public holiday in the active country/region.
3. It does not match any date in `options.customHolidays`.
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
// US Independence Day (Observed Friday July 3, 2026)
const t1 = new Tempo('2026-07-03', { geo: { country: 'US' } });
console.log(t1.holidays.isBusinessDay()); // false (Holiday)
// Regular Monday
const t2 = new Tempo('2026-07-06', { geo: { country: 'US' } });
console.log(t2.holidays.isBusinessDay()); // true
```
---
## Navigating Business Days
### `t.holidays.nextBusinessDay()` and `t.holidays.prevBusinessDay()`
Skips over weekends and intervening public holidays to find the nearest valid working business day:
```typescript
// Thursday July 2, 2026 (US)
const start = new Tempo('2026-07-02', { geo: { country: 'US' } });
// Friday July 3 is Independence Day (Observed), July 4-5 is the weekend
const next = start.holidays.nextBusinessDay();
console.log(next.format('{yyyy}-{mm}-{dd}')); // '2026-07-06' (Monday)
// Stepping backwards from Monday July 6
const prev = next.holidays.prevBusinessDay();
console.log(prev.format('{yyyy}-{mm}-{dd}')); // '2026-07-02' (Thursday)
```
---
## Adding Business Days
### `t.holidays.addBusinessDays(amount, options?)`
Adds or subtracts a specific number of working business days:
```typescript
const orderDate = new Tempo('2026-07-02', { geo: { country: 'US' } });
// Add 3 business days:
// Day 1: Mon July 6
// Day 2: Tue July 7
// Day 3: Wed July 8
const deliveryDate = orderDate.holidays.addBusinessDays(3);
console.log(deliveryDate.format('{yyyy}-{mm}-{dd}')); // '2026-07-08'
// Subtract 3 business days back
const original = deliveryDate.holidays.addBusinessDays(-3);
console.log(original.format('{yyyy}-{mm}-{dd}')); // '2026-07-02'
```
---
## Counting Business Days Between Dates
### `t.holidays.businessDaysUntil(target, options?)`
Calculates the exact number of full business days between two dates:
```typescript
const start = new Tempo('2026-07-02', { geo: { country: 'US' } });
const end = new Tempo('2026-07-08', { geo: { country: 'US' } });
console.log(start.holidays.businessDaysUntil(end)); // 3
console.log(end.holidays.businessDaysUntil(start)); // -3
```
---
## SLA Working Hours Calculation
### `t.holidays.workingHoursUntil(deadline, options?)`
Calculates the exact number of SLA-eligible working hours between two timestamps, taking into account:
- Configurable working day hours (defaults to 9:00 AM to 5:00 PM).
- Exclusion of non-working weekend days.
- Exclusion of regional public holidays and custom non-working days.
```typescript
// Ticket opened on Friday Jan 23, 2026 at 3:00 PM in Australia
const opened = new Tempo('2026-01-23 15:00:00', { geo: { country: 'AU' } });
// Ticket resolved on Tuesday Jan 27, 2026 at 11:00 AM
// (Monday Jan 26 is Australia Day public holiday)
const resolved = new Tempo('2026-01-27 11:00:00', { geo: { country: 'AU' } });
const slaHours = opened.holidays.workingHoursUntil(resolved);
console.log(slaHours); // 4.0 hours
// Breakdown:
// - Friday Jan 23: 15:00 to 17:00 = 2.0 hours
// - Saturday Jan 24: Weekend = 0 hours
// - Sunday Jan 25: Weekend = 0 hours
// - Monday Jan 26: Australia Day = 0 hours
// - Tuesday Jan 27: 09:00 to 11:00 = 2.0 hours
// Total: 4.0 working hours
```
### Custom Work Hour Windows
```typescript
// Custom 8:00 AM to 4:00 PM working day
const hours = opened.holidays.workingHoursUntil(resolved, {
startHour: 8,
endHour: 16,
});
```
---
## Cultural Locale Weekend Awareness
Different countries have different working weeks. For example, in Saudi Arabia (`ar-SA`) and other Middle Eastern jurisdictions, the weekend is Friday and Saturday, and Sunday is a working business day.
Tempo automatically respects the active locale's weekend definition via `tempo.intl.info.weekend`:
```typescript
// Saudi Arabia (ar-SA)
const friday = new Tempo('2026-05-15', { locale: 'ar-SA', geo: { country: 'SA' } });
const sunday = new Tempo('2026-05-17', { locale: 'ar-SA', geo: { country: 'SA' } });
console.log(friday.holidays.isBusinessDay()); // false (Friday is non-working weekend in SA)
console.log(sunday.holidays.isBusinessDay()); // true (Sunday is a standard working day in SA)
```
---
# Document: 9-plugins/holidays.index.md

# @tempo-kit/plugin-holidays
The **Regional Holidays Plugin** provides bank holiday resolution, weekend observation shifts, SLA working hours calculations, and business day arithmetic for [Tempo](https://github.com/magmacomputing/magma/tree/main/packages/tempo).
---
## Key Features
- **Zero-Latency Built-in Calendars**: Instant synchronous holiday calculation for US, Australia, United Kingdom, Canada, Germany, France, Japan, and New Zealand.
- **`t.geo.country` Resolution Cascade**: Automatically resolves national calendars via explicit option, `tempo.geo.country`, `tempo.intl.info.region`, or BCP-47 `tempo.locale`.
- **Global Long-Tail Coverage (100+ Countries)**: Dynamic async preloading via `tempo-fns` with automatic 24-hour TTL caching in runtime storage.
- **SLA Working Hours Calculation**: `t.holidays.workingHoursUntil(deadline)` calculates business hours between dates, taking into account working hour windows, weekends, and regional holidays.
- **Cultural Weekend Awareness**: Automatically respects cultural workweeks (e.g. Friday/Saturday weekend in Middle Eastern locales like `ar-SA`).
---
## Installation
```bash
npm install @tempo-kit/plugin-holidays
```
---
## Quickstart
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
// Australia Day (Jan 26)
const t = new Tempo('2026-01-26', { geo: { country: 'AU' } });
console.log(t.holidays.isHoliday()); // true
console.log(t.holidays.name); // 'Australia Day'
console.log(t.holidays.isBusinessDay()); // false
// Advance to next valid business day past holidays & weekends
const nextWorkDay = t.holidays.nextBusinessDay();
console.log(nextWorkDay.format('{yyyy}-{mm}-{dd}')); // '2026-01-27'
// Calculate SLA working hours between dates
const start = new Tempo('2026-01-23 15:00:00', { geo: { country: 'AU' } }); // Friday 3pm
const deadline = new Tempo('2026-01-27 11:00:00', { geo: { country: 'AU' } }); // Tuesday 11am
console.log(start.holidays.workingHoursUntil(deadline)); // 4.0 hours (2h Fri + 0h Sat/Sun/Mon-Holiday + 2h Tue)
```
---
## Topic Guides
- [Business Days & SLA Arithmetic](./holidays.business-days.md) - Working day calculations, `addBusinessDays`, `nextBusinessDay`, and `workingHoursUntil`.
- [Regional Calendars & Dynamic Preloading](./holidays.regional-calendars.md) - Built-in country rules, state overlays, observation shifts, and async preloading for 100+ countries.
- [Production Use Cases & Architectural Patterns](./holidays.use-cases-and-patterns.md) - Multi-tenant SaaS SLA engines, T+2 trade settlement, payroll rolling conventions, and HR leave accounting.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/holidays.regional-calendars.md
# Regional Calendars & Dynamic Preloading
The **Regional Holidays Plugin** features high-precision offline algorithmic calendars for major world economies and dynamic asynchronous preloading for over 100+ countries.
---
## Supported Offline Built-in Calendars
The following countries are evaluated locally in memory in sub-millisecond execution time with zero network requests:
| Country | Code | Key Holidays & Statutory Rules |
| :--- | :--- | :--- |
| **United States** | `US` | New Year's Day, MLK Day (3rd Mon Jan), Washington's Birthday (3rd Mon Feb), Memorial Day (Last Mon May), Juneteenth, Independence Day, Labor Day (1st Mon Sep), Columbus Day (2nd Mon Oct), Veterans Day, Thanksgiving (4th Thu Nov), Christmas Day. State overlays (e.g. Day After Thanksgiving in `CA`). |
| **Australia** | `AU` | New Year's Day, Australia Day, Good Friday, Easter Monday, ANZAC Day, King's Birthday, Christmas Day, Boxing Day. State overlays for `NSW`, `VIC`, `QLD`, `WA`, `SA`, `TAS`, `ACT`, and `NT`. Melbourne Cup (`VIC`), King's Birthday October rule (`QLD`), dual Christmas/Boxing Day weekend shift rules. |
| **United Kingdom** | `GB` | New Year's Day, Good Friday, Easter Monday, Early May Bank Holiday, Spring Bank Holiday, Summer Bank Holiday, Christmas Day, Boxing Day. Regional overlays for Scotland (`SCT` - 2nd Jan, August Summer Bank, St Andrew's) and Northern Ireland (`NIR` - St Patrick's Day, Battle of the Boyne). |
| **Canada** | `CA` | New Year's Day, Good Friday, Victoria Day, Canada Day, Civic Holiday, Labour Day, National Day for Truth and Reconciliation, Thanksgiving, Remembrance Day, Christmas Day, Boxing Day. Provincial Family Day overlays. |
| **Germany** | `DE` | Neujahr, Karfreitag, Ostermontag, Tag der Arbeit, Christi Himmelfahrt, Pfingstmontag, Fronleichnam, Tag der Deutschen Einheit, Reformationstag, Allerheiligen, Weihnachtstag, Zweiter Weihnachtstag. State holiday overlays across all 16 Bundesländer. |
| **France** | `FR` | Jour de l'An, Lundi de Pâques, Fête du Travail, Victoire 1945, Ascension, Lundi de Pentecôte, Fête Nationale (Bastille Day), Assomption, Toussaint, Armistice 1918, Noël. Alsace-Moselle overlays (Vendredi Saint, Saint-Étienne). |
| **Japan** | `JP` | 元日 (New Year's), 成人の日 (Coming of Age), 建国記念の日 (National Foundation), 天皇誕生日 (Emperor's Birthday), 春分の日 (Vernal Equinox), 昭和の日 (Shōwa Day), 憲法記念日 (Constitution), みどりの日 (Greenery), こどもの日 (Children's), 海の日 (Marine Day), 山の日 (Mountain Day), 敬老の日 (Respect for the Aged), 秋分の日 (Autumnal Equinox), スポーツの日 (Sports Day), 文化の日 (Culture Day), 勤労感謝の日 (Labor Thanksgiving), 振替休日 (Furikae Kyūjitsu substitute holidays). |
| **New Zealand** | `NZ` | New Year's Day, Day after New Year's Day, Waitangi Day, Good Friday, Easter Monday, ANZAC Day, King's Birthday, Matariki (statutory dates), Labour Day, Christmas Day, Boxing Day. Mondayisation shift rules. |
---
## Resolution Hierarchy & Geo Cohesion
When evaluating a holiday or business day, Tempo resolves the effective country and region using the following priority cascade:
1. **Explicit Option**: `t.holidays.isHoliday({ country: 'GB', region: 'SCT' })`
2. **Instance Geolocation**: `t.geo.country` (and `t.geo.region` / `t.geo.state`)
3. **Instance Internationalization**: `tempo.intl.info.region`
4. **Instance Locale**: BCP-47 tag (e.g. `en-AU` → `'AU'`, `fr-CA` → `'CA'`, `ja-JP` → `'JP'`)
5. **Default Fallback**: `'US'`
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
// Geo-aware instance automatically evaluates Australian national and state holidays
const melb = new Tempo('2026-11-03', {
geo: { country: 'AU', region: 'VIC' }
});
console.log(melb.holidays.isHoliday()); // true
console.log(melb.holidays.name); // 'Melbourne Cup Day'
console.log(melb.holidays.country); // 'AU'
console.log(melb.holidays.region); // 'VIC'
```
---
## Dynamic Long-Tail Preloading & Storage Caching
For global applications requiring holiday coverage beyond the 8 built-in economies, the plugin integrates with `tempo-fns` to fetch statutory public holidays for over 100+ countries.
Fetched calendars are stored in runtime storage with a **24-hour TTL** under the `_magma_holidays_` namespace and registered into the in-memory engine, allowing subsequent queries to execute synchronously with zero latency.
### Using Static / Async `Tempo.holidays.preload()`
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
// Preload Italy (IT) for 2026
await Tempo.holidays.preload(2026, 'IT');
// All subsequent synchronous calls now recognize Italian public holidays!
const capodanno = new Tempo('2026-01-01', { geo: { country: 'IT' } });
console.log(capodanno.holidays.isHoliday()); // true
console.log(capodanno.holidays.name); // 'Capodanno'
console.log(capodanno.holidays.isBusinessDay()); // false
```
### Using Instance Method `t.holidays.preload()`
```typescript
const brazil = new Tempo('2026-09-07', { geo: { country: 'BR' } });
// Preloads holidays for Brazil for the instance's year
await brazil.holidays.preload();
console.log(brazil.holidays.isHoliday()); // true (Dia da Independência)
```
---
# Document: 9-plugins/holidays.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
Real-world business systems do not run on simple 24/7 timelines. Banking networks close, financial markets freeze trading on statutory holidays, payroll must disburse before long weekends, and SaaS support contracts enforce strict business-hours response SLAs.
Naive date math—such as adding 48 hours or multiplying days by 86,400,000 milliseconds—causes immediate production bugs: premature SLA breach alerts, miscalculated trade settlement dates, and payroll disputes.
The `@tempo-kit/plugin-holidays` plugin gives Tempo instances native awareness of public holidays, weekend observation shifts, and business-day arithmetic.
---
## 1. Multi-Tenant SaaS SLA Resolution Engine
In B2B SaaS platforms (such as Zendesk, Jira, or ServiceNow architectures), customer support contracts specify service level agreements (SLAs) based on **working business hours in the client's jurisdiction**:
- *"Tier-1 critical incidents acknowledged within 4 business hours."*
- *"Standard tickets resolved within 2 business days."*
If a customer in the UK logs a ticket at 4:30 PM on the Friday before a Bank Holiday, a naive `+ 48h` timer will flag an SLA breach on Sunday afternoon. With `tempo-plugin-holidays`, the SLA engine respects the client's local country and statutory holidays automatically.
### Architecture Pattern
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
interface CustomerOrganization {
id: string;
name: string;
country: string; // e.g. 'US', 'GB', 'AU', 'DE'
region?: string; // e.g. 'NSW', 'VIC', 'CA'
slaBusinessDays: number;
}
export function computeSlaDeadline(
ticketCreatedAt: string,
customer: CustomerOrganization
): { deadline: Tempo; isRiskOfBreach: boolean; remainingWorkingHours: number } {
// 1. Initialize ticket Tempo with the customer's geographic context
const ticketTime = new Tempo(ticketCreatedAt, {
geo: { country: customer.country, region: customer.region }
});
// 2. Add customer's contracted business days (skips holidays + weekends)
const deadline = ticketTime.holidays.addBusinessDays(customer.slaBusinessDays);
// 3. Compute remaining working hours (standard 9am - 5pm business day)
const now = new Tempo('now', {
geo: { country: customer.country, region: customer.region }
});
const remainingWorkingHours = now.holidays.workingHoursUntil(deadline, {
startHour: 9,
endHour: 17
});
return {
deadline,
isRiskOfBreach: remainingWorkingHours < 4,
remainingWorkingHours
};
}
// Example: UK Customer creates ticket on Friday before Summer Bank Holiday
const ticket = computeSlaDeadline('2026-08-28 16:30:00', {
id: 'org_enterprise_uk',
name: 'Acme UK Ltd',
country: 'GB',
slaBusinessDays: 2
});
// Friday + 2 business days (skipping Sat, Sun, and Bank Holiday Monday Aug 31):
// Resolves accurately to Wednesday, Sep 2, 2026
console.log(ticket.deadline.format('{yyyy}-{mm}-{dd}')); // '2026-09-02'
```
---
## 2. Financial T+2 Settlement & Trade Value Dates
In securities trading, currency exchange (FX), and treasury management, trades settle on **T+2** (Trade Date + 2 Business Days). If a trade occurs on Thursday before Good Friday, financial clearing houses (Fedwire, TARGET2, CHAPS) are closed on both Good Friday and Easter Monday.
Settlement cannot occur until the second valid banking day following the trade.
```typescript
import { Tempo } from 'tempo-kit';
import { addBusinessDays, isBusinessDay } from '@tempo-kit/plugin-holidays';
export function calculateTradeSettlement(tradeDateIso: string, marketCountry: string): {
tradeDate: string;
settlementDate: string;
interveningHolidaysSkipped: number;
} {
const trade = new Tempo(tradeDateIso, { geo: { country: marketCountry } });
// Ensure trade was executed on a valid market day
if (!trade.holidays.isBusinessDay()) {
throw new Error(`Trade executed on non-clearing day: ${trade.format('{yyyy}-{mm}-{dd}')}`);
}
// T+2 Settlement Date (skips exchange holidays & weekends)
const settlement = trade.holidays.addBusinessDays(2);
return {
tradeDate: trade.format('{yyyy}-{mm}-{dd}'),
settlementDate: settlement.format('{yyyy}-{mm}-{dd}'),
interveningHolidaysSkipped: trade.holidays.businessDaysUntil(settlement)
};
}
// Thursday April 2, 2026 (day before Good Friday on the London Stock Exchange)
const trade = calculateTradeSettlement('2026-04-02', 'GB');
// In the UK, April 3 (Good Friday) and April 6 (Easter Monday) are bank holidays.
// April 4-5 is the weekend:
// T+1 = Tuesday April 7, T+2 = Wednesday April 8
console.log(trade.settlementDate); // '2026-04-08'
```
---
## 3. Payroll & Automated Invoicing (Preceding vs. Following Conventions)
When automated billing or employee salary disbursement is scheduled for a fixed calendar date (e.g. the 1st or 15th of the month), banking regulations require applying a business day rolling convention if that date lands on a weekend or public holiday:
- **Preceding Business Day (Standard Payroll)**: Employees must be paid *before* the holiday weekend (e.g. Wednesday Dec 31 if Jan 1 is New Year's Day).
- **Following Business Day (Invoicing & Direct Debits)**: Payments are drawn on the next banking day after the holiday.
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
type RollConvention = 'PRECEDING' | 'FOLLOWING';
export function resolvePaymentRunDate(
scheduledDateIso: string,
country: string,
convention: RollConvention
): Tempo {
const target = new Tempo(scheduledDateIso, { geo: { country } });
// If already a valid working day, process on scheduled date
if (target.holidays.isBusinessDay()) {
return target;
}
// Apply banking adjustment convention
return convention === 'PRECEDING'
? target.holidays.prevBusinessDay()
: target.holidays.nextBusinessDay();
}
// 1. Payroll Run: Jan 1, 2026 (New Year's Day - US Bank Holiday)
const payrollRun = resolvePaymentRunDate('2026-01-01', 'US', 'PRECEDING');
console.log(payrollRun.format('{yyyy}-{mm}-{dd}')); // '2025-12-31' (Wednesday)
// 2. Direct Debit Draw: July 4, 2026 (US Independence Day - Saturday)
// Observed holiday is Friday July 3; next banking business day is Monday July 6
const debitRun = resolvePaymentRunDate('2026-07-04', 'US', 'FOLLOWING');
console.log(debitRun.format('{yyyy}-{mm}-{dd}')); // '2026-07-06' (Monday)
```
---
## 4. HR Leave Balance & Vacation Day Accounting
When employees submit annual leave requests, naive calendar day subtraction calculates `endDate - startDate + 1`. This incorrectly charges employees vacation balance for weekends and statutory bank holidays occurring during their time off.
Using `businessDaysUntil` or `isBusinessDay()` ensures fair, legally compliant leave deductions.
```typescript
import '@tempo-kit/plugin-holidays/install';
import { Tempo } from 'tempo-kit';
export function calculateLeaveDeduction(
startDateIso: string,
endDateIso: string,
country: string
): { totalCalendarDays: number; chargeableLeaveDays: number; holidaysIncluded: string[] } {
const start = new Tempo(startDateIso, { geo: { country } });
const end = new Tempo(endDateIso, { geo: { country } });
const holidaysIncluded: string[] = [];
let chargeableDays = 0;
let current = start;
while (current.epoch.ms <= end.epoch.ms) {
if (current.holidays.isHoliday()) {
holidaysIncluded.push(`${current.format('{yyyy}-{mm}-{dd}')}: ${current.holidays.name}`);
} else if (current.holidays.isBusinessDay()) {
chargeableDays++;
}
current = current.add({ day: 1 });
}
return {
totalCalendarDays: Math.round((end.epoch.ms - start.epoch.ms) / 86_400_000) + 1,
chargeableLeaveDays: chargeableDays,
holidaysIncluded
};
}
// Employee books Christmas break in Australia (Dec 24, 2026 to Jan 4, 2027)
const leave = calculateLeaveDeduction('2026-12-24', '2027-01-04', 'AU');
console.log(leave.totalCalendarDays); // 12 days
console.log(leave.chargeableLeaveDays); // 5 working days deducted
console.log(leave.holidaysIncluded);
// [
// '2026-12-25: Christmas Day',
// '2026-12-28: Boxing Day (Observed)',
// '2027-01-01: New Year\'s Day'
// ]
```
---
## 5. Corporate Calendar Overlays & Floating Shutdowns
Enterprises frequently observe non-statutory company closures in addition to national holidays:
- Year-end corporate shutdowns (e.g. December 24 through January 2).
- Annual company hackathons or global mental health recharge days.
- Regional warehouse maintenance downtime.
`tempo-plugin-holidays` supports **`customHolidays`**, seamlessly blending proprietary enterprise closure dates into the national holiday calendar without modifying runtime source files:
```typescript
import { Tempo } from 'tempo-kit';
import { isBusinessDay, addBusinessDays } from '@tempo-kit/plugin-holidays';
const corporateCalendar = {
country: 'US',
customHolidays: [
'2026-11-27', // Company Day after Thanksgiving
'2026-12-24', // Christmas Eve Corporate Closure
'2026-12-31' // New Year's Eve Corporate Closure
]
};
const thanksgivingThursday = new Tempo('2026-11-26');
// Friday Nov 27 is a normal federal business day in the US,
// but our custom enterprise overlay treats it as non-working:
console.log(isBusinessDay(thanksgivingThursday.add({ day: 1 }), corporateCalendar)); // false
// Advances past Thanksgiving (Thu), Company Day (Fri), and the Weekend to Monday:
const nextActiveWorkDay = addBusinessDays(thanksgivingThursday, 1, corporateCalendar);
console.log(nextActiveWorkDay.format('{yyyy}-{mm}-{dd}')); // '2026-11-30' (Monday)
```
---
## 6. Zero-Latency Synchronous Resolution
All standard country calculations (including Easter Computus and observed floating holiday algorithms) execute **100% synchronously in pure memory**.
There are no network round-trips to third-party government APIs, no rate limits, and zero asynchronous latency—making `tempo-plugin-holidays` suitable for high-throughput batch transaction pipelines, bulk database ETL jobs, and millisecond-sensitive order routing engines.
---
# Document: 9-plugins/ntp.algorithms-and-precision.md
# Cristian's Algorithm & Precision Engineering
`@tempo-kit/plugin-ntp` implements Flaviu Cristian's probabilistic clock synchronization algorithm over HTTP(S) with modern performance enhancements: high-resolution monotonic baselines, sub-millisecond `Server-Timing` headers, statistical jitter rejection, and Exponential Moving Average (EMA) smoothing.
---
## 1. Cristian's Algorithm Over HTTP
When a client queries a time endpoint over HTTP:
1. **$T_0$**: Client records its local timestamp immediately before sending the HTTP request.
2. **$T_{\text{server}}$**: Server records the current atomic timestamp when handling the request.
3. **$T_1$**: Client records its local timestamp immediately upon receiving the response.
```
Client Server
| |
|--- HTTP Request (T0) ----------->|
| | (T_server)
|<-- HTTP Response (T1) -----------|
| |
```
### Round-Trip Time (RTT)
$$\text{RTT} = T_1 - T_0$$
### Estimated Server Timestamp at Reception ($T_1$)
Assuming symmetrical network latency (outbound delay $\approx$ inbound delay $\approx \text{RTT} / 2$):
$$T_{\text{estimated}} = T_{\text{server}} + \frac{\text{RTT}}{2}$$
### Clock Drift Offset ($\theta$)
$$\theta = T_{\text{estimated}} - T_1 = T_{\text{server}} - \frac{T_0 + T_1}{2}$$
### Uncertainty Window ($\pm E$)
The maximum theoretical clock error bounds are:
$$E = \pm \frac{\text{RTT}}{2}$$
---
## 2. Sub-Millisecond Precision via `Server-Timing`
Standard HTTP `Date` headers have a coarse **1-second resolution** (`Date: Fri, 02 Oct 2026 06:15:00 GMT`), which introduces up to $\pm 500\text{ms}$ of quantization jitter.
`tempo-plugin-ntp` automatically prioritizes sub-millisecond timestamps delivered via the standard HTTP `Server-Timing` header:
```http
HTTP/1.1 200 OK
Date: Fri, 02 Oct 2026 06:15:00 GMT
Server-Timing: clock=1727856900123.45
Content-Type: application/json
```
If `Server-Timing` contains a `clock=...`, `server_time=...`, or `epoch=...` metric, the plugin parses the high-precision floating-point epoch timestamp, achieving sub-millisecond synchronization accuracy.
---
## 3. Statistical Jitter Rejection & Filtering
Transient network spikes (e.g., cell tower handoffs, packet retries) can cause anomalous RTT measurements. If an asynchronous network delay is heavily skewed in one direction, the symmetrical assumption ($\text{RTT}/2$) breaks down.
The plugin protects against skew distortion using **RTT Threshold Filtering**:
- Samples exceeding the configurable `maxAcceptableRttMs` threshold (default: `1000ms`) are immediately discarded.
- High-latency or asymmetrical network spikes are rejected without updating the active drift calibration.
---
## 4. Exponential Moving Average (EMA) Smoothing
Rather than jumping the clock offset instantaneously upon every sync sample (which could cause time to appear to skip or stutter), new samples are smoothed into the running offset using an Exponential Moving Average:
$$\theta_{t} = \alpha \cdot \theta_{\text{sample}} + (1 - \alpha) \cdot \theta_{t-1}$$
Where:
- $\alpha \in (0, 1]$ is the smoothing factor (default: `0.3`).
- On the very first sample ($t=0$), $\theta_0 = \theta_{\text{sample}}$ to establish immediate baseline calibration.
---
## 5. Monotonic Time Progression with Zero O(N) Overhead
Once calibrated, calling `Tempo.ntp.now()` is a purely synchronous, $O(1)$ calculation:
$$\text{Current Server Time} = \text{Date.now()} + \theta$$
Because the offset $\theta$ is continuously maintained in memory, your application can invoke `Tempo.ntp.now()` millions of times per second inside render loops or high-frequency calculation pipelines with zero performance penalty.
---
# Document: 9-plugins/ntp.index.md

# @tempo-kit/plugin-ntp
A lightweight, high-precision Community plugin for the [Tempo](https://github.com/magmacomputing/magma) ecosystem that provides **client-server network time synchronization** and **monotonic clock drift compensation** using Cristian's algorithm, HTTP `Server-Timing` headers, jitter rejection, and Exponential Moving Average (EMA) smoothing.
---
## Key Features
- **Cristian's Algorithm**: Computes client clock offset from round-trip time (`Δ = T_server - (T_client + RTT / 2)`) without altering the OS clock.
- **Sub-Millisecond Headers**: Reads `Server-Timing: clock=...` with automatic fallback to the standard HTTP `Date` header.
- **Jitter Rejection & EMA Smoothing**: Discards high-latency samples and smooths drift with an Exponential Moving Average.
- **Passive Calibration**: Optionally intercepts `fetch` responses from trusted origins to calibrate with zero extra requests.
- **Synchronous Calibrated Time**: `Tempo.ntp.now()` returns true server-aligned time with no `await`.
- **Universal HTTP Baseline**: Runs identically in browsers, Node.js, Bun, Deno, and Cloudflare Workers.
---
## Installation
```bash
npm install @tempo-kit/plugin-ntp
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { NtpPlugin } from '@tempo-kit/plugin-ntp';
// 1. Install the plugin with target server endpoint
Tempo.use(NtpPlugin, {
server: '/api/time', // Default time synchronization endpoint
syncInterval: '15m', // Automatic periodic re-sync
interceptFetch: ['https://api.mycorp.com', '/api/'] // Passively calibrate only on trusted endpoints
});
// 2. Perform an initial sync
await Tempo.ntp.sync();
// 3. Query true calibrated atomic time (100% synchronous!)
const atomicNow = Tempo.ntp.now();
console.log(`True UTC Time: ${atomicNow.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}')}`);
console.log(`Measured Drift Offset: ${Tempo.ntp.offset}ms`);
console.log(`Uncertainty Window: ±${Tempo.ntp.drift.uncertaintyMs}ms`);
```
### Configuration Options (`NtpSyncOptions`)
| Option | Type | Default | Description |
|---|---|---|---|
| `server` | `string` | `undefined` | Dedicated HTTP time endpoint returning `Date` or `Server-Timing: clock=`. |
| `syncInterval` | `string \| number` | `undefined` | Periodic re-sync interval (e.g. `'15m'`, `'1h'`, or ms). |
| `interceptFetch` | `boolean \| string \| string[] \| RegExp \| Function` | `false` | Passively sniff headers from application `fetch` calls. Can be `true` (sniff all), a path prefix, origin array, regex, or predicate. |
| `trustedOrigins` | `string \| string[] \| RegExp \| Function` | `undefined` | Whitelist of allowed origins or URL prefixes to sample when `interceptFetch: true` is enabled. |
| `maxAcceptableRttMs` | `number` | `1000` | Maximum round-trip time threshold in milliseconds. Jittery or delayed requests are discarded. |
| `alpha` | `number` | `0.3` | Exponential Moving Average (EMA) smoothing factor between `0.0` and `1.0`. |
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-ntp/install';
// Synchronize and query true calibrated server time
await Tempo.ntp.sync();
const now = Tempo.ntp.now();
```
---
## API Reference
### `Tempo.ntp.now(timeZone?: string): Tempo`
Synchronously returns a new `Tempo` instance anchored to the calibrated atomic server timestamp.
### `Tempo.ntp.sync(endpoint?: string): Promise`
Asynchronously sends a lightweight HTTP request to measure Round-Trip Time (RTT) and updates the Exponential Moving Average (EMA) drift offset.
### `Tempo.ntp.offset: number`
Getter returning the current clock drift offset in milliseconds (`serverTime = localTime + offset`).
### `Tempo.ntp.drift: ClockDriftState`
Getter returning the full telemetry state snapshot:
```typescript
interface ClockDriftState {
readonly offsetMs: number;
readonly uncertaintyMs: number;
readonly lastSyncedAt: number;
readonly sampleCount: number;
}
```
### `Tempo.ntp.isCalibrated: boolean`
Getter indicating whether at least one valid synchronization sample has been successfully processed.
### `Tempo.ntp.reset(): void`
Resets the calibration state and sample count back to zero.
### `tempo.toNtpTime(): Tempo`
Instance method that returns a new `Tempo` instance offset by the current NTP clock drift.
---
## Topic Guides
- [Cristian Algorithm & Precision Specs](./ntp.algorithms-and-precision.md) - RTT offset mathematics, `Server-Timing` precision, jitter filtering, and EMA smoothing.
- [Ticker Integration & Atomic Clocks](./ntp.ticker-integration.md) - Drift-compensated continuous execution loops with `@tempo-kit/plugin-ticker` (`ntp: true`).
- [Production Use Cases & Architectural Patterns](./ntp.use-cases-and-patterns.md) - Financial countdowns, live auctions, passive calibration, distributed logging, and TOTP authentication.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/ntp.ticker-integration.md
# Production Use Cases & Architectural Patterns
Client devices in modern web and mobile environments suffer from unpredictable clock skew. Users frequently travel across time zones, adjust system clocks manually, run outdated CMOS batteries, or experience clock throttling during laptop sleep cycles.
The `@tempo-kit/plugin-ntp` plugin provides industrial-grade time consistency by locking Tempo instances to true atomic server time.
---
## 1. Anti-Cheat Live Countdowns & Flash Sales
In live auctions, ticket drops, e-commerce flash sales, and sports betting, user interfaces rely on countdown timers. If a client manipulates their system clock backwards or forwards, standard `new Date()` or `Date.now()` timers will display false deadlines or prematurely disable bidding buttons.
### The Problem with Uncalibrated Timers
```typescript
// ⚠️ VULNERABLE: If user sets their OS clock forward 10 minutes,
// the countdown immediately hits 00:00:00 and locks them out.
const timeLeftMs = saleEnd.getTime() - Date.now();
```
### The Calibrated Solution
`Tempo.ntp.now()` evaluates the true atomic timeline with zero asynchronous overhead:
```typescript
import { Tempo } from 'tempo-kit';
import { NtpPlugin } from '@tempo-kit/plugin-ntp';
Tempo.use(NtpPlugin, { server: '/api/v1/time' });
// Ensure calibration is established
await Tempo.ntp.sync();
function getAuctionRemainingTime(auctionEnd: Tempo) {
// Synchronous, true server time calculation
const trueNow = Tempo.ntp.now();
if (trueNow.epoch.ms >= auctionEnd.epoch.ms) {
return { isExpired: true, remainingMs: 0 };
}
return {
isExpired: false,
remainingMs: auctionEnd.epoch.ms - trueNow.epoch.ms
};
}
```
---
## 2. Zero-Overhead Passive Calibration (`interceptFetch`) & Origin Hardening
Running dedicated background ping loops to sync time can waste mobile battery and add server load. `tempo-plugin-ntp` solves this via **Passive Fetch Interception**.
When passive fetch interception is enabled, the plugin inspects the HTTP response's `Server-Timing` or standard `Date` headers and recalculates drift alongside normal application data fetching, without issuing a single extra HTTP call.
### Trust Boundaries & Origin Hardening
If your application makes network calls to external third parties (e.g., payment gateways, external webhooks, analytics, or user-supplied URLs), you should **never** allow third-party servers to alter your application's shared clock offset.
To enforce strict boundary security, `interceptFetch` supports origin filtering via URL prefixes, origin whitelists, regex patterns, or custom predicates:
```typescript
import { Tempo } from 'tempo-kit';
import { NtpPlugin } from '@tempo-kit/plugin-ntp';
// Option A: Pass trusted origins/prefixes directly to interceptFetch
Tempo.use(NtpPlugin, {
interceptFetch: ['https://api.mycompany.com', '/api/'],
alpha: 0.2
});
// Option B: Enable interceptFetch with an explicit trustedOrigins whitelist
Tempo.use(NtpPlugin, {
interceptFetch: true,
trustedOrigins: ['https://api.mycompany.com', '/api/']
});
// Option C: Pattern matching via regular expression or predicate function
Tempo.use(NtpPlugin, {
interceptFetch: (url) => url.startsWith('/api/') || url.includes('trusted-internal.com')
});
```
### Production Ingestion Flow
```typescript
// 1. Trusted first-party call: passively recalibrates Tempo.ntp clock offset
const user = await fetch('/api/user/profile').then(r => r.json());
console.log(`Calibrated drift: ${Tempo.ntp.offset}ms (Sample #${Tempo.ntp.drift.sampleCount})`);
// 2. Untrusted third-party call: response headers are safely ignored
await fetch('https://untrusted-analytics.com/event', { method: 'POST' });
// Clock offset remains calibrated exclusively by trusted first-party responses
```
---
## 3. Distributed Telemetry & Client Log Correlation
When debugging production issues across thousands of distributed clients, correlating frontend crash events with backend API logs is notoriously difficult because client timestamps are untrustworthy.
Using NTP-anchored logging guarantees that client log records share the backend's exact UTC epoch timeline:
```typescript
import { Tempo } from 'tempo-kit';
export function sendTelemetryLog(eventType: string, payload: Record) {
const payloadWithTrueTimestamp = {
event: eventType,
data: payload,
// True UTC timestamp matching server logs
serverTimeUtc: Tempo.ntp.now().format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}'),
localTimeUtc: new Tempo().format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}.{ms}'),
measuredDriftMs: Tempo.ntp.offset,
uncertaintyMs: Tempo.ntp.drift.uncertaintyMs
};
navigator.sendBeacon('/api/telemetry', JSON.stringify(payloadWithTrueTimestamp));
}
```
---
## 4. Time-Based One-Time Passwords (TOTP / 2FA)
TOTP algorithms (RFC 6238) compute authentication codes using 30-second epoch time slices ($T_0 = \lfloor \text{epochMs} / 30000 \rfloor$). If a client device's clock drifts by more than 30–60 seconds, generated 2FA tokens will be rejected by the server as invalid.
```typescript
import { Tempo } from 'tempo-kit';
function getTotpTimeStep(): number {
// Always derive 30s bucket from calibrated atomic time
const calibratedEpoch = Tempo.ntp.now().epoch.ms;
return Math.floor(calibratedEpoch / 30000);
}
```
---
## 5. Drift Convergence & High-Frequency Queries
Once calibrated, `Tempo.ntp.now()` synchronously calculates `Date.now() + offset`.
Because drift is continuously smoothed via Exponential Moving Average (EMA) and maintained in-memory, high-frequency renders, animation frames, and interval loops can query true server time millions of times per second with zero network or asynchronous overhead.
---
# Document: 9-plugins/roman.calendar-mechanics.md
# Classical Fasti & Lunar Anchors
The Roman calendar system (*Fasti*) operated on astronomical and liturgical principles distinct from modern sequential month numbering. Rather than numbering days sequentially from 1 to 31, Roman dates were computed by counting backwards from three fixed lunar anchor points.
---
## The Three Lunar Anchor Points
Every Roman month contains three primary anchor points rooted in the lunar calendar of the early Roman Republic:
1. **Kalends** (*Kalendae*):
- Always occurs on the **1st** day of every month.
- Originally marked the new crescent moon (*calare*, to call out or announce).
- In Latin syntax, dates on the Kalends use the feminine plural Ablative: *Kalendis*.
2. **Nones** (*Nonae*):
- Originally coincided with the First Quarter moon (nine days before the Ides, counting inclusively).
- Occurs on the **7th day** in the four long "MOM-J" months: **March**, **October**, **May**, and **July**.
- Occurs on the **5th day** in all remaining eight months.
- In Latin syntax: *Nonis* (Ablative).
3. **Ides** (*Idus*):
- Originally coincided with the Full Moon.
- Occurs on the **15th day** in "MOM-J" months (March, October, May, July).
- Occurs on the **13th day** in all other months.
- In Latin syntax: *Idibus* (Ablative).
```
MOM-J Months (March, October, May, July):
Day 1: Kalends (Kalendis)
Day 7: Nones (Nonis)
Day 15: Ides (Idibus)
All Other Months (Jan, Feb, Apr, Jun, Aug, Sep, Nov, Dec):
Day 1: Kalends (Kalendis)
Day 5: Nones (Nonis)
Day 13: Ides (Idibus)
```
---
## Inclusive Backward Counting (*Ante Diem*)
Romans did not count forward from the beginning of the month; they counted backwards towards the next upcoming anchor point:
1. **Exact Anchor Days (`relation: 'on'`)**:
Expressed in the Ablative case without prefixes:
- March 15 $\implies$ *Idibus Martiis* (`Id. Mart.`)
- January 1 $\implies$ *Kalendis Januariis* (`Kal. Jan.`)
2. **The Preceding Day (`relation: 'pridie'`)**:
The day immediately preceding an anchor uses the adverb *Pridie* followed by the anchor and month in the Accusative:
- March 14 $\implies$ *Pridie Idus Martias* (`Prid. Id. Mart.`)
- October 31 $\implies$ *Pridie Kalendas Novembres* (`Prid. Kal. Nov.`)
3. **Inclusive Counting (`relation: 'ante_diem'`)**:
All other days count inclusively, meaning both the starting date and the anchor date itself are counted. The formula for days prior to the Nones or Ides is:
$$\text{Count} = \text{AnchorDay} - \text{Day} + 1$$
For example, March 12 before the March 15 Ides:
$$15 - 12 + 1 = 4 \implies \text{\textit{ante diem IV Idus Martias}}$$
4. **Dates Past the Ides**:
Once the Ides of a month passes, dates are calculated backwards from the **Kalends of the following month**:
$$\text{Count} = \text{DaysInMonth} - \text{Day} + 2$$
For example, October 16 (in a 31-day month) before the November 1 Kalends:
$$31 - 16 + 2 = 17 \implies \text{\textit{ante diem XVII Kalendas Novembres}}$$
---
## Leap Year Intercalation: The Bissextile Day
Under the Julian calendar reform (45 BCE), an intercalary day was added every four years in February. Rather than appending an extra day at the end of the month (which would have disturbed the religious festivals aligned to the end of February, such as the *Terminalia* on February 23), the Romans doubled the **sixth day before the March Kalends** (*ante diem sextum Kalendas Martias*):
- **February 24**: *ante diem bis sextum Kalendas Martias* (the doubled "second sixth day")
- **February 25**: *ante diem sextum Kalendas Martias* (the sixth day)
- **February 29**: *Pridie Kalendas Martias*
This practice gave rise to the term **Bissextile Year** (*annus bissextilis*). `@tempo-kit/plugin-roman` faithfully reproduces this classical intercalation by default (`{ bissextile: true }`):
```typescript
const leapDay = new Tempo('2024-02-24');
const res = leapDay.toRomanClassical();
console.log(res.isBissextile); // true
console.log(res.latin); // "ante diem bis sextum Kalendas Martias"
console.log(res.shortLatin); // "a.d. bis VI Kal. Mart."
```
---
## Ab Urbe Condita (AUC) Calculations
Years were traditionally recorded by naming the presiding Roman Consuls. Historians also reckoned time **Ab Urbe Condita** ("from the founding of the City"), traditionally fixed to 753 BCE by the scholar Marcus Terentius Varro.
The plugin provides exact mathematical conversions between astronomical years, Common Era years, and AUC:
1. **Common Era ($Y \ge 1$)**:
$$\text{AUC} = Y + 753$$
- $1 \text{ CE} \implies 754 \text{ AUC}$
- $2026 \text{ CE} \implies 2779 \text{ AUC}$
2. **Before Common Era ($Y_{\text{BCE}} \ge 1$)**:
$$\text{AUC} = 754 - Y_{\text{BCE}}$$
- $44 \text{ BCE} \implies 754 - 44 = 710 \text{ AUC}$
- $753 \text{ BCE} \implies 754 - 753 = 1 \text{ AUC}$
3. **Astronomical Years ($Y \le 0$)**:
Continuous astronomical year numbering ($0 = 1\text{ BCE}$, $-43 = 44\text{ BCE}$) follows a single continuous linear relation:
$$\text{AUC} = Y + 753$$
---
## Consular Chronology (*Fasti Consulares*)
In everyday Roman civic and legal life, years were designated by naming the two ordinary consuls (*consules ordinarii*) who entered office on the Kalends of January:
$$\text{\textit{Cicerone et Antonio consulibus}} \implies 63 \text{ BCE} \text{ (astronomical } -62)$$
The plugin includes historical consular dating. By default, the core bundle provides a curated seed catalog of landmark years (e.g. 509 BCE founding, 63 BCE Cicero, 44 BCE Caesar, 541 CE Basilius).
To access the complete historical catalog spanning all 1,050 years from the founding of the Roman Republic in 509 BCE (`-508`) through the final recorded consul in the West in 541 CE (`541`), import the `./consuls` subpath:
```typescript
import '@tempo-kit/plugin-roman/consuls';
const idesMarch44 = new Tempo('-000043-03-15');
console.log(idesMarch44.consuls);
// "C. Julio Caesare V, M. Antonio coss."
```
---
## See Also
- **[Use Cases & Production Patterns](./roman.use-cases-and-patterns.md)**: Applied historical, academic, and numismatic workflows.
---
# Document: 9-plugins/roman.index.md

# @tempo-kit/plugin-roman
A lightweight, zero-dependency Community plugin for the [Tempo](https://github.com/magmacomputing/magma) ecosystem that provides **classical Roman calendar arithmetic** (*Kalends*, *Nones*, *Ides*, *Ante Diem*), **leap year bissextile handling**, and **AUC (*Ab Urbe Condita*) year conversions**.
---
## Key Features
- **Classical Anchors**: Resolves any date to its Roman *Kalends*, *Nones*, or *Ides* anchor, including *Pridie* and inclusive *ante diem* counts.
- **Latin Phrasing**: Emits full (`ante diem XVII Kalendas Novembres`) and abbreviated (`a.d. XVII Kal. Nov.`) forms with correct Ablative/Accusative declensions.
- **Bissextile Day**: Reproduces the classical leap-year doubling of the sixth day before the March Kalends (`a.d. bis VI Kal. Mart.`).
- **AUC Year Reckoning**: Bidirectional *Ab Urbe Condita* conversion for CE, BCE, and astronomical years.
- **Classical Latin Parser**: Robust parser recognizing arbitrary Latin expressions (e.g. `a.d. IV Id. Mart. 710 AUC`, `Idibus Martiis Cicerone coss.`) with calendar validation.
- **Fasti Consulares (509 BCE–541 CE)**: Historical catalog of Roman Consuls with Latin ablative absolute (`coss.`) formatting and searching (full catalog via `./consuls`, with landmark years in core).
- **Lossless Round-Trips**: `Tempo.roman.fromClassical()` maps any classical date back to its exact calendar day.
- **Immutable Results**: Every structured result is frozen; zero runtime dependencies beyond Tempo.
---
## Installation & Import Paths
```bash
npm install @tempo-kit/plugin-roman
```
### Choose Your Import Path
| Import Path | Minified Size | What's Included |
| :--- | :--- | :--- |
| `import '@tempo-kit/plugin-roman/install'` | **~15 KB** | Full Roman calendar arithmetic, Latin phrasing/parsing, AUC conversions, and ~20 landmark consul years (Cicero, Caesar, Brutus, Basilius). Auto-installs plugin. |
| `import '@tempo-kit/plugin-roman/consuls'` | **~70 KB** | Batteries-included: full Roman calendar plugin + complete **1,050-year Fasti consulares** catalog (509 BCE–541 CE). Auto-installs plugin in one import. |
| `import { RomanPlugin } from '@tempo-kit/plugin-roman'` | **~15 KB** | Core plugin definition for explicit installation via `Tempo.use(RomanPlugin)`. |
---
## Quickstart
### Option A: Lean Core Plugin (Zero-Boilerplate)
```typescript
import '@tempo-kit/plugin-roman/install';
import { Tempo } from 'tempo-kit';
// 1. Compute classical Roman date and Latin phrasing
const today = new Tempo('2026-10-16');
const classical = today.toRomanClassical();
console.log(`Roman Date: ${classical.latin}`); // "ante diem XVII Kalendas Novembres"
console.log(`Abbreviated: ${classical.shortLatin}`);// "a.d. XVII Kal. Nov."
console.log(`Anchor: ${classical.anchor}`); // "Kalends"
console.log(`Year AUC: ${today.auc} AUC`); // 2779 AUC
// 2. Ides of March (44 BCE = astronomical year -43)
const idesOfMarch = new Tempo('-000043-03-15');
console.log(idesOfMarch.toRomanClassical().latin); // "Idibus Martiis"
console.log(idesOfMarch.toAUC()); // 710 (AUC)
console.log(idesOfMarch.consuls); // "C. Julio Caesare V, M. Antonio coss."
// 3. Leap year bissextile day (February 24 in a leap year)
const leapDay = new Tempo('2024-02-24');
console.log(leapDay.toRomanClassical().latin); // "ante diem bis sextum Kalendas Martias"
console.log(leapDay.toRomanClassical().shortLatin); // "a.d. bis VI Kal. Mart."
// 4. Classical Latin Date Parsing
const parsed = Tempo.roman.parse('a.d. IV Id. Mart. 710 AUC');
console.log(parsed.format('{yyyy}-{mm}-{dd}')); // "-000043-03-12" (March 12, 44 BCE)
```
### Option B: Full Consular Fasti (Single Import)
To access the complete historical Fasti consulares spanning all 1,050 years from 509 BCE through 541 CE:
```typescript
import '@tempo-kit/plugin-roman/consuls';
import { Tempo } from 'tempo-kit';
// Auto-installs RomanPlugin AND populates all 1,050 consular years
const trajanYear = new Tempo('0100-01-01');
console.log(trajanYear.consuls);
// "Imp. Caesare Nerva Trajano Augusto III, Sex. Julio Frontino III coss."
console.log(trajanYear.format('{roman:consul}'));
// "Imp. Caesare Nerva Trajano Augusto III, Sex. Julio Frontino III coss."
```
### Option C: Explicit Plugin Registration
```typescript
import { Tempo } from 'tempo-kit';
import { RomanPlugin } from '@tempo-kit/plugin-roman';
Tempo.use(RomanPlugin);
```
---
## API Reference
### `tempo.toRomanClassical(options?: RomanCalculationOptions): ClassicalRomanDate`
Instance method calculating the complete classical Roman calendar descriptor for the instance date. Returns an immutable, frozen `ClassicalRomanDate` object.
### `tempo.toAUC(): number`
Instance method returning the year reckoned Ab Urbe Condita (AUC).
### `tempo.auc: number`
Getter returning the year in AUC.
### `Tempo.roman.toClassical(date, options?): ClassicalRomanDate`
Static calculation function resolving `Tempo`, native JavaScript `Date`, or plain `{ year, month, day }` objects into a frozen `ClassicalRomanDate`.
### `Tempo.roman.fromClassical(anchor, anchorMonth, anchorYear, relation, count?, isBissextile?, isJulian?): { year, month, day }`
Resolves classical Roman calendar anchor parameters back to modern calendar coordinates.
### `Tempo.roman.parse(input: string, options?: RomanParseOptions): Tempo`
Parses a natural classical Latin date string (e.g. `'a.d. IV Id. Mart. 710 AUC'` or `'Idibus Martiis Cicerone coss.'`) directly into a `Tempo` instance.
### `Tempo.roman.parseDate(input: string, options?: RomanParseOptions): ParsedRomanDate`
Parses a Latin date string into calendar coordinates (`{ year, month, day, auc, classical }`) without constructing an instance.
### `Tempo.roman.getConsuls(year: number): readonly string[] | undefined`
Retrieves the eponymous Roman consuls for an astronomical year from the Fasti consulares (509 BCE–541 CE).
### `Tempo.roman.formatConsuls(year: number, style?: 'ablative' | 'nominative'): string | undefined`
Renders the eponymous consuls into a classical Latin dating formula (e.g. `"M. Tullio Cicerone, C. Antonio Hybrida coss."`).
### `Tempo.roman.findConsuls(query: string): ConsularPair[]`
Performs a substring search against the Fasti consulares and returns matching years and names.
### `Tempo.roman.yearToAuc(year: number, era?: 'CE' | 'BCE'): number`
Converts an astronomical year (or positive BCE year with explicit era) into AUC.
### `Tempo.roman.aucToYear(auc: number, format?: 'astronomical' | 'historical')`
Converts an AUC year into an astronomical integer or `{ year, era: 'CE' | 'BCE' }`.
### `Tempo.roman.getNonesDay(month: number): number`
Returns 7 for MOM-J months (March, October, May, July) and 5 for all other months.
### `Tempo.roman.getIdesDay(month: number): number`
Returns 15 for MOM-J months (March, October, May, July) and 13 for all other months.
### `Tempo.roman.isLeapYear(year: number, isJulian?: boolean): boolean`
Evaluates leap year status under Gregorian or Julian calendar rules.
---
## Topic Guides
- [Classical Fasti & Lunar Anchors](./roman.calendar-mechanics.md) - Kalends, Nones, Ides, inclusive backward counting, bissextile intercalation, and AUC conversion mathematics.
- [Production Use Cases & Architectural Patterns](./roman.use-cases-and-patterns.md) - Epigraphy, numismatics, archival cataloging, and manuscript dating workflows.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/roman.use-cases-and-patterns.md
# Use Cases & Production Patterns
`@tempo-kit/plugin-roman` provides deterministic, high-performance classical calendar calculations for applications in classical archaeology, numismatics, epigraphy, academic digital humanities, and legal manuscript processing.
---
## 1. Digital Epigraphy & Classical Inscription Parsing
### The Challenge
Museum catalogs, archaeological excavation databases, and epigraphic registries (such as the *Corpus Inscriptionum Latinarum*) frequently record dates in Latin abbreviations (e.g. `a.d. IV Id. Mart.` or `a.d. XVII Kal. Nov.`). Systems need to compute the exact modern Gregorian/Julian calendar coordinate for temporal indexing and GIS timelines.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import { RomanPlugin } from '@tempo-kit/plugin-roman';
Tempo.use(RomanPlugin);
interface InscriptionRecord {
id: string;
catalogNumber: string;
latinDate: string;
anchor: 'Kalends' | 'Nones' | 'Ides';
anchorMonth: number;
relation: 'on' | 'pridie' | 'ante_diem';
count: number;
yearAuc: number;
}
function resolveInscriptionDate(record: InscriptionRecord): Tempo {
// 1. Convert AUC year to astronomical calendar year
const astronomicalYear = Tempo.roman.aucToYear(record.yearAuc);
// 2. Resolve classical Roman anchor to calendar date
const resolved = Tempo.roman.fromClassical(
record.anchor,
record.anchorMonth,
astronomicalYear,
record.relation,
record.count,
false, // isBissextile
true // isJulian
);
return new Tempo({
year: resolved.year,
month: resolved.month,
day: resolved.day
});
}
// Example: Inscription recording "a.d. XVII Kal. Nov. 2779 AUC"
const tempoDate = resolveInscriptionDate({
id: 'c-104',
catalogNumber: 'CIL VI 2065',
latinDate: 'a.d. XVII Kal. Nov.',
anchor: 'Kalends',
anchorMonth: 11,
relation: 'ante_diem',
count: 17,
yearAuc: 2779
});
console.log(tempoDate.format('{yyyy}-{mm}-{dd}')); // "2026-10-16"
// Or resolve the inscription text directly using the Phase 3 Classical Parser:
const parsedFromText = Tempo.roman.parse('a.d. XVII Kal. Nov. 2779 AUC');
console.log(parsedFromText.format('{yyyy}-{mm}-{dd}')); // "2026-10-16"
```
---
## 2. Numismatics & Ancient Coin Provenance
### The Challenge
Numismatic databases record Roman imperial coinage dated by AUC foundation years or major commemorative Roman dates. Coin metadata must be indexed synchronously alongside both modern CE/BCE dates and historical AUC timestamps.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-roman/install';
interface RomanCoin {
mintId: string;
emperor: string;
issueDate: Tempo;
}
const coinCollection: RomanCoin[] = [
{
mintId: 'RIC-I-42',
emperor: 'Augustus',
issueDate: new Tempo('-000026-01-16') // January 16, 27 BCE (Title of Augustus conferred)
},
{
mintId: 'RRC-415-1',
emperor: 'Julius Caesar',
issueDate: new Tempo('-000043-03-15') // March 15, 44 BCE (Ides of March)
}
];
// Enrich numismatic metadata with classical Roman and AUC representations
const enrichedCatalog = coinCollection.map(coin => {
const roman = coin.issueDate.toRomanClassical();
return {
mintId: coin.mintId,
emperor: coin.emperor,
gregorian: coin.issueDate.format('{yyyy}-{mm}-{dd}'),
latinDate: roman.latin,
shortDate: roman.shortLatin,
yearAuc: `${coin.issueDate.toAUC()} AUC`
};
});
console.table(enrichedCatalog);
```
---
## 3. Academic Manuscript Dating & Legal Charters
### The Challenge
Medieval papal bulls, monastic annals, and European royal charters frequently dated official decrees using the Roman ecclesiastical calendar. Archival tools need to verify whether transcribed dates match internal document text and compute verified civil calendar dates.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-roman/install';
function verifyCharterDating(year: number, month: number, day: number) {
const tempo = new Tempo({ year, month, day });
const classical = tempo.toRomanClassical();
return {
isoDate: tempo.format('{yyyy}-{mm}-{dd}'),
formalLatin: classical.latin,
abbreviated: classical.shortLatin,
aucYear: classical.auc,
isLeapIntercalation: classical.isBissextile
};
}
// Verify a decree signed on February 24 in a leap year
const leapCharter = verifyCharterDating(2024, 2, 24);
console.log(leapCharter.formalLatin);
// "ante diem bis sextum Kalendas Martias"
// Verify an autumn charter signed on October 14
const idesEveCharter = verifyCharterDating(2026, 10, 14);
console.log(idesEveCharter.formalLatin);
// "Pridie Idus Octobres"
```
---
## 4. Consular Dating & Fasti Chronology
### The Challenge
Historical sources and decrees from the Roman Republic and early Empire were rarely dated by year numbers; they were dated by the eponymous Roman consuls holding office. Historians need to match consular dating formulas (e.g., *"C. Julio Caesare V, M. Antonio coss."*) with exact astronomical and civil calendar coordinates.
### Implementation Pattern
```typescript
import { Tempo } from 'tempo-kit';
// Full 1,050-year Fasti consulares (also auto-installs RomanPlugin):
import '@tempo-kit/plugin-roman/consuls';
// (For lean core without full Fasti, use: import '@tempo-kit/plugin-roman/install')
// 1. Resolve an astronomical date and format its presiding consuls
const ides44BCE = new Tempo('-000043-03-15');
console.log(ides44BCE.consuls);
// "C. Julio Caesare V, M. Antonio coss."
// 2. Format with standard Tempo tokens
console.log(ides44BCE.format('{roman:classical}, {roman:consul}'));
// "Idibus Martiis, C. Julio Caesare V, M. Antonio coss."
// 3. Search the Fasti consulares (509 BCE–541 CE) by consul name
const ciceroEntries = Tempo.roman.findConsuls('Cicero');
console.log(ciceroEntries[0]);
// { year: -62, consuls: ['M. Tullius Cicero', 'C. Antonius Hybrida'], formatted: 'M. Tullio Cicerone, C. Antonio Hybrida coss.' }
// 4. Parse classical text with a consular dating formula directly
const dateFromConsuls = Tempo.roman.parse('Idibus Martiis Cicerone coss.');
console.log(dateFromConsuls.format('{yyyy}-{mm}-{dd}')); // "-000062-03-15" (March 15, 63 BCE)
```
---
## See Also
- **[Classical Fasti & Lunar Anchors](./roman.calendar-mechanics.md)**: Deep dive on anchor formulas, bissextile intercalation, and Latin declensions.
- **[Plugin Documentation Home](./roman.index.md)**: Complete API surface catalog and interactive live REPL.
---
# Document: 9-plugins/signals.index.md

# @tempo-kit/plugin-signals
Tempo community plugin for reactive TC39 Signals (`Signify`), adaptive relative-time formatting, boundary-scheduled interval state observation, and global configuration reactivity.
Core `tempo-kit` is a static, immutable, zero-timer snapshot engine. `@tempo-kit/plugin-signals` layers fine-grained, event-driven reactivity on top of Tempo without adding background timers or reactivity overhead to core bundles.
## Key Features
- **Tree-Shakeable Functions & Explicit Installation**: Standalone functions (`toRelativeSignal`, `intervalSignal`, `localeSignal`, `timeZoneSignal`) and `SignalsPlugin` are exported from the root entry with zero side effects; registration occurs only via `Tempo.use(SignalsPlugin)` or the `/install` entry (which mounts `Tempo.signals`, `tempo.toRelativeSignal()`, and `interval.toSignal()`).
- **Two Integration Patterns**: Use standalone tree-shakeable functions directly, or mount `Tempo.signals`, `tempo.toRelativeSignal()`, and `interval.toSignal()` via `Tempo.use(SignalsPlugin)` or `/install`.
- **Adaptive Relative-Time Signals**: `toRelativeSignal` schedules one-shot `setTimeout` updates at exact unit-bucket boundaries (`second` → `minute` → `hour` → `day` → `month` → `year`) instead of polling every second, and automatically tracks global `Tempo.init({ locale })` updates.
- **Boundary-Scheduled Interval Observation**: `intervalSignal` tracks `isCurrent`, `isPast`, `isFuture`, and normalized `progress` ($\in [0, 1]$) with zero polling while future or past.
- **Reactive Global Configuration**: `localeSignal` and `timeZoneSignal` synchronize with `Tempo.init()` via `tempo-kit/plugin/sdk`'s `onConfigChange` hook.
- **Deterministic Cleanup**: Returned signals implement both `dispose()` and `Symbol.dispose` (for TypeScript `using` declarations), backed by a `Finalizer` safety net.
---
## Installation {#installation}
```bash
npm install @tempo-kit/plugin-signals
```
---
## Quickstart {#quickstart}
### Plugin Registration (`Tempo.use` or `/install`) {#plugin-registration}
Installing `SignalsPlugin` mounts the frozen `Tempo.signals` namespace, `Tempo.prototype.toRelativeSignal()`, and `Tempo.Interval.prototype.toSignal()`:
```typescript
import { Tempo } from 'tempo-kit';
import { SignalsPlugin } from '@tempo-kit/plugin-signals';
Tempo.use(SignalsPlugin);
const meeting = new Tempo().add({ minutes: 5 });
using relative = meeting.toRelativeSignal();
console.log(relative.get()); // e.g. "in 4m" (default 'narrow' style, truncating toward zero once the clock advances by a few ms)
```
Or use the side-effect `/install` entrypoint to auto-register `SignalsPlugin` on import:
```typescript
import '@tempo-kit/plugin-signals/install';
import { Tempo } from 'tempo-kit';
const deadline = new Tempo().add({ hours: 2 });
using relative = deadline.toRelativeSignal({ style: 'long' });
console.log(relative.value); // e.g. "in 1 hour"
```
### Tree-Shakeable Standalone Functions {#tree-shakeable-functions}
For bundle-sensitive applications, import only the functions you need from the root entrypoint without mutating `Tempo`:
```typescript
import { Tempo } from 'tempo-kit';
import { toRelativeSignal } from '@tempo-kit/plugin-signals';
const target = new Tempo().add({ minutes: 10 });
using relative = toRelativeSignal(target, { style: 'short' });
console.log(relative.get()); // e.g. "in 9 min."
```
| Approach | Import Syntax | Side Effects | Ideal For |
| :--- | :--- | :--- | :--- |
| **Tree-Shakeable Functions** | `import { toRelativeSignal, intervalSignal } from '@tempo-kit/plugin-signals'` | None | Minimal client bundles and isolated components |
| **Explicit Plugin** | `import { SignalsPlugin } from '@tempo-kit/plugin-signals'` + `Tempo.use(SignalsPlugin)` | Explicit | Controlled initialization with `SignalsPluginOptions` |
| **Auto-Install Import** | `import '@tempo-kit/plugin-signals/install'` | Registers `SignalsPlugin` | Apps, REPLs, and convenience setup |
---
## Global Configuration Signals {#global-config-signals}
`localeSignal`, `timeZoneSignal`, and `createConfigSignals` expose `ReadonlySignal` instances that stay synchronized with global `Tempo.init()` calls.
```typescript
import { Tempo } from 'tempo-kit';
import { Signify } from 'tempo-kit/library';
import {
createConfigSignals,
disposeConfigSignals,
} from '@tempo-kit/plugin-signals';
Tempo.init({ locale: 'en-US', timeZone: 'UTC' });
const { locale, timeZone } = createConfigSignals({
locale: 'en-US',
timeZone: 'UTC',
});
const summary = Signify.computed(() => `${locale.get()} @ ${timeZone.get()}`);
console.log(summary.get()); // "en-US @ UTC"
Tempo.init({ locale: 'fr-FR', timeZone: 'Europe/Paris' });
console.log(summary.get()); // "fr-FR @ Europe/Paris"
// Detach the global onConfigChange listener when tearing down
disposeConfigSignals();
```
When `SignalsPlugin` is installed, the same signals are exposed on `Tempo.signals.locale` and `Tempo.signals.timeZone` (and detached via `Tempo.signals.dispose()` or `using _ = Tempo.signals`).
### Options (`SignalsPluginOptions`) {#signals-plugin-options}
| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `locale` | `string` | Runtime `Intl` locale (or `'en'`) | Fallback BCP 47 locale before `Tempo.init()` specifies one |
| `timeZone` | `string` | Runtime `Intl` time zone (or `'UTC'`) | Fallback IANA time zone before `Tempo.init()` specifies one |
### System Locale & Time-Zone Watchers (`watchSystemConfig`) {#watch-system-config}
To synchronize `Tempo.init()` automatically when the host OS or browser changes its locale or time zone (e.g., laptop travel across time zones or `languagechange` events) with **zero background polling**:
```typescript
import { watchSystemConfig } from '@tempo-kit/plugin-signals';
// Sync both locale and timeZone on browser focus/visibility/languagechange events
using watcher = watchSystemConfig();
// Or keep a pinned locale and sync only timeZone
using tzOnly = watchSystemConfig({ locale: false });
```
When `SignalsPlugin` is installed, the same helper is available at `Tempo.signals.watchSystem(options?)`. Non-browser runtimes can pass a custom `subscribe(trigger)` hook (e.g., Electron `powerMonitor`), call `watcher.check()`, or opt into `pollIntervalMs`.
---
## Adaptive Relative-Time Signals (`toRelativeSignal`) {#adaptive-relative-time}
`toRelativeSignal(target, options?)` (and `tempo.toRelativeSignal(options?)` / `Tempo.signals.relative(target, options?)`) returns a `DisposableSignal` formatted via `Intl.RelativeTimeFormat`.
Instead of running a fixed 1-second timer, it computes the exact delay until the next unit-bucket transition and schedules a single one-shot `setTimeout` for that boundary—keeping background wakeups $O(1)$ per bucket change. If `options.locale` is omitted, the signal also reacts automatically to global `Tempo.init({ locale })` changes.
```typescript
import { Tempo } from 'tempo-kit';
import { Signify } from 'tempo-kit/library';
import { toRelativeSignal } from '@tempo-kit/plugin-signals';
const target = new Tempo().add({ minutes: 5 });
using relative = toRelativeSignal(target, {
style: 'long',
numeric: 'auto',
});
const label = Signify.computed(() => `Starts ${relative.get()}`);
console.log(label.get()); // "Starts in 4 minutes"
// Automatically updates when Tempo.init({ locale }) changes
Tempo.init({ locale: 'es-ES' });
console.log(label.get()); // "Starts dentro de 4 minutos"
```
### Accepted Targets (`RelativeSignalTarget`) {#relative-signal-target}
`toRelativeSignal` accepts any of the following target forms:
- `Tempo` instance
- `Temporal.ZonedDateTime` or `Temporal.Instant`
- Object with `{ epoch?: { ms?: number; ns?: bigint } }` or `{ epochMilliseconds?: number; epochNanoseconds?: bigint }`
- `string` (parsed via `new Tempo(target)`)
- `number` (epoch milliseconds) or `bigint` (epoch nanoseconds)
Invalid targets throw a `TypeError`.
### Options (`RelativeSignalOptions`) {#relative-signal-options}
| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `locale` | `string` | Reactive `localeSignal()` | Explicit BCP 47 locale override (disables reactive global locale tracking) |
| `style` | `'long' \| 'short' \| 'narrow'` | `'narrow'` | `Intl.RelativeTimeFormat` formatting style |
| `numeric` | `'always' \| 'auto'` | `'auto'` | `Intl.RelativeTimeFormat` numeric mode (e.g. `'yesterday'` vs `'1 day ago'`) |
| `now` | `() => number` | `Date.now` | Custom clock returning epoch milliseconds (useful for deterministic tests) |
### `DisposableSignal` Surface {#disposable-signal}
`DisposableSignal` extends `ReadonlySignal` and is callable (`sig()`), readable via `.get()` or `.value`, and explicitly disposable:
- `disposed`: `boolean` — `true` after `dispose()` or `[Symbol.dispose]()` has been called.
- `dispose()`: stops pending boundary timers and releases resources.
- `[Symbol.dispose]()`: alias for `dispose()` enabling `using` blocks.
---
## Interval State Signals (`intervalSignal`) {#interval-state-signals}
`intervalSignal(interval, options?)` (and `interval.toSignal(options?)` / `Tempo.signals.interval(interval, options?)`) projects a Tempo `Interval` into four reactive `ReadonlySignal` properties:
- `isFuture`: `ReadonlySignal` — `true` while `now < start`.
- `isCurrent`: `ReadonlySignal` — `true` while `now` is within `[start, end)`.
- `isPast`: `ReadonlySignal` — `true` once `now >= end`.
- `progress`: `ReadonlySignal` — normalized elapsed ratio in $[0, 1]$ (`0` before start, `1` at or after end).
Boundary transitions (`start` and `end`) use exact one-shot `setTimeout` scheduling—zero polling occurs while the interval is in the future or past. The `progress` ticker runs only while `isCurrent` is `true` (unless disabled).
```typescript
import { Tempo, Interval } from 'tempo-kit';
import { intervalSignal } from '@tempo-kit/plugin-signals';
const start = new Tempo().add({ seconds: 10 });
const end = start.add({ minutes: 5 });
const window = new Interval(start, end);
using state = intervalSignal(window, { progressInterval: 500 });
console.log(state.isFuture.get()); // true
console.log(state.isCurrent.get()); // false
console.log(state.isPast.get()); // false
console.log(state.progress.get()); // 0
```
With `SignalsPlugin` installed, you can call `.toSignal()` directly on any `Interval`:
```typescript
import '@tempo-kit/plugin-signals/install';
import { Tempo, Interval } from 'tempo-kit';
const now = new Tempo();
const meeting = new Interval(now, now.add({ minutes: 30 }));
using state = meeting.toSignal({ progressInterval: false });
console.log(state.isCurrent.get()); // true
```
### Options (`IntervalSignalOptions`) {#interval-signal-options}
| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `progressInterval` | `number \| false` | `1000` | Update interval in milliseconds for `progress` while `isCurrent` is `true`. Set to `false` or `0` to disable periodic progress ticks. |
| `now` | `() => number` | `Date.now` | Custom clock returning epoch milliseconds. |
---
## API Summary {#api-summary}
| Export | Kind | Description |
| :--- | :--- | :--- |
| `SignalsPlugin`, `signalsPlugin`, `default` | `TempoPlugin` | Plugin mounting `Tempo.signals`, `Tempo.prototype.toRelativeSignal`, and `Tempo.Interval.prototype.toSignal` |
| `localeSignal(options?)` | Function | Shared `ReadonlySignal` synchronized with global `locale` |
| `timeZoneSignal(options?)` | Function | Shared `ReadonlySignal` synchronized with global `timeZone` |
| `createConfigSignals(options?)` | Function | Frozen `{ locale, timeZone }` config signals object |
| `disposeConfigSignals()` | Function | Detaches the global `onConfigChange` listener |
| `toRelativeSignal(target, options?)` | Function | Adaptive, boundary-scheduled `DisposableSignal` |
| `intervalSignal(interval, options?)` | Function | Boundary-scheduled `IntervalSignalState` (`isCurrent`, `isPast`, `isFuture`, `progress`) |
---
## Relationship with `@tempo-kit/plugin-ticker` {#relationship-with-ticker}
- Use **`@tempo-kit/plugin-ticker`** when you need continuous fixed-cadence clock streams (`Tempo.ticker.signal({ seconds: 1 })`).
- Use **`@tempo-kit/plugin-signals`** when you need event-driven relative-time labels, interval lifecycle state, or reactive `Tempo.init()` configuration signals.
---
## Topic Guides {#topic-guides}
- [Production Use Cases & Architectural Patterns](./signals.use-cases-and-patterns.md) - Battery-friendly activity feeds, live interval progress bars, and app-wide locale/time zone reactivity.
---
## License {#license}
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/signals.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
`@tempo-kit/plugin-signals` brings event-driven TC39 Signals (`Signify`) to UI components, dashboards, and scheduling workflows without adding background polling overhead to Core `tempo-kit`.
---
## 1. Battery-Friendly Activity Feeds (`toRelativeSignal`) {#activity-feeds}
Chat messages, deployment logs, and audit trails often render hundreds of relative timestamps (`"just now"`, `"5 minutes ago"`, `"2 hours ago"`). Polling every row once per second wastes CPU and battery on stale entries.
`toRelativeSignal` schedules a single one-shot `setTimeout` at the exact next unit-bucket boundary (`second` → `minute` → `hour` → `day` → `month` → `year`), so a 3-hour-old item sleeps for up to an hour between updates:
```typescript
import { toRelativeSignal } from '@tempo-kit/plugin-signals';
function mountTimestampBadge(createdAtIso: string) {
const label = toRelativeSignal(createdAtIso, { style: 'narrow' });
// Read current value synchronously in your UI render / effect
console.log(label.get());
// Call label.dispose() when the row/component unmounts
return () => label.dispose();
}
```
---
## 2. Live Meeting & Booking Progress Bars (`intervalSignal`) {#interval-progress}
Calendar cards, maintenance windows, and SLA timers need to transition cleanly through **upcoming** (`isFuture`), **active** (`isCurrent`), and **completed** (`isPast`) states while tracking normalized completion `progress` ($\in [0, 1]$).
```typescript
import { Tempo } from 'tempo-kit';
import { intervalSignal } from '@tempo-kit/plugin-signals';
const start = new Tempo().add({ minutes: 10 });
const end = start.add({ minutes: 50 });
const meetingWindow = new Tempo.Interval(start, end);
using state = intervalSignal(meetingWindow, { progressInterval: 1_000 });
console.log({
isFuture: state.isFuture.get(),
isCurrent: state.isCurrent.get(),
isPast: state.isPast.get(),
progress: state.progress.get(),
});
```
- While `isFuture` is `true`, **no progress ticker runs**—only a single boundary timer waits until `start`.
- Once `start` is reached, `isCurrent` flips to `true` and optional `progressInterval` updates begin.
- Once `end` is reached, `isPast` becomes `true`, `progress` locks at `1`, and all timers stop automatically.
---
## 3. App-Wide Locale & Time Zone Switching (`localeSignal` / `timeZoneSignal`) {#global-config-reactivity}
When a user switches language or time zone in application settings via `Tempo.init()`, `localeSignal` and `timeZoneSignal` propagate the change to reactive views automatically via `tempo-kit/plugin/sdk`'s `onConfigChange` hook:
```typescript
import { Tempo } from 'tempo-kit';
import { localeSignal, timeZoneSignal, disposeConfigSignals } from '@tempo-kit/plugin-signals';
const locale = localeSignal();
const timeZone = timeZoneSignal();
console.log(locale.get(), timeZone.get());
// Updating global Tempo configuration notifies active config signals
Tempo.init({ locale: 'fr-FR', timeZone: 'Europe/Paris' });
console.log(locale.get(), timeZone.get()); // "fr-FR", "Europe/Paris"
// Detach global config observer on app teardown
disposeConfigSignals();
```
---
## 4. Travel & Live OS Time-Zone Sync (`watchSystemConfig`) {#travel-os-sync}
For web apps, PWAs, or desktop apps where a user's device may cross time zones or change OS region settings while the app stays open, `watchSystemConfig()` (or `Tempo.signals.watchSystem()`) bridges host `Intl` changes into `Tempo.init()` without background polling:
```typescript
import { Tempo } from 'tempo-kit';
import { SignalsPlugin, watchSystemConfig } from '@tempo-kit/plugin-signals';
Tempo.use(SignalsPlugin);
Tempo.init({ locale: 'en-AU', calendar: 'iso8601' });
// Keep the pinned app locale while syncing OS time-zone changes on focus/visibility
using watcher = watchSystemConfig({ locale: false });
// Hybrid/desktop apps (e.g. Electron) can also attach native wake events:
// using desktopWatcher = Tempo.signals.watchSystem({
// subscribe: (trigger) => {
// powerMonitor.on('resume', trigger);
// return () => powerMonitor.off('resume', trigger);
// },
// });
```
---
# Document: 9-plugins/snap.index.md

# @tempo-kit/plugin-snap
A Community plugin for the [Tempo](https://github.com/magmacomputing/magma) library that provides robust time rounding and interval snapping functionality across standard time components (`hours`, `minutes`, `seconds`, `milliseconds`, `microseconds`, and `nanoseconds`).
By default, the plugin effortlessly snaps dates to a configurable minute-interval. This is invaluable when building UI components like time-pickers and calendar grids, downsampling telemetry streams, or aligning timestamps to multimedia frame boundaries.
---
## Key Features
- **Interval Snapping**: Rounds to the nearest interval of any time unit: `hh`, `mi`, `ss`, `ms`, `us`, or `ns`.
- **Sensible Default**: `t.snap()` snaps to the nearest 15 minutes.
- **Directional Control**: `direction: 'up' | 'down'` selects ceiling or floor snapping.
- **Immutable**: Returns a **new** `Tempo` instance with sub-units cleared to zero.
- **Time Components Only**: Date units are intentionally disallowed; use `.startOf()` or `.add()` for calendar math.
---
## Installation
```bash
npm install @tempo-kit/plugin-snap
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import { SnapPlugin } from '@tempo-kit/plugin-snap';
Tempo.use(SnapPlugin);
const t = new Tempo('2026-06-01T14:08:00Z');
// Snaps to the nearest 15 minutes by default
const snapped = t.snap();
console.log(snapped.format('{hh}:{mi}')); // "14:15"
// Or explicitly provide units and intervals
const snapHour = t.snap({ hh: 1 });
const snapSecond = t.snap({ ss: 30 });
const snapMs = t.snap({ ms: 100 });
// Directional snapping (floor vs ceiling)
const snapUp = t.snap({ mi: 15, direction: 'up' }); // 14:15
const snapDown = t.snap({ mi: 15, direction: 'down' }); // 14:00
```
### Zero-Boilerplate Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-snap/install';
const t = new Tempo('2026-06-01T14:08:00Z');
console.log(t.snap().format('{hh}:{mi}')); // "14:15"
```
---
## API Reference
The Snap plugin extends `Tempo.prototype` with a fluent, immutable `snap()` method:
| Method | Target | Options Argument | Returns | Description |
| :--- | :--- | :--- | :--- | :--- |
| **`t.snap(options?)`** | Instance | `SnapOptions?: OneKey & { direction?: 'up' \| 'down' }` | `Tempo` | Returns a **new** Tempo instance rounded to the nearest interval of the specified time unit. Sub-units are cleared to zero. |
### Supported Units (`SnapKey`)
The options object accepts exactly one time component mapped to a numeric step:
| Unit Key | Long Aliases | Description | Example |
| :--- | :--- | :--- | :--- |
| `'hh'` | `'hour'`, `'hours'` | Snaps to hour interval (e.g. nearest 1, 2, or 4 hours) | `t.snap({ hh: 1 })` |
| `'mi'` | `'minute'`, `'minutes'` | Snaps to minute interval (default: `15`) | `t.snap({ mi: 15 })` |
| `'ss'` | `'second'`, `'seconds'` | Snaps to second interval (e.g. 10s, 30s) | `t.snap({ ss: 30 })` |
| `'ms'` | `'millisecond'`, `'milliseconds'` | Snaps to millisecond interval | `t.snap({ ms: 50 })` |
| `'us'` | `'microsecond'`, `'microseconds'` | Snaps to microsecond interval | `t.snap({ us: 500 })` |
| `'ns'` | `'nanosecond'`, `'nanoseconds'` | Snaps to nanosecond interval | `t.snap({ ns: 1000 })` |
> [!NOTE]
> **Time Components Only**: Date units (`days`, `months`, `years`) are strictly disallowed in `snap()`. For calendar date manipulation, use Tempo core's native `.startOf('month')`, `.startOf('week')`, or `.add({ days: 1 })`.
---
## Topic Guides
- **[Production Use Cases & Architectural Patterns](./snap.use-cases-and-patterns.md)**: Interactive calendar UI scheduling grids (15m/30m drop slots), InfluxDB/Prometheus telemetry downsampling buckets, and 60fps/25fps multimedia frame boundary snapping.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/snap.use-cases-and-patterns.md
# Lock-Free Atomics & Memory Architecture
The `@tempo-kit/plugin-sync` plugin provides hardware-level, nanosecond-accurate cross-thread time synchronization using standard JavaScript `SharedArrayBuffer` and `Atomics`.
It is specifically engineered for multi-threaded architectures—such as high-frequency trading (HFT) risk checkers, real-time physics engines, and audio digital signal processing (DSP)—where inter-process communication (IPC) latency or event-loop microtasks cannot be tolerated.
---
## The Shared Memory Layout
Traditional multi-worker architectures broadcast timestamp updates via `postMessage()`. In Node.js or high-throughput browser Web Workers, `postMessage()` suffers from structural cloning serialization costs, thread-context switching, and event loop queue delays ranging from `0.5ms` to `15ms`.
The Sync plugin bypasses the event loop entirely by allocating a dedicated 8-byte shared buffer in virtual memory:
```
┌────────────────────────────────────────────────────────┐
│ Virtual Memory: SharedArrayBuffer (8 Bytes) │
├────────────────────────────────────────────────────────┤
│ [ 0x00 | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 ] │
│ ◄──────────────── 64-Bit Integer (BigInt64Array) ────► │
│ Represents: Epoch Time in Nanoseconds (nowNano) │
└────────────────────────────────────────────────────────┘
▲ │
│ │
Atomics.store Atomics.load
(Master Thread) (Worker Threads)
```
### 1. Master Clock Writer (`AtomicClock`)
* The master process instantiates `AtomicClock`, allocating `new SharedArrayBuffer(8)` with a `BigInt64Array` typed view.
* An internal monotonic ticker writes the current timestamp in nanoseconds into index `0` using `Atomics.store(this.#view, 0, nowNano)`.
* Because `Atomics.store` is an atomic store instruction, it guarantees sequential consistency across all CPU cores and hardware memory caches without requiring thread locking or mutex semaphores.
### 2. Lock-Free Worker Reader (`AtomicReader`)
* Worker threads receive the `SharedArrayBuffer` reference upon initialization (e.g. via `workerData` in Node.js or `postMessage` transfer in the browser).
* The worker binds an `AtomicReader` directly to the buffer.
* Invoking `reader.nowNano()` or `reader.now()` executes a single CPU instruction: `Atomics.load(this.#view, 0)`.
* This read executes synchronously in **$O(1)$ constant time** ($\approx 10\text{–}25\text{ nanoseconds}$ on modern x86/ARM hardware), with zero IPC overhead and zero garbage collection pressure.
---
## Dual-Layer Lifecycle Management
Long-running timer loops in Node.js can inadvertently keep processes alive or cause memory leaks during hot-reloads and test teardowns. The Sync plugin implements Tempo's **Dual-Layer Lifecycle Model**:
### 1. Native Timer Unreferencing (`unref()`)
When the master clock starts its periodic synchronization loop, it automatically calls `.unref()` on the underlying timer:
```typescript
if (typeof timer.unref === 'function') {
timer.unref();
}
```
This ensures that the presence of the background sync clock will not prevent Node.js from exiting gracefully when all primary application tasks complete.
### 2. Explicit Deterministic Resource Management (`using`)
`AtomicClock` implements `[Symbol.dispose]()` for deterministic cleanup via TypeScript 5.2+ explicit resource management:
```typescript
{
using clock = Tempo.sync.startClock({ interval: 5 });
// Buffer is actively shared with worker threads...
} // <-- Automatically invokes clock.stop() upon leaving block scope
```
### 3. GC Finalization Registry Safety Net
As an asynchronous fallback, the clock registers with Tempo's `Finalizer` registry. If a developer forgets to call `clock.stop()` or dispose the instance, the timer is safely halted when the clock instance is reclaimed by the garbage collector.
---
## Browser Security Constraints: Cross-Origin Isolation
Due to Spectre and Meltdown side-channel mitigation policies, web browsers disable `SharedArrayBuffer` by default unless the host website serves strict **Cross-Origin Isolation** HTTP headers:
```http
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
### Environment Compatibility Matrix
| Runtime Environment | `SharedArrayBuffer` Support | Configuration Requirements |
| :--- | :--- | :--- |
| **Node.js (v18+)** | ✅ Native (Unrestricted) | None. Enabled by default across all worker threads. |
| **Browser (Isolated)** | ✅ Native (High Precision) | Web server must emit `COOP: same-origin` and `COEP: require-corp`. |
| **Browser (Non-Isolated)** | ❌ Blocked by Browser | Static hosts (e.g. GitHub Pages) cannot enable SAB without proxy headers. |
| **Electron / Tauri** | ✅ Native (Configurable) | Set `webPreferences: { nodeIntegration: true }` or configure isolation headers. |
> [!NOTE]
> If `SharedArrayBuffer` is not supported in the host environment, `AtomicClock` immediately throws a descriptive initialization error directing developers to verify their server headers or run in Node.js.
---
# Document: 9-plugins/sync.index.md

# @tempo-kit/plugin-sync
This is a Community plugin for the [Tempo](https://github.com/magmacomputing/magma) library that provides lock-free, nanosecond-accurate cross-thread time synchronization using `SharedArrayBuffer` and `Atomics`.
It eliminates inter-process message passing (IPC) latency, allowing worker threads and Web Workers to read current timestamps synchronously in constant $O(1)$ time.
::: tip Perfect For
High-frequency trading platforms, real-time multiplayer authoritative game servers, distributed microservice tracing, and extreme-precision scientific telemetry.
:::
---
## Key Features
- **Lock-Free Cross-Thread Clock**: A master `AtomicClock` writes time into a `SharedArrayBuffer` that workers read with `AtomicReader`.
- **Constant-Time Reads**: `reader.now()` returns epoch milliseconds in $O(1)$ time with no inter-process messaging.
- **Nanosecond Precision**: `reader.nowNano()` returns BigInt nanoseconds and `reader.getTempo()` hydrates an exact `Tempo`.
- **Browser & Node.js Workers**: Works across Web Workers (with Cross-Origin Isolation) and Node.js `worker_threads`.
- **Managed Timer Lifecycle**: Master clock timers support `unref()` and `using` for deterministic cleanup.
---
## Installation
```bash
npm install @tempo-kit/plugin-sync
```
---
## Quickstart
::: info Live Interactive Sandbox Note
This plugin leverages `SharedArrayBuffer` and `Atomics` for hardware-level cross-thread synchronization. Modern browsers require **Cross-Origin Isolation** (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`) to enable `SharedArrayBuffer`. Because GitHub Pages static hosting cannot emit custom HTTP response headers, the live browser sandbox widget is disabled on this documentation page. To test the Sync plugin, run it in **Node.js** (supported natively) or in a local development environment with custom server headers configured.
:::
### Master Process: Initializing the Atomic Clock
```typescript
import { Tempo } from 'tempo-kit';
import { SyncPlugin } from '@tempo-kit/plugin-sync';
Tempo.use(SyncPlugin);
// Start master clock loop (interval in ms, default is 10)
const clock = Tempo.sync.startClock({ interval: 5 });
const buffer = clock.getBuffer(); // Pass this SharedArrayBuffer to your workers
```
#### Zero-Boilerplate Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-sync/install';
const clock = Tempo.sync.startClock({ interval: 10 });
```
### Worker Process: Lock-Free Reading
```typescript
// worker.ts
import { workerData } from 'node:worker_threads';
import { AtomicReader } from '@tempo-kit/plugin-sync';
// Hydrate reader directly from shared memory
const reader = new AtomicReader(workerData.buffer);
// 1. Get raw epoch milliseconds (O(1) Atomic Read)
const ms = reader.now();
// 2. Get high-precision BigInt nanoseconds
const ns = reader.nowNano();
// 3. Hydrate a brand new Tempo instance with exact precision
const t = reader.getTempo();
console.log(t.iso);
```
---
## API Reference
The Sync plugin exposes two primary abstractions: `AtomicClock` for the master thread, and `AtomicReader` for worker threads:
| Class / Method | Context | Parameters | Returns | Description |
| :--- | :--- | :--- | :--- | :--- |
| **`Tempo.sync.startClock(opts?)`** | Master | `ClockOptions?: { interval?: number }` | `AtomicClock` | Initializes and starts the master clock loop, continuously writing time to shared memory. |
| **`Tempo.sync.stopClock()`** | Master | None | `void` | Halts the master clock synchronization loop. |
| **`Tempo.sync.getBuffer()`** | Master | None | `SharedArrayBuffer` | Returns the underlying 8-byte shared buffer for worker transfer. |
| **`new AtomicReader(buffer)`** | Worker | `buffer: SharedArrayBuffer` | `AtomicReader` | Instantiates a high-speed reader bound to the shared clock buffer. |
| **`reader.now()`** | Worker | None | `number` | Returns synchronized epoch timestamp in milliseconds in $O(1)$ time. |
| **`reader.nowNano()`** | Worker | None | `bigint` | Returns synchronized epoch timestamp in BigInt nanoseconds. |
| **`reader.getTempo()`** | Worker | None | `Tempo` | Hydrates a new immutable `Tempo` instance representing current synchronized time. |
---
## Topic Guides
- **[Lock-Free Atomics & Memory Architecture](./sync.atomic-architecture.md)**: Hardware-level memory layout (`SharedArrayBuffer(8)`), Atomics sequential consistency, browser COOP/COEP isolation rules, and dual-layer timer lifecycle management (`unref()`, `using`).
- **[Production Use Cases & Architectural Patterns](./sync.use-cases-and-patterns.md)**: High-frequency trading worker clusters, authoritative multiplayer game physics loops, and real-time audio DSP thread synchronization.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/sync.use-cases-and-patterns.md
# Production Use Cases & Architectural Patterns
This guide explores architectural patterns where `@tempo-kit/plugin-sync` provides lock-free, zero-latency time synchronization across multi-threaded systems.
---
## 1. High-Frequency Trading (HFT) Worker Thread Risk Cluster
### Problem Statement
In automated algorithmic trading and risk evaluation engines, 16–32 worker threads concurrently evaluate order books, order cancellations, and margin limits. In asynchronous microsecond trading environments, inter-thread message passing (`worker.postMessage`) introduces 500µs to 2ms of jitter. Workers evaluating risk thresholds with staggered clock skews make inconsistent margin calls or execute out-of-order market orders.
### Architectural Solution
The main thread runs a master `AtomicClock` updating every 1ms. The shared buffer is passed to worker threads at startup. Worker risk evaluators read the exact current timestamp in $O(1)$ lock-free time via `reader.nowNano()`, guaranteeing absolute ordering and eliminating IPC delays.
```
Master Process (WebSocket Ingestion)
│
[AtomicClock: 1ms loop]
│
SharedArrayBuffer(8)
┌──────────────┼──────────────┐
▼ ▼ ▼
Worker #1 Worker #2 Worker #3
(Risk Engine) (Order Book) (Compliance)
│ │ │
reader.now() reader.now() reader.now()
(Sub-microsecond Lock-Free Atomic Read)
```
### Production Implementation
```typescript
// master.ts (Main Process)
import { Worker } from 'node:worker_threads';
import { Tempo } from 'tempo-kit';
import { SyncPlugin } from '@tempo-kit/plugin-sync';
Tempo.use(SyncPlugin);
export class TradingEngineCluster {
private clock = Tempo.sync.startClock({ interval: 1 }); // 1ms tick
private workers: Worker[] = [];
spawnWorkers(workerScriptPath: string, count = 4) {
const buffer = this.clock.getBuffer();
for (let i = 0; i < count; i++) {
const worker = new Worker(workerScriptPath, {
workerData: { buffer, workerId: i + 1 }
});
this.workers.push(worker);
}
}
shutdown() {
this.clock.stop();
for (const w of this.workers) w.terminate();
}
}
```
```typescript
// worker.ts (Executed inside worker thread)
import { workerData } from 'node:worker_threads';
import { AtomicReader } from '@tempo-kit/plugin-sync';
// Hydrate atomic reader directly from shared memory
const reader = new AtomicReader(workerData.buffer);
export function evaluateTradeRisk(orderId: string, limitPrice: number) {
// Ultra-fast lock-free read (approx 15ns)
const currentNano = reader.nowNano();
const currentMs = reader.now();
// Hydrate full Tempo instance for audit logging when violations occur
if (limitPrice > 10_000) {
const auditTime = reader.getTempo();
console.warn(`[Risk Violation] Order ${orderId} at ${auditTime.iso}`);
}
return { orderId, evaluatedAtNano: currentNano, evaluatedAtMs: currentMs };
}
```
---
## 2. Authoritative Multiplayer Game Simulation Ticks
### Problem Statement
In real-time multiplayer dedicated game servers (spatial combat, FPS, sports), physics simulations (Havok, Rapier, PhysX) run across multiple dedicated background workers. If physics workers derive their simulation `deltaTime` from independent `Date.now()` or `performance.now()` calls, thread scheduling jitter creates simulation desyncs, "rubber-banding", and inconsistent projectile trajectories.
### Architectural Solution
The master server loop drives simulation time using `AtomicClock`. Physics worker threads query `reader.now()` at the beginning of each simulation step to access drift-free master time. When workers require a strictly common simulation timestamp across all isolates, the master captures one tick value and passes it to all workers.
```typescript
import { Tempo } from 'tempo-kit';
import { SyncPlugin, AtomicReader } from '@tempo-kit/plugin-sync';
Tempo.use(SyncPlugin);
export class PhysicsSimulationWorker {
private reader: AtomicReader;
private lastTickMs: number;
constructor(sharedBuffer: SharedArrayBuffer) {
this.reader = new AtomicReader(sharedBuffer);
this.lastTickMs = this.reader.now();
}
/**
* Evaluates a single physics tick synchronized with the master server clock.
*/
stepSimulation() {
const currentMs = this.reader.now();
const deltaTime = (currentMs - this.lastTickMs) / 1000; // in seconds
this.lastTickMs = currentMs;
// Run physics integration with zero inter-worker time drift
return { currentMs, deltaTime };
}
}
```
---
## 3. Real-Time Audio DSP Buffer Synchronization
### Problem Statement
In WebAudio and professional audio workstations, digital signal processing (DSP) threads process audio frames in strict 128-sample buffers (approx `2.9ms` at 44.1kHz). If the UI thread or network synchronization thread communicates with the audio thread via asynchronous messages, audio buffer under-runs (clicks and pops) occur whenever the main thread is busy rendering or parsing JSON.
### Architectural Solution
By sharing an `AtomicClock` buffer between the main thread and audio workers, the audio processor can stamp incoming MIDI notes and parameter automations synchronously without touching the event loop:
```typescript
import { AtomicReader } from '@tempo-kit/plugin-sync';
export class AudioWorkletTimeSync {
private reader: AtomicReader;
constructor(sharedBuffer: SharedArrayBuffer) {
this.reader = new AtomicReader(sharedBuffer);
}
/**
* Called within audio rendering callback (zero allocations permitted).
*/
processAudioFrame(frameNumber: number) {
// Lock-free read executes in O(1) time without garbage collection
const sampleTimestampNs = this.reader.nowNano();
return { frameNumber, timestampNs: sampleTimestampNs };
}
}
```
---
# Document: 9-plugins/ticker.index.md

# @tempo-kit/plugin-ticker
A high-performance Community plugin for the [Tempo](https://github.com/magmacomputing/magma) ecosystem providing temporal continuous execution loops, best-effort scheduling with millisecond resolution, explicit resource management disposers (`using` / `await using`), async generator streams, and multi-clock synchronization.
Unlike raw `setInterval`, Tempo Ticker handles calendar arithmetic, month-length adjustments, daylight saving shifts, recurrence rules, and cron schedules with zero timer drift.
---
## Key Features
- **Zero-Drift Scheduling**: Calendar-aware intervals with month-length adjustments, DST shift correction, and cron/RRULE recurrence.
- **Explicit Resource Management**: First-class `using` / `await using` disposer support (`Symbol.dispose` / `Symbol.asyncDispose`) for leak-free scoped lifecycles.
- **Async Generator Streams**: `for await (const t of ticker)` streaming loop support for reactive pipelines and telemetry.
- **Rich Event Listeners**: `.on('pulse')`, `.on('stop')`, `.on('catch')` hooks for fine-grained control and error isolation.
- **Registry Diagnostics**: `Ticker.active` snapshot of all running tickers for health monitoring.
- **Multi-Clock Synchronization**: Synchronize multiple tickers to shared NTP-corrected clocks via `@tempo-kit/plugin-ntp`.
---
## Installation
```bash
npm install @tempo-kit/plugin-ticker
```
---
## Quickstart
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-ticker/install';
{
await using ticker = Tempo.ticker({ seconds: 1 }, (t) => {
console.log('Tick:', t.format('{hh}:{mi}:{ss}'));
});
// Keep scope alive to observe repeated ticks
await new Promise((resolve) => setTimeout(resolve, 2500));
} // ⚡ Cleaned up automatically upon leaving scope
```
### Auto-Installation (Side-Effect Import)
```typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-ticker/install';
const ticker = Tempo.ticker({ seconds: 1 });
```
### Plugin Registration
```typescript
import { Tempo } from 'tempo-kit';
import { TickerPlugin } from '@tempo-kit/plugin-ticker';
Tempo.use(TickerPlugin);
```
### Async Generator Stream
```typescript
async function streamClock() {
await using ticker = Tempo.ticker({ seconds: 1 });
let count = 0;
for await (const t of ticker) {
console.log('Stream tick:', t.iso);
if (++count >= 5) break;
}
}
```
---
## API Reference
### Creation: `Tempo.ticker(intervalOrOptions?, callback?)`
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `intervalOrOptions` | `Ticker.Interval \| Ticker.Options` | Number of seconds, cron expression, RRULE string, calendar term, or comprehensive options object. |
| `callback` | `(t: Tempo, stop: () => void) => void` | Optional pulse callback. |
### `Ticker.Options` Configuration
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `seconds` / `ss` | `number` | `1` | Seconds interval step. Negative values count backwards. |
| `minutes` / `mi` | `number` | — | Minutes interval step. |
| `hours` / `hh` | `number` | — | Hours interval step. |
| `days` / `dd` | `number` | — | Days interval step. |
| `months` / `mm` | `number` | — | Calendar months interval step. |
| `years` / `yy` | `number` | — | Years interval step. |
| `cron` | `string` | — | Standard 5-field cron expression (e.g. `'*/15 * * * *'`). |
| `rrule` | `string` | — | Standard RFC 5545 iCalendar recurrence rule string. |
| `seed` | `string \| Date \| Tempo` | Current time | Initial timestamp or starting point for virtual clocks and countdowns. |
| `until` | `string \| Date \| Tempo` | — | Inclusive termination boundary. |
| `limit` | `number` | — | Maximum pulse count before automatic shutdown (`limit: 0` stops immediately). |
| `label` | `string` | — | Descriptive label visible in `Ticker.active` telemetry. |
### `TickerInstance` Object
| Method / Property | Return Type | Description |
| :--- | :--- | :--- |
| `ticker.stop()` | `void` | Stops the ticker, clears active timers, and finalizes pending async iterators. |
| `ticker.pulse()` | `Tempo` | Manually triggers a pulse, advances state, and notifies listeners. |
| `ticker.info` | `object` | Telemetry snapshot: `{ next, ticks, limit, interval, stopped }`. |
| `ticker.on(event, cb)` | `this` | Registers listeners for `'pulse'`, `'stop'`, or `'catch'`. |
| `[Symbol.dispose]` | `void` | Synchronous disposer hook for `using` blocks. |
| `[Symbol.asyncDispose]` | `Promise` | Asynchronous disposer hook for `await using` blocks. |
| `[Symbol.asyncIterator]` | `AsyncGenerator` | Streaming generator support for `for await (const t of ticker)` loops. |
### Static `Ticker` Namespace
| Property | Return Type | Description |
| :--- | :--- | :--- |
| `Ticker.active` | `Snapshot[]` | Returns an array of snapshots for all currently running (non-stopped) Tickers. |
---
## Topic Guides
Explore detailed guides on specific capabilities:
- **[Intervals & Scheduling Engines](./ticker.intervals-and-scheduling.md)**: Semantic durations (`{ months: 1 }`), calendar terms (`#timeOfDay`), 5-field Cron expressions (`0 9 * * 1-5`), RFC 5545 RRULE, countdowns, and one-shot meeting alerts.
- **[Resource Management & Lifecycle](./ticker.resource-management.md)**: Explicit resource management (`using` / `await using`), async generators (`for await`), programmatic controls (`stop`, `info`, `pulse`), limits, and zombie process prevention.
- **[Event Streams & Reactive Clocks](./ticker.reactive-clocks-and-events.md)**: Event listeners (`.on('pulse')`, `.on('stop')`, `.on('catch')`), registry diagnostics (`Ticker.active`), and zero-drift multi-timezone dashboards with UI signals.
- **[Production Use Cases & Architectural Patterns](./ticker.use-cases-and-patterns.md)**: Zero-drift telemetry heartbeats, leak prevention via `using`, streaming market tick generators, multi-timezone cron schedules, and laptop sleep recovery.
---
## License
This is a **Community** plugin. It is completely free and open-source for personal and commercial use under the MIT license.
---
# Document: 9-plugins/ticker.intervals-and-scheduling.md
# Production Use Cases & Architectural Patterns
Standard JavaScript scheduling primitives (`setInterval` and `setTimeout`) are notorious for silent failures in long-running production systems:
1. **Cumulative Clock Drift**: Timers drift by dozens of milliseconds per cycle due to main-thread execution lag and event loop starvation.
2. **Zombie Timers & Memory Leaks**: Orphaned intervals remain running after UI components unmount or HTTP request handlers finish, slowly leaking memory.
3. **Desktop & Mobile Sleep Distortion**: When an operating system enters low-power sleep mode, standard intervals freeze, skipping scheduled database jobs or failing to drain background work queues.
The `@tempo-kit/plugin-ticker` plugin solves these challenges with calendar-aware scheduling, Explicit Resource Management (`using` / `await using`), async generators, and self-healing sleep recovery.
---
## 1. Zero-Drift Telemetry & Heartbeat Loops
In backend services and IoT edge gateways, healthcheck heartbeats and metric aggregations must pulse on exact intervals (e.g. precisely every 15 seconds) regardless of how long the async payload takes to send.
With `setInterval`, network latency or slow database queries delay subsequent ticks. With `Tempo.ticker`, each pulse is pinned to an absolute epoch target, completely eliminating cumulative drift:
```typescript
import '@tempo-kit/plugin-ticker/install';
import { Tempo } from 'tempo-kit';
export function startTelemetryEmitter(endpointUrl: string) {
// Pulses every 15 seconds with automatic catch-up on system wake
const heartbeat = Tempo.ticker({
seconds: 15,
catch: true,
label: 'telemetry-emitter'
});
heartbeat.on('pulse', async (t: Tempo) => {
const payload = {
timestamp: t.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}'),
epochMs: t.epoch.ms,
tickCount: heartbeat.info.ticks
};
try {
await fetch(endpointUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
} catch (err) {
console.error('Failed to dispatch heartbeat:', err);
}
});
return heartbeat;
}
```
---
## 2. Preventing Zombie Leaks with Explicit Resource Management (`using`)
One of the most common memory leaks in modern TypeScript applications is forgotten timer handles in async operations, unit tests, or component lifecycles.
`Tempo.ticker` implements JavaScript's **Explicit Resource Management** (`Disposable` and `AsyncDisposable`). When defined with `using` or `await using`, the ticker automatically cleans up its internal timers, event listeners, and weak references the exact moment code leaves scope:
```typescript
import '@tempo-kit/plugin-ticker/install';
import { Tempo } from 'tempo-kit';
async function monitorJobQueue(jobId: string): Promise {
// Automatically disposed when monitorJobQueue exits (even if an error throws)
using clock = Tempo.ticker({ seconds: 2 });
while (!isJobComplete(jobId)) {
// Pull the next scheduled tick promise
await clock.pull();
console.log(`Polling status for ${jobId} at ${new Tempo().format('{hh}:{mi}:{ss}')}`);
}
} // <-- clock is automatically stopped and deregistered here!
```
---
## 3. Streaming Financial Market Feeds (`for await...of`)
Instead of managing imperative callbacks and event listener state, `Tempo.ticker` can be consumed directly as an **Async Generator**.
This pattern provides natural backpressure handling in data pipelines: if downstream processing slows down, the consumer controls the flow without dropped events:
```typescript
import '@tempo-kit/plugin-ticker/install';
import { Tempo } from 'tempo-kit';
interface MarketSummary {
symbol: string;
price: number;
sampledAt: string;
}
export async function* streamMarketTicks(
symbol: string,
sampleRateSeconds: number
): AsyncGenerator {
// Streams ticks at precise interval intervals
for await (const tick of Tempo.ticker({ seconds: sampleRateSeconds })) {
const latestPrice = await fetchLatestQuote(symbol);
yield {
symbol,
price: latestPrice,
sampledAt: tick.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}')
};
}
}
```
---
## 4. Multi-Timezone Market Opening & Closing Schedules
Scheduling financial batch jobs across global exchanges (e.g. NYSE at 9:30 AM EST, Tokyo Stock Exchange at 9:00 AM JST) is prone to bugs when countries change between Daylight Saving Time (DST) on different weeks.
`Tempo.ticker` supports standard 5-field Cron syntax with explicit `timeZone` anchoring:
```typescript
import '@tempo-kit/plugin-ticker/install';
import { Tempo } from 'tempo-kit';
// 9:30 AM Monday-Friday in New York time (respects US DST transitions automatically)
const nyseBell = Tempo.ticker({
cron: '30 9 * * 1-5',
timeZone: 'America/New_York',
label: 'nyse-opening-bell'
});
nyseBell.on('pulse', (t: Tempo) => {
console.log(`NYSE Open at: ${t.format('{yyyy}-{mm}-{dd} {hh}:{mi}:{ss}')}`);
triggerDailyOpeningAuction();
});
```
---
## 5. Mobile & Laptop Sleep Recovery (`catch: true`)
When a mobile app or laptop enters sleep mode, background execution freezes. When the user opens their laptop 2 hours later, a standard `setInterval` only fires once for the latest tick, losing all context of the missed window.
With `{ catch: true }`, `Tempo.ticker` detects the elapsed time gap and fires the `catch` event with the missed pulse sequence, allowing applications to drain queues or synchronize state:
```typescript
import '@tempo-kit/plugin-ticker/install';
import { Tempo } from 'tempo-kit';
const syncLoop = Tempo.ticker({
minutes: 5,
catch: true,
label: 'offline-cache-sync'
});
syncLoop.on('catch', (missedTick: Tempo) => {
console.warn(`Recovering missed sync point from: ${missedTick.format('{hh}:{mi}:{ss}')}`);
reconcileDatabaseChanges(missedTick);
});
syncLoop.on('pulse', (currentTick: Tempo) => {
runScheduledSync(currentTick);
});
```
---