# API and extension contracts

## Calendar engine

`new Calendar(options)` from `advent-of-anything/core`. It is an `EventTarget` and
uses no DOM globals, layouts, animation code or automatic timers.

| Option         | Default / meaning                                                                              |
| -------------- | ---------------------------------------------------------------------------------------------- |
| `id`           | `calendar`; choose a stable unique identifier when persisting                                  |
| `version`      | `1`; change deliberately to isolate incompatible saved state                                   |
| `start`, `end` | Optional date-only range; `end` bounds derived `day` entries, not availability after the range |
| `timeZone`     | `UTC`, an IANA timezone accepted by `Intl`                                                     |
| `preview`      | `false`; bypass scheduling, never disabled state; separate persistence namespace               |
| `clock`        | `() => Date.now()`; supply a function returning Date or epoch milliseconds                     |
| `policy`       | `datePolicy`; synchronous `(entry, context) => boolean`                                        |
| `persistence`  | `noPersistence()`; synchronous adapter                                                         |
| `entries`      | Initial array; duplicate IDs rejected                                                          |

`register(entry)` validates and adds one entry. `update(id, partialEntry)` preserves
open/progress state and does not allow renaming the ID. `remove(id)` removes the
entry and its saved state. `get(id)` returns `{ entry, locked, disabled, open,
opened }`, or undefined. `entries` returns a new array; `progress` is `{ total,
opened, currentOpen, unlocked, complete }`. `opened` counts entries ever revealed;
completion requires a nonempty calendar and every current entry seen once.

`open(id)`, `close(id)`, `unlock(id)` return whether they made an applicable change.
Opening refreshes availability first. A `once` entry cannot be closed after
opening. `refresh()` reevaluates policies, closes entries that become unavailable,
and returns progress. Call it when a custom policy's external inputs change.
`dispose()` stops pending ready delivery and prevents future mutations. Consumers
own their own clock polling and event listeners; the engine owns no timers.

### Entry fields

Only `id` is required. Optional `label`, `title`, `description`, `url`, `image`,
`category`, `metadata`, `linkLabel`, `day`, `unlockAt`, `alwaysAvailable`, `manual`,
`disabled`, `once`, `reveal`, and `layout` hints. Content need not have a URL.
Use stable IDs so progress survives changes to order or content.

- `day` is a positive 1-based calendar-day offset from `start`.
- `unlockAt: '2027-07-06'` means the beginning of that civil day in `timeZone`.
- `unlockAt: '2027-07-06T12:00:00Z'` or an explicit numeric offset is an exact
  instant; timezone does not shift it. Offsetless timestamps are rejected.
- `unlockAt` takes precedence over `day`. Entries with no scheduling fields
  are always available unless `manual` is true.
- Default policy: manual unlock or `alwaysAvailable` wins, then `manual` blocks,
  then a date is checked. Disabled always blocks; preview bypasses the policy.
- Ranges can cross months/years and leap days. Civil-day arithmetic handles DST
  without assuming a local day is 24 hours. Explicit timestamps may lie outside
  the optional range. End is not an expiration/relock date.

### Custom policy

```js
import { datePolicy } from 'advent-of-anything/core';
const policy = (entry, context) =>
  datePolicy(entry, context) && completedLessons.has(entry.metadata.lesson);
```

Context contains `now`, `timeZone`, `manuallyUnlocked`, `preview`. Policies must
return a boolean synchronously. Exceptions and Promise results fail closed and
emit `advent:error`. Fetch external eligibility outside the policy, then refresh.

## Components

Importing `advent-of-anything` automatically defines both components if a custom
element registry exists. Import `/components` and call `defineComponents()` for
explicit registration. Use native custom-element properties/methods from any
framework; no framework adapter is required.

### `<advent-calendar>`

Attributes: `id`, `version`, `start`, `end`, `time-zone`, `preview`, `persistence`
(`none`, `memory`, `local`, `session`), `layout`, `seed`, `reveal`, and `src` (remote
JSON). Local/session storage requires an explicit stable ID. Booleans are HTML
boolean attributes: presence enables them; `preview="false"` still enables preview.

Slots: `heading`, `description`, `empty`; default slot contains direct doors.
Nested calendars own their own children. Schedule attributes rebuild the engine;
use persistence if you need to restore state across reconfiguration/reconnection.
Layout, seed, theme and reveal changes preserve engine state. `theme` is a CSS
selector, not engine configuration.

- `.configure(options)` applies engine options; properties override attributes.
  Optional `entries` replaces doors. Validates first. Returns the component.
- `.register(entry, contentElement?)` adds a door and returns it. Without a content
  element, title/description/image/link are rendered with safe DOM APIs. With one,
  it is moved into `slot="content"`; callers own this trusted DOM.
- `.load(source)` accepts a URL, JSON string, array, or `{ entries }`. Successful
  validation replaces entries. A later load/configure or disconnect aborts stale
  remote work. It returns a Promise of entries; failed loads emit error and reject.
- `.engine` is available after connection/reconciliation. Await `advent:ready` or
  call `.configure()` on an attached element before using it. Calling engine
  `.register()` alone does not create DOM; use component `.register()` for that.

Direct-child additions/removals and entry attributes are observed. An explicit
`entry-id` is recommended; otherwise an HTML `id` or component-local identifier is
used. Generated IDs are not stable across a fresh page. The connected component
refreshes policies every second, with no guarantee about background-tab timer
throttling. Opening also refreshes. Disconnect stops the timer and fetch work.

### `<advent-door>`

Works alone or as a direct calendar child. Slots: `front` (noninteractive label or
artwork), `content` (arbitrary HTML). Methods: `.open()`, `.close()`, `.toggle()`,
`.unlock()`; `.state` exposes its current state. Methods return booleans.

Attributes: `label`, `open-label`, `close-label`, `once`, `disabled`, `reveal`,
`unlock-at`, `manual`, `always-available`, and `open`. Inside a calendar: `entry-id`
and `day`. Standalone scheduling uses `unlock-at`, `time-zone`, `preview`, or
`locked` for an externally controlled manual lock. Calendar-owned `locked` and
`open` reflect the engine; setting `open` cannot bypass its policy. Standalone
doors use ephemeral engine state; use a calendar/custom integration for persistence.

Built-in reveals: `hinge`, `flip`, `slide`, `fade`, `instant`. A calendar's reveal
is inherited unless a door has its own override. Unknown reveal names allow
consumer CSS mechanisms (otherwise the neutral hinge rules apply).

## Content and remote trust

`parseManifest(input, config?)` validates an array or `{ entries }`. Extra metadata
is data only; `html` and `render` keys are rejected. `fetchManifest(url, options?)`
adds HTTP status checking, abort support, credential omission and a 1 MiB default
body limit. Options: `signal`, `fetcher`, `config`, `maxBytes`. No remote code runs.

`renderEntry(entry, document)` creates an article with `textContent`, not an HTML
parser. Only HTTP(S) image and link URLs survive `safeURL`; relative URLs resolve
against the consuming document. Images can still contact a remote host; callers
must choose trusted image sources or apply a CSP. Arbitrary HTML is supported
only through consumer-owned slots/DOM, not remote manifests. JSON-only calendars
need an author-provided static fallback when JavaScript is unavailable.

## Persistence

Exports: `memoryPersistence()`, `noPersistence()`, `localStoragePersistence()`,
`sessionStoragePersistence()`, `storagePersistence(getStorage)`.

Custom adapters implement `load(key)`, `save(key, state)`, `remove(key)`; no Promises.
State: `{ schema: 1, open: string[], seen: string[], manual: string[] }`. The engine
validates loaded state, reports errors and continues in memory. Storage is obtained
lazily so denied browser access does not break component import. Keys encode ID and
version, with a separate `:preview` namespace. State is not a shared backend, and
cross-tab live synchronization is not implemented. Supply unique calendar IDs.

## Events

All use `Event` with a read-only `.detail`; they are not cancelable. Engine events
do not bubble; component events bubble and are composed across shadow roots. Owned
doors report through their calendar once; standalone doors report on themselves.

| Event                         | When / detail                                                          |
| ----------------------------- | ---------------------------------------------------------------------- |
| `advent:ready`                | Engine initialized; queued so callers can subscribe after construction |
| `advent:unlock`               | A registered entry transitions from locked to available                |
| `advent:open`, `advent:close` | Current visibility changes                                             |
| `advent:progress`             | Registration, removal, availability or visibility changes              |
| `advent:complete`             | Nonempty current entry set transitions to all ever opened              |
| `advent:error`                | `error`, `operation`, and optional affected entry                      |

Normal details include `calendarId`, optional `entryId`/`entry`, and `progress`.
Initialization does not generate an unlock event for every already available
entry; inspect ready/progress instead. Listen for errors before setting `src` or
call `.load()` and handle its Promise. State changes are not canceled via events;
use the policy for access decisions.
