@serene-pub/sdk 0.6.0-pr-5 → 0.6.0-pr-7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.d.ts +52 -2
- package/dist/actions.js +56 -6
- package/dist/annexFields.d.ts +32 -2
- package/dist/annexFields.js +48 -5
- package/dist/announce.d.ts +142 -2
- package/dist/announce.js +198 -2
- package/dist/attributes.d.ts +331 -6
- package/dist/attributes.js +339 -27
- package/dist/bridges.d.ts +61 -0
- package/dist/bridges.js +112 -0
- package/dist/builder.d.ts +278 -51
- package/dist/builder.js +267 -30
- package/dist/cadences.d.ts +585 -0
- package/dist/cadences.js +1118 -0
- package/dist/capabilities.d.ts +106 -17
- package/dist/capabilities.js +85 -7
- package/dist/checkMethods.d.ts +240 -0
- package/dist/checkMethods.js +362 -0
- package/dist/component.d.ts +6 -1
- package/dist/componentClient.d.ts +42 -6
- package/dist/componentWire.js +22 -4
- package/dist/composerStates.d.ts +96 -0
- package/dist/composerStates.js +190 -0
- package/dist/conditions.d.ts +424 -0
- package/dist/conditions.js +521 -0
- package/dist/config.d.ts +42 -6
- package/dist/config.js +48 -20
- package/dist/conversions.d.ts +41 -0
- package/dist/conversions.js +50 -0
- package/dist/declarations.d.ts +40 -2
- package/dist/declarations.js +178 -10
- package/dist/descriptors.d.ts +287 -4
- package/dist/descriptors.js +281 -18
- package/dist/document.d.ts +47 -2
- package/dist/document.js +46 -14
- package/dist/entities.d.ts +156 -0
- package/dist/entities.js +259 -0
- package/dist/events.d.ts +711 -1
- package/dist/events.js +412 -1
- package/dist/executor.d.ts +4 -3
- package/dist/executor.js +22 -8
- package/dist/exposure.d.ts +128 -0
- package/dist/exposure.js +168 -0
- package/dist/extension.d.ts +127 -3
- package/dist/extension.js +43 -0
- package/dist/fit.d.ts +198 -0
- package/dist/fit.js +351 -0
- package/dist/functions.d.ts +554 -0
- package/dist/functions.js +712 -0
- package/dist/genres.d.ts +303 -89
- package/dist/genres.js +335 -100
- package/dist/hookGrants.d.ts +15 -1
- package/dist/hookGrants.js +11 -10
- package/dist/hooks.d.ts +34 -5
- package/dist/hooks.js +5 -2
- package/dist/hostElements.d.ts +7 -1
- package/dist/hostElements.js +20 -1
- package/dist/hostState.d.ts +110 -0
- package/dist/hostState.js +140 -0
- package/dist/identity.d.ts +1 -1
- package/dist/identity.js +1 -1
- package/dist/index.d.ts +25 -0
- package/dist/index.js +48 -0
- package/dist/jsonSchema.d.ts +178 -0
- package/dist/jsonSchema.js +570 -0
- package/dist/libraryDraft.d.ts +27 -0
- package/dist/libraryDraft.js +25 -0
- package/dist/lorebookFile.d.ts +44 -0
- package/dist/lorebookFile.js +202 -0
- package/dist/media.d.ts +127 -12
- package/dist/media.js +45 -1
- package/dist/messageBlocks.d.ts +179 -5
- package/dist/messageBlocks.js +208 -6
- package/dist/participants.d.ts +32 -9
- package/dist/participants.js +13 -2
- package/dist/pluginHarness.d.ts +63 -33
- package/dist/pluginHarness.js +78 -144
- package/dist/pluginPermissions.d.ts +15 -1
- package/dist/pluginPermissions.js +29 -2
- package/dist/preview.d.ts +45 -4
- package/dist/preview.js +52 -12
- package/dist/primers.d.ts +177 -0
- package/dist/primers.js +265 -0
- package/dist/receipt.d.ts +11 -0
- package/dist/receiverRules.js +9 -0
- package/dist/refs.d.ts +9 -1
- package/dist/refs.js +12 -0
- package/dist/registrations.d.ts +384 -0
- package/dist/registrations.js +625 -0
- package/dist/repertoires.d.ts +502 -0
- package/dist/repertoires.js +666 -0
- package/dist/rulesetDocument.d.ts +116 -0
- package/dist/rulesetDocument.js +252 -0
- package/dist/rulesetSections.d.ts +631 -0
- package/dist/rulesetSections.js +1288 -0
- package/dist/rulesetTemplates.d.ts +161 -0
- package/dist/rulesetTemplates.js +242 -0
- package/dist/rulesets.d.ts +899 -0
- package/dist/rulesets.js +1378 -0
- package/dist/sceneSettings.d.ts +8 -0
- package/dist/sceneSettings.js +10 -2
- package/dist/scope.d.ts +44 -3
- package/dist/scope.js +18 -0
- package/dist/scripts.d.ts +31 -8
- package/dist/scripts.js +45 -8
- package/dist/sessionDossier.d.ts +157 -7
- package/dist/sessionLayout.d.ts +291 -138
- package/dist/sessionLayout.js +504 -211
- package/dist/sessionSettings.d.ts +24 -0
- package/dist/settings.d.ts +95 -4
- package/dist/settings.js +293 -4
- package/dist/shapes.d.ts +80 -1
- package/dist/shapes.js +100 -5
- package/dist/speech.d.ts +333 -0
- package/dist/speech.js +199 -0
- package/dist/statShapes.d.ts +8 -1
- package/dist/statShapes.js +8 -1
- package/dist/status.d.ts +14 -0
- package/dist/status.js +12 -0
- package/dist/storage.d.ts +53 -66
- package/dist/storage.js +7 -12
- package/dist/storyTime.d.ts +25 -1
- package/dist/storyTime.js +42 -2
- package/dist/surfaces.d.ts +15 -2
- package/dist/template.d.ts +19 -1
- package/dist/template.js +25 -11
- package/dist/templateScopeAt.d.ts +1 -1
- package/dist/templateScopeAt.js +11 -8
- package/dist/ties.d.ts +211 -0
- package/dist/ties.js +301 -0
- package/dist/turnOrder.d.ts +25 -14
- package/dist/turnOrder.js +21 -8
- package/dist/userAnnex.d.ts +126 -0
- package/dist/userAnnex.js +214 -0
- package/dist/validate.js +114 -19
- package/dist/values.js +6 -0
- package/dist/vocabularies.d.ts +192 -0
- package/dist/vocabularies.js +326 -0
- package/dist/widgetDecls.d.ts +12 -0
- package/dist/widgetDecls.js +2 -0
- package/dist/widgets.d.ts +1062 -29
- package/dist/widgets.js +218 -3
- package/host-elements.d.ts +90 -0
- package/package.json +1 -1
package/dist/cadences.js
ADDED
|
@@ -0,0 +1,1118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 🚧 **Cadences** — when a routine runs (R5, R9, R10, R15–R21; PLAN-layering D2).
|
|
3
|
+
*
|
|
4
|
+
* A routine is a pipeline registered on a **cadence**: a declared condition
|
|
5
|
+
* that answers one thing — due or not — and passes **no data of its own**
|
|
6
|
+
* (R9). The host evaluates a cadence only at the **events** it **wakes on**
|
|
7
|
+
* (D11, 2026-10-23: they are events, never "moments") — a turn ended, a
|
|
8
|
+
* round ended, a scene opened or closed, the story clock moved, the
|
|
9
|
+
* 5-minute system tick, or any session event (`ANY_EVENT`: `onEvent`,
|
|
10
|
+
* `whenValue`) — so a cadence that is not due costs nothing.
|
|
11
|
+
*
|
|
12
|
+
* Every cadence is declared once, globally, with a stable id
|
|
13
|
+
* (`core:cadence/every-n-turns@1`) and **options** declared as fields, so a
|
|
14
|
+
* registration states it as `{ id, options }` (a `CadenceRef`): addressable,
|
|
15
|
+
* serializable, validated by the same field declarations an administrator's
|
|
16
|
+
* settings use (§11-3). Core's ten are evaluated natively by the host
|
|
17
|
+
* (`evaluate: 'host'`); a plugin's cadence is a script of kind
|
|
18
|
+
* `core:script:cadence/due@1`, run in the sandbox.
|
|
19
|
+
*
|
|
20
|
+
* The pure due-functions live here, so the host and an author's test agree:
|
|
21
|
+
* `cadenceDue(ref, event, state)` answers one event and returns the state
|
|
22
|
+
* to keep (a cron's next time, a value's last answer), and
|
|
23
|
+
* `simulateCadence(ref, events)` drives a list of events for a test (A17).
|
|
24
|
+
*
|
|
25
|
+
* ## The rulings the functions hold
|
|
26
|
+
*
|
|
27
|
+
* · **No seconds** (R10): nothing here counts finer than a minute.
|
|
28
|
+
* · **System Cron: five minutes is the floor** (R15) — a minutes interval is
|
|
29
|
+
* a multiple of 5, at least 5. Core ticks routines every 5 minutes.
|
|
30
|
+
* · **Timeline Cron** (R10, R17, R19): on the session's story calendar,
|
|
31
|
+
* at least one minute; when the clock moves it fires **once** if its
|
|
32
|
+
* remaining wait is within the jump, never once per interval crossed (no
|
|
33
|
+
* catch-up); an optional **jump ceiling** (`maxJump`, "Skip when the clock
|
|
34
|
+
* jumps more than …") makes a larger move fire nothing.
|
|
35
|
+
* · **Schedule** (R20): set moments — once, daily, weekly, monthly,
|
|
36
|
+
* annually — on the 5-minute grid, on the system clock (the owner's time
|
|
37
|
+
* zone) or the story calendar (its own weekdays and months).
|
|
38
|
+
* · **No catch-up after a restart** (R21): the host clears a cron's state
|
|
39
|
+
* on the first interaction after a restart, and each counts its next time
|
|
40
|
+
* from then.
|
|
41
|
+
*
|
|
42
|
+
* Story time is ordered by `compareStoryTimes` and stepped by
|
|
43
|
+
* `advanceStoryTime` — never packed into one number.
|
|
44
|
+
* @experimental
|
|
45
|
+
* @ruling R5, R9, R10, R15, R16, R17, R19, R20, R21, A17
|
|
46
|
+
*/
|
|
47
|
+
import { checkValues } from './settings.js';
|
|
48
|
+
import { refuseUnlessIdentical } from './hash.js';
|
|
49
|
+
import { i18nFindings } from './i18n.js';
|
|
50
|
+
import { conditionFindings, evaluateCondition } from './conditions.js';
|
|
51
|
+
import { CORE_EVENTS, EVENT_ID, eventById, eventIdOf, notADeclaredEvent, packageEventById, } from './events.js';
|
|
52
|
+
import { advanceStoryTime, compareStoryTimes, parseStoryTime, storyDayIndex, storyTimeProblem, storyTimeText, } from './storyTime.js';
|
|
53
|
+
// ── Events a cadence wakes on (D11) ─────────────────────────────────────────
|
|
54
|
+
/** 🚧 `core:event/turn-ended@1` — a turn ended (R51). @experimental */
|
|
55
|
+
export const TURN_ENDED_EVENT = 'core:event/turn-ended@1';
|
|
56
|
+
/** 🚧 `core:event/round-ended@1` — a round ended (R52). @experimental */
|
|
57
|
+
export const ROUND_ENDED_EVENT = 'core:event/round-ended@1';
|
|
58
|
+
/** 🚧 `core:event/scene-opened@1`. @experimental */
|
|
59
|
+
export const SCENE_OPENED_EVENT = 'core:event/scene-opened@1';
|
|
60
|
+
/** 🚧 `core:event/scene-closed@1`. @experimental */
|
|
61
|
+
export const SCENE_CLOSED_EVENT = 'core:event/scene-closed@1';
|
|
62
|
+
/** 🚧 `core:event/story-clock-moved@1`. @experimental */
|
|
63
|
+
export const STORY_CLOCK_MOVED_EVENT = 'core:event/story-clock-moved@1';
|
|
64
|
+
/**
|
|
65
|
+
* 🚧 `core:event/system-tick@1` — the 5-minute system tick as the event the
|
|
66
|
+
* host emits to cadences (D11: "the system tick becomes a host-emitted event
|
|
67
|
+
* too"). Host-only: no declared `EventDef`, so no pipeline registers on it —
|
|
68
|
+
* a routine on the system clock is a System Cron, under the cron caps.
|
|
69
|
+
* @experimental
|
|
70
|
+
*/
|
|
71
|
+
export const SYSTEM_TICK_EVENT = 'core:event/system-tick@1';
|
|
72
|
+
/**
|
|
73
|
+
* 🚧 What a cadence that wakes on **every** session event lists (`onEvent`
|
|
74
|
+
* reads its option's event; `whenValue` the published values the host
|
|
75
|
+
* hands with the event).
|
|
76
|
+
* @experimental
|
|
77
|
+
*/
|
|
78
|
+
export const ANY_EVENT = '*';
|
|
79
|
+
// Derive, don't spell (R35): the five session events are core's declared ones.
|
|
80
|
+
for (const [id, def] of [
|
|
81
|
+
[TURN_ENDED_EVENT, CORE_EVENTS.turnEnded],
|
|
82
|
+
[ROUND_ENDED_EVENT, CORE_EVENTS.roundEnded],
|
|
83
|
+
[SCENE_OPENED_EVENT, CORE_EVENTS.sceneOpened],
|
|
84
|
+
[SCENE_CLOSED_EVENT, CORE_EVENTS.sceneClosed],
|
|
85
|
+
[STORY_CLOCK_MOVED_EVENT, CORE_EVENTS.storyClockMoved],
|
|
86
|
+
])
|
|
87
|
+
if (eventIdOf(def) !== id)
|
|
88
|
+
throw new Error(`cadences: '${id}' is not core's ${eventIdOf(def)}`);
|
|
89
|
+
/** 🚧 The core events the host evaluates cadences at, in order. @experimental */
|
|
90
|
+
export const CADENCE_EVENTS = [
|
|
91
|
+
TURN_ENDED_EVENT,
|
|
92
|
+
ROUND_ENDED_EVENT,
|
|
93
|
+
SCENE_OPENED_EVENT,
|
|
94
|
+
SCENE_CLOSED_EVENT,
|
|
95
|
+
STORY_CLOCK_MOVED_EVENT,
|
|
96
|
+
SYSTEM_TICK_EVENT,
|
|
97
|
+
];
|
|
98
|
+
/** The short name an event id reads as in a reason — `turn-ended` for core's. */
|
|
99
|
+
const eventWord = (id) => (id === ANY_EVENT ? 'any event' : (/^core:event\/([a-z0-9-]+)@\d+$/.exec(id)?.[1] ?? id));
|
|
100
|
+
/** ⏳ The moments core's host evaluated cadences at — say `CADENCE_EVENTS`. @experimental */
|
|
101
|
+
export const CORE_MOMENTS = [
|
|
102
|
+
'turn-ended',
|
|
103
|
+
'round-ended',
|
|
104
|
+
'scene-opened',
|
|
105
|
+
'scene-closed',
|
|
106
|
+
'story-clock-moved',
|
|
107
|
+
'system-tick',
|
|
108
|
+
'event',
|
|
109
|
+
'value-changed',
|
|
110
|
+
];
|
|
111
|
+
/** ⏳ What each moment is as an event: the session moments their event ids, `event` and `value-changed` every event. @experimental */
|
|
112
|
+
export const MOMENT_EVENTS = Object.freeze({
|
|
113
|
+
'turn-ended': TURN_ENDED_EVENT,
|
|
114
|
+
'round-ended': ROUND_ENDED_EVENT,
|
|
115
|
+
'scene-opened': SCENE_OPENED_EVENT,
|
|
116
|
+
'scene-closed': SCENE_CLOSED_EVENT,
|
|
117
|
+
'story-clock-moved': STORY_CLOCK_MOVED_EVENT,
|
|
118
|
+
'system-tick': SYSTEM_TICK_EVENT,
|
|
119
|
+
event: ANY_EVENT,
|
|
120
|
+
'value-changed': ANY_EVENT,
|
|
121
|
+
});
|
|
122
|
+
/** 🚧 What a wake is, as an event id: an old moment kind read through `MOMENT_EVENTS` (⏳), anything else as said. @experimental */
|
|
123
|
+
export const cadenceWakeOf = (w) => Object.prototype.hasOwnProperty.call(MOMENT_EVENTS, w) ? MOMENT_EVENTS[w] : w;
|
|
124
|
+
/**
|
|
125
|
+
* 🚧 Any event a cadence is handed, as a `CadenceEvent`: one already is;
|
|
126
|
+
* a ⏳ moment (`kind`) is read as its event — `{ kind: 'event', event,
|
|
127
|
+
* payload }` as that event, `{ kind: 'value-changed', values }` as an event
|
|
128
|
+
* with no id of its own (`ANY_EVENT`) carrying the values.
|
|
129
|
+
* @experimental
|
|
130
|
+
*/
|
|
131
|
+
export function cadenceEventOf(e) {
|
|
132
|
+
const o = e;
|
|
133
|
+
if (typeof o?.event === 'string' && o.kind === undefined)
|
|
134
|
+
return e;
|
|
135
|
+
const { kind, ...rest } = o;
|
|
136
|
+
if (kind === 'event')
|
|
137
|
+
return { ...rest, event: String(rest.event) };
|
|
138
|
+
if (kind === 'value-changed')
|
|
139
|
+
return { event: ANY_EVENT, values: rest.values };
|
|
140
|
+
return { ...rest, event: cadenceWakeOf(String(kind)) };
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* ⏳ The moments a cadence wakes at, in the words before events — for a host
|
|
144
|
+
* that still raises moments (`{ kind }`) for one release: each event id as
|
|
145
|
+
* its moment, every event (`ANY_EVENT`) as `value-changed` for `whenValue`
|
|
146
|
+
* and `event` for any other. Say `cadenceWakesOn`.
|
|
147
|
+
* @experimental
|
|
148
|
+
*/
|
|
149
|
+
export function cadenceMomentKinds(def) {
|
|
150
|
+
const out = new Set();
|
|
151
|
+
for (const w of def?.wakesOn ?? []) {
|
|
152
|
+
if (w === ANY_EVENT)
|
|
153
|
+
out.add(def.id === WHEN_VALUE.id ? 'value-changed' : 'event');
|
|
154
|
+
else {
|
|
155
|
+
const kind = Object.keys(MOMENT_EVENTS).find((k) => MOMENT_EVENTS[k] === w);
|
|
156
|
+
out.add(kind ?? w);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return [...out];
|
|
160
|
+
}
|
|
161
|
+
/** 🚧 Whether a cadence wakes at an event: it lists the event, or every event. @experimental */
|
|
162
|
+
export const cadenceWakesOn = (def, event) => def.wakesOn.includes(ANY_EVENT) || def.wakesOn.includes(event);
|
|
163
|
+
/** `<ns>:cadence/<name>@<N>`. @experimental */
|
|
164
|
+
export const CADENCE_ID = /^[a-z0-9]+(?:[.-][a-z0-9]+)*:cadence\/[a-z0-9]+(?:-[a-z0-9]+)*@\d+$/;
|
|
165
|
+
/** A cadence's name segment — `every-n-turns` for `core:cadence/every-n-turns@1`. @experimental */
|
|
166
|
+
export const cadenceSlugOf = (id) => id.slice(id.indexOf('/') + 1).replace(/@\d+$/, '');
|
|
167
|
+
/** Whether a value is a cadence reference (`{ id, options }` with a cadence id). @experimental */
|
|
168
|
+
export const isCadenceRef = (v) => !!v &&
|
|
169
|
+
typeof v === 'object' &&
|
|
170
|
+
typeof v.id === 'string' &&
|
|
171
|
+
CADENCE_ID.test(v.id) &&
|
|
172
|
+
!!v.options &&
|
|
173
|
+
typeof v.options === 'object';
|
|
174
|
+
const cadences = new Map();
|
|
175
|
+
function cadenceDeclFindings(def) {
|
|
176
|
+
const out = [];
|
|
177
|
+
if (!def || typeof def !== 'object')
|
|
178
|
+
return ['a cadence is { id, i18n, options, wakesOn, carries, evaluate }'];
|
|
179
|
+
if (typeof def.id !== 'string' || !CADENCE_ID.test(def.id))
|
|
180
|
+
out.push(`'${String(def.id)}' is not a cadence id — '<namespace>:cadence/<name>@<version>', lowercase and hyphenated`);
|
|
181
|
+
out.push(...i18nFindings(def.i18n?.name, `${def.id} i18n.name`, { required: true }));
|
|
182
|
+
out.push(...i18nFindings(def.i18n?.description, `${def.id} i18n.description`));
|
|
183
|
+
if (!def.options || typeof def.options !== 'object' || Array.isArray(def.options))
|
|
184
|
+
out.push(`${def.id}: options is a map of field declarations ({} when it takes none)`);
|
|
185
|
+
if (!Array.isArray(def.wakesOn) ||
|
|
186
|
+
!def.wakesOn.length ||
|
|
187
|
+
def.wakesOn.some((m) => typeof m !== 'string' || !m || (cadenceWakeOf(m) !== ANY_EVENT && !EVENT_ID.test(cadenceWakeOf(m)))))
|
|
188
|
+
out.push(`${def.id}: wakesOn lists the events it is evaluated at — event ids (${CADENCE_EVENTS.join(', ')}), or '${ANY_EVENT}' for every event`);
|
|
189
|
+
if (!Array.isArray(def.carries) || def.carries.some((k) => typeof k !== 'string' || !k))
|
|
190
|
+
out.push(`${def.id}: carries lists entity kinds — ['session'] when its event carries nothing more`);
|
|
191
|
+
if (def.clock !== undefined && def.clock !== 'system' && def.clock !== 'story')
|
|
192
|
+
out.push(`${def.id}: clock is 'system' or 'story'`);
|
|
193
|
+
const ev = def.evaluate;
|
|
194
|
+
if (ev !== 'host' &&
|
|
195
|
+
!(ev &&
|
|
196
|
+
typeof ev === 'object' &&
|
|
197
|
+
typeof ev.script === 'string' &&
|
|
198
|
+
ev.script.trim()))
|
|
199
|
+
out.push(`${def.id}: evaluate is 'host' (core's) or { script } — the source of a core:script:cadence/due@1 script`);
|
|
200
|
+
else if (typeof ev === 'object' &&
|
|
201
|
+
ev.script.length > MAX_CADENCE_SCRIPT_BYTES)
|
|
202
|
+
out.push(`${def.id}: the script is ${ev.script.length} bytes; a cadence script is at most ${MAX_CADENCE_SCRIPT_BYTES}`);
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/** The most a cadence script's source may weigh — the sandbox's source cap. @experimental */
|
|
206
|
+
export const MAX_CADENCE_SCRIPT_BYTES = 256 * 1024;
|
|
207
|
+
/**
|
|
208
|
+
* Declare a cadence. Core's own (`core:` ids, evaluated by the host); a
|
|
209
|
+
* plugin declares through `definePluginCadence`. An identical
|
|
210
|
+
* re-declaration is a no-op — a dev server's reload re-runs this — and a
|
|
211
|
+
* different one under a claimed id throws (src/hash.ts).
|
|
212
|
+
* @experimental
|
|
213
|
+
*/
|
|
214
|
+
export function defineCadence(def) {
|
|
215
|
+
const found = cadenceDeclFindings(def);
|
|
216
|
+
if (found.length)
|
|
217
|
+
throw new Error(`cadence refused:\n · ${found.join('\n · ')}`);
|
|
218
|
+
const frozen = Object.freeze({
|
|
219
|
+
...def,
|
|
220
|
+
options: Object.freeze({ ...def.options }),
|
|
221
|
+
// ⏳ An old moment kind is stored as its event (D11).
|
|
222
|
+
wakesOn: Object.freeze([...new Set(def.wakesOn.map(cadenceWakeOf))]),
|
|
223
|
+
carries: Object.freeze([...def.carries]),
|
|
224
|
+
});
|
|
225
|
+
const existing = cadences.get(def.id);
|
|
226
|
+
if (existing) {
|
|
227
|
+
refuseUnlessIdentical(existing, frozen, `duplicate cadence id: ${def.id}`);
|
|
228
|
+
// The same declaration again (a reload): the one already held stays.
|
|
229
|
+
return existing;
|
|
230
|
+
}
|
|
231
|
+
cadences.set(def.id, frozen);
|
|
232
|
+
return frozen;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* A plugin's cadence: its own namespace, evaluated by a script of kind
|
|
236
|
+
* `core:script:cadence/due@1` (the host evaluates only core's natively), and
|
|
237
|
+
* waking only on events the host emits — core's cadence events, a declared
|
|
238
|
+
* session event, or every event.
|
|
239
|
+
* @experimental
|
|
240
|
+
*/
|
|
241
|
+
export function definePluginCadence(pluginId, def) {
|
|
242
|
+
if (typeof def?.id === 'string' && def.id.startsWith('core:'))
|
|
243
|
+
throw new Error(`plugin '${pluginId}' may not declare '${def.id}': the 'core:' namespace is core's`);
|
|
244
|
+
if (def?.evaluate === 'host')
|
|
245
|
+
throw new Error(`plugin '${pluginId}' cadence '${def.id}' says evaluate: 'host' — a plugin's cadence is a script of kind ` +
|
|
246
|
+
`core:script:cadence/due@1: evaluate: { script }`);
|
|
247
|
+
const unknown = (def?.wakesOn ?? []).filter((m) => {
|
|
248
|
+
const w = cadenceWakeOf(m);
|
|
249
|
+
return w !== ANY_EVENT && !CADENCE_EVENTS.includes(w) && !eventById(w) && !packageEventById(w);
|
|
250
|
+
});
|
|
251
|
+
if (unknown.length)
|
|
252
|
+
throw new Error(`plugin '${pluginId}' cadence '${def.id}' wakes on ${unknown.map((m) => `'${m}'`).join(', ')}, which core ` +
|
|
253
|
+
`never emits — one of ${CADENCE_EVENTS.join(', ')}, a declared session event, or '${ANY_EVENT}'`);
|
|
254
|
+
return defineCadence(def);
|
|
255
|
+
}
|
|
256
|
+
/** A declared cadence by id, or undefined. @experimental */
|
|
257
|
+
export const getCadence = (id) => cadences.get(id);
|
|
258
|
+
/** Every declared cadence. @experimental */
|
|
259
|
+
export const allCadences = () => [...cadences.values()];
|
|
260
|
+
/** Withdraw a plugin's cadence (uninstall). Core's stay. @internal */
|
|
261
|
+
export function _withdrawCadence(id) {
|
|
262
|
+
if (id.startsWith('core:'))
|
|
263
|
+
return false;
|
|
264
|
+
return cadences.delete(id);
|
|
265
|
+
}
|
|
266
|
+
// ── Option helpers ──────────────────────────────────────────────────────────
|
|
267
|
+
/** `HH:MM`, 24-hour. @experimental */
|
|
268
|
+
export const CLOCK_TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
|
269
|
+
const parseClockTime = (t) => {
|
|
270
|
+
if (typeof t !== 'string')
|
|
271
|
+
return undefined;
|
|
272
|
+
const m = CLOCK_TIME.exec(t);
|
|
273
|
+
return m ? { hour: Number(m[1]), minute: Number(m[2]) } : undefined;
|
|
274
|
+
};
|
|
275
|
+
const MINUTE = 60_000;
|
|
276
|
+
const UNIT_MS = {
|
|
277
|
+
minutes: MINUTE,
|
|
278
|
+
hours: 60 * MINUTE,
|
|
279
|
+
days: 24 * 60 * MINUTE,
|
|
280
|
+
};
|
|
281
|
+
/** The system tick's grid: core emits system time to routines every 5 minutes (R15). @experimental */
|
|
282
|
+
export const SYSTEM_TICK_MINUTES = 5;
|
|
283
|
+
const isWhole = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
284
|
+
const SYSTEM_UNITS = ['minutes', 'hours', 'days'];
|
|
285
|
+
const STORY_UNITS = ['minutes', 'hours', 'days', 'months', 'years'];
|
|
286
|
+
function spanFindings(raw, at, units) {
|
|
287
|
+
if (!raw || typeof raw !== 'object')
|
|
288
|
+
return [`${at}: { every, unit } — a whole number and one of ${units.join(', ')}`];
|
|
289
|
+
const s = raw;
|
|
290
|
+
const out = [];
|
|
291
|
+
if (!isWhole(s.every) || s.every < 1)
|
|
292
|
+
out.push(`${at}.every: a whole number, 1 or more`);
|
|
293
|
+
if (!units.includes(s.unit))
|
|
294
|
+
out.push(`${at}.unit: one of ${units.join(', ')} — no seconds: core never counts finer than a minute (R10)`);
|
|
295
|
+
return out;
|
|
296
|
+
}
|
|
297
|
+
function scheduleAtFindings(raw, clock, at) {
|
|
298
|
+
const out = [];
|
|
299
|
+
const time = (t, where) => {
|
|
300
|
+
const p = parseClockTime(t);
|
|
301
|
+
if (!p)
|
|
302
|
+
out.push(`${where}: a time of day 'HH:MM', 24-hour`);
|
|
303
|
+
else if (p.minute % SYSTEM_TICK_MINUTES)
|
|
304
|
+
out.push(`${where}: '${String(t)}' is off the 5-minute grid — a schedule fires on whole 5 minutes (R20)`);
|
|
305
|
+
};
|
|
306
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
307
|
+
return [
|
|
308
|
+
`${at}: one of { once }, { daily }, { weekly: { weekday, time } }, { monthly: { day, time } }, { annually: { month, day, time } }`,
|
|
309
|
+
];
|
|
310
|
+
const keys = Object.keys(raw);
|
|
311
|
+
if (keys.length !== 1 || !['once', 'daily', 'weekly', 'monthly', 'annually'].includes(keys[0]))
|
|
312
|
+
return [`${at}: exactly one of once, daily, weekly, monthly, annually`];
|
|
313
|
+
const a = raw;
|
|
314
|
+
if ('once' in a) {
|
|
315
|
+
if (clock === 'system') {
|
|
316
|
+
const m = typeof a.once === 'string'
|
|
317
|
+
? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2})$/.exec(a.once)
|
|
318
|
+
: null;
|
|
319
|
+
if (!m)
|
|
320
|
+
out.push(`${at}.once: 'YYYY-MM-DDTHH:MM' in the session owner's time zone`);
|
|
321
|
+
else
|
|
322
|
+
time(m[4], `${at}.once`);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
const t = parseStoryTime(a.once);
|
|
326
|
+
if (!t)
|
|
327
|
+
out.push(`${at}.once: a story time line such as '412-03-05 22:30'`);
|
|
328
|
+
else if (t.minute != null && t.minute % SYSTEM_TICK_MINUTES)
|
|
329
|
+
out.push(`${at}.once: '${a.once}' is off the 5-minute grid (R20)`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
else if ('daily' in a)
|
|
333
|
+
time(a.daily, `${at}.daily`);
|
|
334
|
+
else if ('weekly' in a) {
|
|
335
|
+
if (!a.weekly ||
|
|
336
|
+
!isWhole(a.weekly.weekday) ||
|
|
337
|
+
a.weekly.weekday < 0 ||
|
|
338
|
+
(clock === 'system' && a.weekly.weekday > 6))
|
|
339
|
+
out.push(`${at}.weekly.weekday: ${clock === 'system' ? 'a whole number 0–6, 0 = Monday' : "a whole number indexing the calendar's weekdays, from 0"}`);
|
|
340
|
+
time(a.weekly?.time, `${at}.weekly.time`);
|
|
341
|
+
}
|
|
342
|
+
else if ('monthly' in a) {
|
|
343
|
+
if (!a.monthly ||
|
|
344
|
+
!isWhole(a.monthly.day) ||
|
|
345
|
+
a.monthly.day < 1 ||
|
|
346
|
+
(clock === 'system' && a.monthly.day > 31))
|
|
347
|
+
out.push(`${at}.monthly.day: a day of the month, from 1`);
|
|
348
|
+
time(a.monthly?.time, `${at}.monthly.time`);
|
|
349
|
+
}
|
|
350
|
+
else if ('annually' in a) {
|
|
351
|
+
const y = a.annually;
|
|
352
|
+
if (!y || !isWhole(y.month) || y.month < 1 || (clock === 'system' && y.month > 12))
|
|
353
|
+
out.push(`${at}.annually.month: a month, from 1`);
|
|
354
|
+
if (!y || !isWhole(y.day) || y.day < 1 || (clock === 'system' && y.day > 31))
|
|
355
|
+
out.push(`${at}.annually.day: a day of the month, from 1`);
|
|
356
|
+
time(y?.time, `${at}.annually.time`);
|
|
357
|
+
}
|
|
358
|
+
return out;
|
|
359
|
+
}
|
|
360
|
+
// ── Core's ten (PLAN-layering D2) ───────────────────────────────────────────
|
|
361
|
+
const HOST = 'host';
|
|
362
|
+
/** @experimental */
|
|
363
|
+
export const EVERY_N_TURNS = defineCadence({
|
|
364
|
+
id: 'core:cadence/every-n-turns@1',
|
|
365
|
+
i18n: {
|
|
366
|
+
name: { en: 'Every few turns' },
|
|
367
|
+
description: { en: 'Runs after every so many turns of the session.' },
|
|
368
|
+
},
|
|
369
|
+
options: {
|
|
370
|
+
n: {
|
|
371
|
+
type: 'integer',
|
|
372
|
+
min: 1,
|
|
373
|
+
max: 1000,
|
|
374
|
+
default: 5,
|
|
375
|
+
label: { en: 'Every how many turns' },
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
wakesOn: [TURN_ENDED_EVENT],
|
|
379
|
+
carries: ['session', 'message', 'speaker'],
|
|
380
|
+
evaluate: HOST,
|
|
381
|
+
});
|
|
382
|
+
/** @experimental */
|
|
383
|
+
export const AFTER_EACH_TURN = defineCadence({
|
|
384
|
+
id: 'core:cadence/after-each-turn@1',
|
|
385
|
+
i18n: {
|
|
386
|
+
name: { en: 'After each turn' },
|
|
387
|
+
description: { en: 'Runs after every turn, once what it set off has settled.' },
|
|
388
|
+
},
|
|
389
|
+
options: {},
|
|
390
|
+
wakesOn: [TURN_ENDED_EVENT],
|
|
391
|
+
carries: ['session', 'message', 'speaker'],
|
|
392
|
+
evaluate: HOST,
|
|
393
|
+
});
|
|
394
|
+
/** @experimental */
|
|
395
|
+
export const AFTER_EACH_ROUND = defineCadence({
|
|
396
|
+
id: 'core:cadence/after-each-round@1',
|
|
397
|
+
i18n: {
|
|
398
|
+
name: { en: 'After each round' },
|
|
399
|
+
description: { en: 'Runs once everyone the turn order seats has taken a turn.' },
|
|
400
|
+
},
|
|
401
|
+
options: {},
|
|
402
|
+
wakesOn: [ROUND_ENDED_EVENT],
|
|
403
|
+
carries: ['session'],
|
|
404
|
+
evaluate: HOST,
|
|
405
|
+
});
|
|
406
|
+
/** @experimental */
|
|
407
|
+
export const AFTER_EACH_SCENE = defineCadence({
|
|
408
|
+
id: 'core:cadence/after-each-scene@1',
|
|
409
|
+
i18n: { name: { en: 'After each scene' }, description: { en: 'Runs when a scene closes.' } },
|
|
410
|
+
options: {},
|
|
411
|
+
wakesOn: [SCENE_CLOSED_EVENT],
|
|
412
|
+
carries: ['session', 'scene'],
|
|
413
|
+
evaluate: HOST,
|
|
414
|
+
});
|
|
415
|
+
/** @experimental */
|
|
416
|
+
export const WHEN_IDLE = defineCadence({
|
|
417
|
+
id: 'core:cadence/when-idle@1',
|
|
418
|
+
i18n: {
|
|
419
|
+
name: { en: 'When nobody is playing' },
|
|
420
|
+
description: { en: 'Runs once after the session has gone quiet for a while.' },
|
|
421
|
+
},
|
|
422
|
+
options: {
|
|
423
|
+
minutes: {
|
|
424
|
+
type: 'integer',
|
|
425
|
+
min: 5,
|
|
426
|
+
default: 30,
|
|
427
|
+
label: { en: 'After how many quiet minutes' },
|
|
428
|
+
},
|
|
429
|
+
},
|
|
430
|
+
wakesOn: [SYSTEM_TICK_EVENT],
|
|
431
|
+
carries: ['session'],
|
|
432
|
+
clock: 'system',
|
|
433
|
+
evaluate: HOST,
|
|
434
|
+
});
|
|
435
|
+
/** @experimental */
|
|
436
|
+
export const ON_EVENT = defineCadence({
|
|
437
|
+
id: 'core:cadence/on-event@1',
|
|
438
|
+
i18n: {
|
|
439
|
+
name: { en: 'When something happens' },
|
|
440
|
+
description: {
|
|
441
|
+
en: 'Runs when a session event fires, optionally only when its own fields say so.',
|
|
442
|
+
},
|
|
443
|
+
},
|
|
444
|
+
options: {
|
|
445
|
+
event: { type: 'string', label: { en: 'Event' } },
|
|
446
|
+
where: { type: 'text', format: 'json', label: { en: 'Only when' } },
|
|
447
|
+
},
|
|
448
|
+
wakesOn: [ANY_EVENT],
|
|
449
|
+
// What the event carries — `cadenceCarries` reads the named event's.
|
|
450
|
+
carries: ['session'],
|
|
451
|
+
evaluate: HOST,
|
|
452
|
+
});
|
|
453
|
+
/** @experimental */
|
|
454
|
+
export const WHEN_VALUE = defineCadence({
|
|
455
|
+
id: 'core:cadence/when-value@1',
|
|
456
|
+
i18n: {
|
|
457
|
+
name: { en: 'When a value says so' },
|
|
458
|
+
description: { en: "Runs when a condition over the session's values becomes true." },
|
|
459
|
+
},
|
|
460
|
+
options: { when: { type: 'text', format: 'json', label: { en: 'When' } } },
|
|
461
|
+
wakesOn: [ANY_EVENT],
|
|
462
|
+
carries: ['session', 'slot'],
|
|
463
|
+
evaluate: HOST,
|
|
464
|
+
});
|
|
465
|
+
/** @experimental */
|
|
466
|
+
export const SYSTEM_CRON = defineCadence({
|
|
467
|
+
id: 'core:cadence/system-cron@1',
|
|
468
|
+
i18n: {
|
|
469
|
+
name: { en: 'System Cron' },
|
|
470
|
+
description: { en: 'Runs every so often in real time — every 5 minutes at the finest.' },
|
|
471
|
+
},
|
|
472
|
+
options: {
|
|
473
|
+
every: { type: 'integer', min: 1, default: 1, label: { en: 'Every' } },
|
|
474
|
+
unit: { type: 'enum', of: SYSTEM_UNITS, default: 'hours', label: { en: 'Unit' } },
|
|
475
|
+
},
|
|
476
|
+
wakesOn: [SYSTEM_TICK_EVENT],
|
|
477
|
+
carries: ['session'],
|
|
478
|
+
clock: 'system',
|
|
479
|
+
evaluate: HOST,
|
|
480
|
+
});
|
|
481
|
+
/** @experimental */
|
|
482
|
+
export const TIMELINE_CRON = defineCadence({
|
|
483
|
+
id: 'core:cadence/timeline-cron@1',
|
|
484
|
+
i18n: {
|
|
485
|
+
name: { en: 'Timeline Cron' },
|
|
486
|
+
description: {
|
|
487
|
+
en: "Runs every so often in story time, counted on the session's story calendar.",
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
options: {
|
|
491
|
+
every: { type: 'integer', min: 1, default: 1, label: { en: 'Every' } },
|
|
492
|
+
unit: { type: 'enum', of: STORY_UNITS, default: 'days', label: { en: 'Unit' } },
|
|
493
|
+
maxJump: {
|
|
494
|
+
type: 'object',
|
|
495
|
+
label: { en: 'Skip when the clock jumps more than …' },
|
|
496
|
+
fields: {
|
|
497
|
+
every: { type: 'integer', min: 1, label: { en: 'More than' } },
|
|
498
|
+
unit: { type: 'enum', of: STORY_UNITS, label: { en: 'Unit' } },
|
|
499
|
+
},
|
|
500
|
+
},
|
|
501
|
+
},
|
|
502
|
+
wakesOn: [STORY_CLOCK_MOVED_EVENT],
|
|
503
|
+
carries: ['session', 'clock'],
|
|
504
|
+
clock: 'story',
|
|
505
|
+
evaluate: HOST,
|
|
506
|
+
});
|
|
507
|
+
/** @experimental */
|
|
508
|
+
export const SCHEDULE = defineCadence({
|
|
509
|
+
id: 'core:cadence/schedule@1',
|
|
510
|
+
i18n: {
|
|
511
|
+
name: { en: 'Schedule' },
|
|
512
|
+
description: {
|
|
513
|
+
en: 'Runs at set moments — once, daily, weekly, monthly or yearly — in real time or story time.',
|
|
514
|
+
},
|
|
515
|
+
},
|
|
516
|
+
options: {
|
|
517
|
+
clock: {
|
|
518
|
+
type: 'enum',
|
|
519
|
+
of: ['system', 'story'],
|
|
520
|
+
default: 'system',
|
|
521
|
+
label: { en: 'Clock' },
|
|
522
|
+
},
|
|
523
|
+
at: { type: 'text', format: 'json', label: { en: 'When' } },
|
|
524
|
+
maxJump: {
|
|
525
|
+
type: 'object',
|
|
526
|
+
label: { en: 'Skip when the clock jumps more than …' },
|
|
527
|
+
fields: {
|
|
528
|
+
every: { type: 'integer', min: 1, label: { en: 'More than' } },
|
|
529
|
+
unit: { type: 'enum', of: STORY_UNITS, label: { en: 'Unit' } },
|
|
530
|
+
},
|
|
531
|
+
},
|
|
532
|
+
},
|
|
533
|
+
wakesOn: [SYSTEM_TICK_EVENT, STORY_CLOCK_MOVED_EVENT],
|
|
534
|
+
carries: ['session'],
|
|
535
|
+
evaluate: HOST,
|
|
536
|
+
});
|
|
537
|
+
/** Core's cadences, by name. @experimental */
|
|
538
|
+
export const coreCadences = Object.freeze({
|
|
539
|
+
everyNTurns: EVERY_N_TURNS,
|
|
540
|
+
afterEachTurn: AFTER_EACH_TURN,
|
|
541
|
+
afterEachRound: AFTER_EACH_ROUND,
|
|
542
|
+
afterEachScene: AFTER_EACH_SCENE,
|
|
543
|
+
whenIdle: WHEN_IDLE,
|
|
544
|
+
onEvent: ON_EVENT,
|
|
545
|
+
whenValue: WHEN_VALUE,
|
|
546
|
+
systemCron: SYSTEM_CRON,
|
|
547
|
+
timelineCron: TIMELINE_CRON,
|
|
548
|
+
schedule: SCHEDULE,
|
|
549
|
+
});
|
|
550
|
+
// ── Validation ──────────────────────────────────────────────────────────────
|
|
551
|
+
/** Options validated by their own rules rather than `checkValues` (JSON values, nested objects). */
|
|
552
|
+
const CUSTOM_OPTIONS = new Set(['where', 'when', 'at', 'maxJump', 'event']);
|
|
553
|
+
/**
|
|
554
|
+
* Every fault in a cadence reference: an undeclared cadence, an option it
|
|
555
|
+
* does not declare, a value its declaration refuses — and the rulings: a
|
|
556
|
+
* System Cron in minutes is a multiple of 5 and at least 5 (R15), a Timeline
|
|
557
|
+
* Cron at least one minute, a Schedule on the 5-minute grid (R20), no seconds
|
|
558
|
+
* anywhere (R10). As sentences that say what to do instead.
|
|
559
|
+
* @experimental
|
|
560
|
+
* @ruling R10, R15, R20
|
|
561
|
+
*/
|
|
562
|
+
export function cadenceOptionFindings(ref, at = 'cadence') {
|
|
563
|
+
if (!ref || typeof ref !== 'object')
|
|
564
|
+
return [
|
|
565
|
+
`${at}: a cadence is { id, options } — make one with everyNTurns(…), systemCron(…), …`,
|
|
566
|
+
];
|
|
567
|
+
const def = getCadence(ref.id);
|
|
568
|
+
if (!def)
|
|
569
|
+
return [
|
|
570
|
+
`${at}: '${String(ref.id)}' is not a declared cadence — core's are ${allCadences()
|
|
571
|
+
.filter((c) => c.id.startsWith('core:'))
|
|
572
|
+
.map((c) => cadenceSlugOf(c.id))
|
|
573
|
+
.join(', ')}`,
|
|
574
|
+
];
|
|
575
|
+
const options = (ref.options ?? {});
|
|
576
|
+
if (typeof options !== 'object' || Array.isArray(options))
|
|
577
|
+
return [`${at}.options: a map of option values`];
|
|
578
|
+
const out = [];
|
|
579
|
+
for (const k of Object.keys(options))
|
|
580
|
+
if (!(k in def.options))
|
|
581
|
+
out.push(`${at}.options.${k}: ${cadenceSlugOf(def.id)} takes ${Object.keys(def.options).join(', ') || 'no options'}`);
|
|
582
|
+
// Core's JSON-valued options (`where`, `when`, `at`, …) are judged by their
|
|
583
|
+
// own rules below; a plugin's options are all its declarations' to judge.
|
|
584
|
+
const custom = def.id.startsWith('core:') ? CUSTOM_OPTIONS : new Set();
|
|
585
|
+
const plain = Object.fromEntries(Object.entries(def.options).filter(([k]) => !custom.has(k)));
|
|
586
|
+
for (const f of checkValues(plain, options))
|
|
587
|
+
out.push(`${at}.options: ${f.message} — ${f.fix}`);
|
|
588
|
+
if (typeof options.unit === 'string' && /^sec/i.test(options.unit))
|
|
589
|
+
out.push(`${at}.options.unit: no seconds — core never counts finer than a minute (R10)`);
|
|
590
|
+
const slug = def.id.startsWith('core:') ? cadenceSlugOf(def.id) : '';
|
|
591
|
+
switch (slug) {
|
|
592
|
+
case 'system-cron':
|
|
593
|
+
if (options.unit === 'minutes' &&
|
|
594
|
+
isWhole(options.every) &&
|
|
595
|
+
(options.every < SYSTEM_TICK_MINUTES || options.every % SYSTEM_TICK_MINUTES))
|
|
596
|
+
out.push(`${at}.options.every: a System Cron in minutes runs every 5, 10, 15 … minutes — core ticks routines every 5 minutes, never finer (R15)`);
|
|
597
|
+
break;
|
|
598
|
+
case 'timeline-cron':
|
|
599
|
+
if (options.maxJump !== undefined)
|
|
600
|
+
out.push(...spanFindings(options.maxJump, `${at}.options.maxJump`, STORY_UNITS));
|
|
601
|
+
break;
|
|
602
|
+
case 'when-idle':
|
|
603
|
+
if (isWhole(options.minutes) && options.minutes % SYSTEM_TICK_MINUTES)
|
|
604
|
+
out.push(`${at}.options.minutes: a multiple of 5 — the session's quiet is checked on the 5-minute tick (R15)`);
|
|
605
|
+
break;
|
|
606
|
+
case 'on-event': {
|
|
607
|
+
const ev = options.event;
|
|
608
|
+
if (typeof ev !== 'string' || !ev)
|
|
609
|
+
out.push(`${at}.options.event: the event it listens to — onEvent(coreEvents.…)`);
|
|
610
|
+
else if (!eventById(ev))
|
|
611
|
+
out.push(`${at}.options.event: ${notADeclaredEvent(ev)}`);
|
|
612
|
+
if (options.where !== undefined)
|
|
613
|
+
out.push(...conditionFindings(options.where, `${at}.options.where`));
|
|
614
|
+
break;
|
|
615
|
+
}
|
|
616
|
+
case 'when-value':
|
|
617
|
+
if (options.when === undefined)
|
|
618
|
+
out.push(`${at}.options.when: the condition it waits for — whenValue({ when })`);
|
|
619
|
+
else
|
|
620
|
+
out.push(...conditionFindings(options.when, `${at}.options.when`));
|
|
621
|
+
break;
|
|
622
|
+
case 'schedule': {
|
|
623
|
+
const clock = options.clock ?? 'system';
|
|
624
|
+
if (clock !== 'system' && clock !== 'story')
|
|
625
|
+
break;
|
|
626
|
+
if (options.at === undefined) {
|
|
627
|
+
out.push(`${at}.options.at: when it fires — { once }, { daily }, { weekly }, { monthly } or { annually }`);
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
out.push(...scheduleAtFindings(options.at, clock, `${at}.options.at`));
|
|
631
|
+
if (options.maxJump !== undefined) {
|
|
632
|
+
if (clock !== 'story')
|
|
633
|
+
out.push(`${at}.options.maxJump: only a story-clock schedule skips long clock jumps — after a restart a system schedule waits for an interaction (R21)`);
|
|
634
|
+
else
|
|
635
|
+
out.push(...spanFindings(options.maxJump, `${at}.options.maxJump`, STORY_UNITS));
|
|
636
|
+
}
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* A reference's options with every option it leaves out at its declared
|
|
644
|
+
* default — what the due-function reads, and what a settings form shows.
|
|
645
|
+
* @experimental
|
|
646
|
+
*/
|
|
647
|
+
export function cadenceOptionsOf(ref) {
|
|
648
|
+
const def = getCadence(ref.id);
|
|
649
|
+
const out = {};
|
|
650
|
+
for (const [k, d] of Object.entries(def?.options ?? {}))
|
|
651
|
+
if (d.default !== undefined)
|
|
652
|
+
out[k] = d.default;
|
|
653
|
+
return { ...out, ...(ref.options ?? {}) };
|
|
654
|
+
}
|
|
655
|
+
/** The clock a cadence reference counts on, if any — `story` needs a session with a story clock. @experimental */
|
|
656
|
+
export function cadenceClock(ref) {
|
|
657
|
+
const def = getCadence(ref.id);
|
|
658
|
+
if (!def)
|
|
659
|
+
return undefined;
|
|
660
|
+
if (def.clock)
|
|
661
|
+
return def.clock;
|
|
662
|
+
if (def.id === SCHEDULE.id)
|
|
663
|
+
return ref.options?.clock === 'story' ? 'story' : 'system';
|
|
664
|
+
return undefined;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* What a cadence reference's `cause` carries — its declaration's `carries`,
|
|
668
|
+
* except where an option decides: `onEvent` carries what its event carries,
|
|
669
|
+
* and a story-clock `schedule` carries the story clock.
|
|
670
|
+
* @experimental
|
|
671
|
+
* @ruling R9, R12
|
|
672
|
+
*/
|
|
673
|
+
export function cadenceCarries(ref) {
|
|
674
|
+
const def = getCadence(ref.id);
|
|
675
|
+
if (!def)
|
|
676
|
+
return ['session'];
|
|
677
|
+
if (def.id === ON_EVENT.id) {
|
|
678
|
+
const ev = typeof ref.options?.event === 'string' ? eventById(ref.options.event) : undefined;
|
|
679
|
+
return [...(ev?.carries ?? ['session'])];
|
|
680
|
+
}
|
|
681
|
+
if (def.id === SCHEDULE.id && ref.options?.clock === 'story')
|
|
682
|
+
return ['session', 'clock'];
|
|
683
|
+
return [...def.carries];
|
|
684
|
+
}
|
|
685
|
+
const freezeRef = (id, options) => {
|
|
686
|
+
const ref = Object.freeze({ id, options: Object.freeze(options) });
|
|
687
|
+
const found = cadenceOptionFindings(ref, cadenceSlugOf(id));
|
|
688
|
+
if (found.length)
|
|
689
|
+
throw new Error(`cadence refused:\n · ${found.join('\n · ')}`);
|
|
690
|
+
return ref;
|
|
691
|
+
};
|
|
692
|
+
// ── The ready-made cadences (each returns a `CadenceRef`) ───────────────────
|
|
693
|
+
/** Every `n` turns — the 5th, the 10th, … @experimental */
|
|
694
|
+
export const everyNTurns = (o) => freezeRef(EVERY_N_TURNS.id, { n: o?.n });
|
|
695
|
+
/** After every turn. @experimental */
|
|
696
|
+
export const afterEachTurn = () => freezeRef(AFTER_EACH_TURN.id, {});
|
|
697
|
+
/** After every round — the "wait for everyone". @experimental */
|
|
698
|
+
export const afterEachRound = () => freezeRef(AFTER_EACH_ROUND.id, {});
|
|
699
|
+
/** After every scene closes. @experimental */
|
|
700
|
+
export const afterEachScene = () => freezeRef(AFTER_EACH_SCENE.id, {});
|
|
701
|
+
/** Once, after the session has been quiet for `minutes` (a multiple of 5). @experimental */
|
|
702
|
+
export const whenIdle = (o) => freezeRef(WHEN_IDLE.id, { minutes: o?.minutes });
|
|
703
|
+
/**
|
|
704
|
+
* When a session event fires — `onEvent(coreEvents.castChanged, { where: … })`
|
|
705
|
+
* — optionally only when a condition over the event's own payload holds.
|
|
706
|
+
* @experimental
|
|
707
|
+
*/
|
|
708
|
+
export const onEvent = (event, o = {}) => freezeRef(ON_EVENT.id, {
|
|
709
|
+
event: eventIdOf(event),
|
|
710
|
+
...(o.where !== undefined ? { where: o.where } : {}),
|
|
711
|
+
});
|
|
712
|
+
/** When a condition over the session's published values becomes true. @experimental */
|
|
713
|
+
export const whenValue = (o) => freezeRef(WHEN_VALUE.id, { when: o?.when });
|
|
714
|
+
/** Every so often in real time — minutes in multiples of 5 (R15), hours, days. @experimental */
|
|
715
|
+
export const systemCron = (o) => freezeRef(SYSTEM_CRON.id, { every: o?.every, unit: o?.unit });
|
|
716
|
+
/**
|
|
717
|
+
* Every so often in story time, on the session's calendar (R10). `maxJump`:
|
|
718
|
+
* "Skip when the clock jumps more than …" (R19).
|
|
719
|
+
* @experimental
|
|
720
|
+
*/
|
|
721
|
+
export const timelineCron = (o) => freezeRef(TIMELINE_CRON.id, {
|
|
722
|
+
every: o?.every,
|
|
723
|
+
unit: o?.unit,
|
|
724
|
+
...(o?.maxJump ? { maxJump: { ...o.maxJump } } : {}),
|
|
725
|
+
});
|
|
726
|
+
/**
|
|
727
|
+
* 🚧 Once each story day (M0, SHAPES L3): `timelineCron({ every: 1,
|
|
728
|
+
* unit: 'days' })` by name — what the weather routine and a nightly diary
|
|
729
|
+
* run on. A helper over the Timeline Cron, not a cadence of its own.
|
|
730
|
+
* @experimental
|
|
731
|
+
*/
|
|
732
|
+
export const afterEachDay = () => timelineCron({ every: 1, unit: 'days' });
|
|
733
|
+
/** At set moments on the system clock or the story calendar (R20). @experimental */
|
|
734
|
+
export const schedule = (o) => freezeRef(SCHEDULE.id, {
|
|
735
|
+
clock: o?.clock,
|
|
736
|
+
at: o?.at,
|
|
737
|
+
...(o?.maxJump ? { maxJump: { ...o.maxJump } } : {}),
|
|
738
|
+
});
|
|
739
|
+
const no = (state, reason) => ({ due: false, state, reason });
|
|
740
|
+
const spanText = (s) => `${s.every} ${s.every === 1 ? s.unit.replace(/s$/, '') : s.unit}`;
|
|
741
|
+
/**
|
|
742
|
+
* Whether a move of the story clock from `from` to `to` is larger than the
|
|
743
|
+
* ceiling — `undefined` when the ceiling cannot be counted from `from`.
|
|
744
|
+
*/
|
|
745
|
+
function jumpsPast(from, to, ceiling, calendar) {
|
|
746
|
+
const limit = advanceStoryTime(from, ceiling.every, ceiling.unit, calendar);
|
|
747
|
+
if (!limit.time)
|
|
748
|
+
return undefined;
|
|
749
|
+
return compareStoryTimes(to, limit.time) > 0;
|
|
750
|
+
}
|
|
751
|
+
/** A story time on `day`'s date at `hour:minute`. */
|
|
752
|
+
const atTime = (day, t) => ({
|
|
753
|
+
year: day.year,
|
|
754
|
+
month: day.month ?? null,
|
|
755
|
+
day: day.day ?? null,
|
|
756
|
+
hour: t.hour,
|
|
757
|
+
minute: t.minute,
|
|
758
|
+
});
|
|
759
|
+
/**
|
|
760
|
+
* The first occurrence of a schedule strictly after `after`, on a story
|
|
761
|
+
* calendar — or `null` when the clock cannot place one (a daily schedule on
|
|
762
|
+
* a clock with no day, a weekly one on a calendar with no week).
|
|
763
|
+
* @experimental
|
|
764
|
+
* @ruling R20
|
|
765
|
+
*/
|
|
766
|
+
export function nextStoryOccurrence(after, at, calendar) {
|
|
767
|
+
const later = (t) => compareStoryTimes(t, after) > 0;
|
|
768
|
+
if ('once' in at) {
|
|
769
|
+
const t = parseStoryTime(at.once);
|
|
770
|
+
return t && later(t) ? t : null;
|
|
771
|
+
}
|
|
772
|
+
const hasDay = after.month != null && after.day != null;
|
|
773
|
+
if ('daily' in at) {
|
|
774
|
+
const t = parseClockTime(at.daily);
|
|
775
|
+
if (!t || !hasDay)
|
|
776
|
+
return null;
|
|
777
|
+
const today = atTime(after, t);
|
|
778
|
+
if (later(today))
|
|
779
|
+
return today;
|
|
780
|
+
return advanceStoryTime(today, 1, 'days', calendar).time ?? null;
|
|
781
|
+
}
|
|
782
|
+
if ('weekly' in at) {
|
|
783
|
+
const t = parseClockTime(at.weekly.time);
|
|
784
|
+
const week = calendar?.weekdays ?? [];
|
|
785
|
+
if (!t || !hasDay || !calendar || !week.length)
|
|
786
|
+
return null;
|
|
787
|
+
for (let i = 0; i <= week.length; i++) {
|
|
788
|
+
const day = i === 0
|
|
789
|
+
? atTime(after, t)
|
|
790
|
+
: advanceStoryTime(atTime(after, t), i, 'days', calendar).time;
|
|
791
|
+
if (!day)
|
|
792
|
+
return null;
|
|
793
|
+
const index = storyDayIndex(day, calendar);
|
|
794
|
+
if (index === null)
|
|
795
|
+
continue;
|
|
796
|
+
const weekday = (((index + (calendar.firstWeekday ?? 0)) % week.length) + week.length) % week.length;
|
|
797
|
+
if (weekday === at.weekly.weekday && later(day))
|
|
798
|
+
return day;
|
|
799
|
+
}
|
|
800
|
+
return null;
|
|
801
|
+
}
|
|
802
|
+
if ('monthly' in at) {
|
|
803
|
+
const t = parseClockTime(at.monthly.time);
|
|
804
|
+
if (!t || after.month == null)
|
|
805
|
+
return null;
|
|
806
|
+
const months = calendar?.months.length ?? 12;
|
|
807
|
+
for (let k = 0; k <= months * 2 + 1; k++) {
|
|
808
|
+
const month = k === 0
|
|
809
|
+
? { year: after.year, month: after.month }
|
|
810
|
+
: advanceStoryTime({ year: after.year, month: after.month }, k, 'months', calendar).time;
|
|
811
|
+
if (!month || month.month == null)
|
|
812
|
+
return null;
|
|
813
|
+
const candidate = {
|
|
814
|
+
year: month.year,
|
|
815
|
+
month: month.month,
|
|
816
|
+
day: at.monthly.day,
|
|
817
|
+
hour: t.hour,
|
|
818
|
+
minute: t.minute,
|
|
819
|
+
};
|
|
820
|
+
if (storyTimeProblem(candidate, calendar))
|
|
821
|
+
continue;
|
|
822
|
+
if (later(candidate))
|
|
823
|
+
return candidate;
|
|
824
|
+
}
|
|
825
|
+
return null;
|
|
826
|
+
}
|
|
827
|
+
if ('annually' in at) {
|
|
828
|
+
const t = parseClockTime(at.annually.time);
|
|
829
|
+
if (!t)
|
|
830
|
+
return null;
|
|
831
|
+
const cycle = Math.max(1, calendar?.leap?.every ?? 1) * 2 + 1;
|
|
832
|
+
for (let k = 0; k <= Math.min(cycle, 1000); k++) {
|
|
833
|
+
const candidate = {
|
|
834
|
+
year: after.year + k,
|
|
835
|
+
month: at.annually.month,
|
|
836
|
+
day: at.annually.day,
|
|
837
|
+
hour: t.hour,
|
|
838
|
+
minute: t.minute,
|
|
839
|
+
};
|
|
840
|
+
if (storyTimeProblem(candidate, calendar))
|
|
841
|
+
continue;
|
|
842
|
+
if (later(candidate))
|
|
843
|
+
return candidate;
|
|
844
|
+
}
|
|
845
|
+
return null;
|
|
846
|
+
}
|
|
847
|
+
return null;
|
|
848
|
+
}
|
|
849
|
+
const WEEKDAY_INDEX = {
|
|
850
|
+
Mon: 0,
|
|
851
|
+
Tue: 1,
|
|
852
|
+
Wed: 2,
|
|
853
|
+
Thu: 3,
|
|
854
|
+
Fri: 4,
|
|
855
|
+
Sat: 5,
|
|
856
|
+
Sun: 6,
|
|
857
|
+
};
|
|
858
|
+
/** The wall-clock parts of an instant in a time zone. */
|
|
859
|
+
function wallClock(at, timeZone) {
|
|
860
|
+
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', {
|
|
861
|
+
timeZone,
|
|
862
|
+
year: 'numeric',
|
|
863
|
+
month: '2-digit',
|
|
864
|
+
day: '2-digit',
|
|
865
|
+
hour: '2-digit',
|
|
866
|
+
minute: '2-digit',
|
|
867
|
+
weekday: 'short',
|
|
868
|
+
hourCycle: 'h23',
|
|
869
|
+
})
|
|
870
|
+
.formatToParts(new Date(at))
|
|
871
|
+
.map((p) => [p.type, p.value]));
|
|
872
|
+
return {
|
|
873
|
+
year: Number(parts.year),
|
|
874
|
+
month: Number(parts.month),
|
|
875
|
+
day: Number(parts.day),
|
|
876
|
+
hour: Number(parts.hour) % 24,
|
|
877
|
+
minute: Number(parts.minute),
|
|
878
|
+
weekday: WEEKDAY_INDEX[parts.weekday] ?? 0,
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
882
|
+
/** Does the wall-clock moment match the schedule? */
|
|
883
|
+
function wallMatches(w, at) {
|
|
884
|
+
const hhmm = `${pad(w.hour)}:${pad(w.minute)}`;
|
|
885
|
+
if ('once' in at)
|
|
886
|
+
return at.once === `${w.year}-${pad(w.month)}-${pad(w.day)}T${hhmm}`;
|
|
887
|
+
if ('daily' in at)
|
|
888
|
+
return at.daily === hhmm;
|
|
889
|
+
if ('weekly' in at)
|
|
890
|
+
return at.weekly.weekday === w.weekday && at.weekly.time === hhmm;
|
|
891
|
+
if ('monthly' in at)
|
|
892
|
+
return at.monthly.day === w.day && at.monthly.time === hhmm;
|
|
893
|
+
if ('annually' in at)
|
|
894
|
+
return (at.annually.month === w.month && at.annually.day === w.day && at.annually.time === hhmm);
|
|
895
|
+
return false;
|
|
896
|
+
}
|
|
897
|
+
/** The most 5-minute grid points one system tick looks back over — a week. */
|
|
898
|
+
const MAX_GRID_LOOKBACK = (7 * 24 * 60) / SYSTEM_TICK_MINUTES;
|
|
899
|
+
/**
|
|
900
|
+
* Whether a system-clock schedule has an occurrence in `(after, upTo]`, read
|
|
901
|
+
* on the 5-minute grid in `timeZone`. Fires once however many it passed
|
|
902
|
+
* (no catch-up, R19/R21).
|
|
903
|
+
* @experimental
|
|
904
|
+
*/
|
|
905
|
+
export function systemScheduleDue(after, upTo, at, timeZone = 'UTC') {
|
|
906
|
+
const step = SYSTEM_TICK_MINUTES * MINUTE;
|
|
907
|
+
let t = Math.floor(after / step) * step + step;
|
|
908
|
+
const earliest = upTo - MAX_GRID_LOOKBACK * step;
|
|
909
|
+
if (t < earliest)
|
|
910
|
+
t = Math.ceil(earliest / step) * step;
|
|
911
|
+
for (; t <= upTo; t += step)
|
|
912
|
+
if (wallMatches(wallClock(t, timeZone), at))
|
|
913
|
+
return true;
|
|
914
|
+
return false;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* One event's answer for one cadence reference: due or not, the state to
|
|
918
|
+
* keep, and why when it is not. Pure — the host evaluates core's cadences
|
|
919
|
+
* with exactly this, and `simulateCadence` drives it for a test. An event
|
|
920
|
+
* the cadence does not wake on is never due. A plugin's cadence is evaluated
|
|
921
|
+
* by its script, not here (`simulateCadence` takes an `evaluate` stand-in).
|
|
922
|
+
* ⏳ A moment in the shape before events (`{ kind }`) is read as its event
|
|
923
|
+
* (`cadenceEventOf`).
|
|
924
|
+
* @experimental
|
|
925
|
+
* @ruling R9, R15, R17, R19, R20, R21, D11
|
|
926
|
+
*/
|
|
927
|
+
export function cadenceDue(ref, event, state = {}) {
|
|
928
|
+
const def = getCadence(ref.id);
|
|
929
|
+
if (!def)
|
|
930
|
+
return no(state, `'${ref.id}' is not a declared cadence`);
|
|
931
|
+
const e = cadenceEventOf(event);
|
|
932
|
+
if (!cadenceWakesOn(def, e.event))
|
|
933
|
+
return no(state, `${cadenceSlugOf(def.id)} sleeps at ${eventWord(e.event)}`);
|
|
934
|
+
if (def.evaluate !== 'host')
|
|
935
|
+
return no(state, `${cadenceSlugOf(def.id)} is decided by its script, on the host`);
|
|
936
|
+
const o = cadenceOptionsOf(ref);
|
|
937
|
+
// The known events, by id; any other is `{ event, payload, values }`.
|
|
938
|
+
const m = e;
|
|
939
|
+
switch (def.id) {
|
|
940
|
+
case EVERY_N_TURNS.id: {
|
|
941
|
+
if (m.event !== TURN_ENDED_EVENT)
|
|
942
|
+
break;
|
|
943
|
+
const n = isWhole(o.n) && o.n >= 1 ? o.n : 5;
|
|
944
|
+
return m.turn >= 1 && m.turn % n === 0
|
|
945
|
+
? { due: true, state }
|
|
946
|
+
: no(state, `turn ${m.turn} is not a multiple of ${n}`);
|
|
947
|
+
}
|
|
948
|
+
case AFTER_EACH_TURN.id:
|
|
949
|
+
case AFTER_EACH_ROUND.id:
|
|
950
|
+
case AFTER_EACH_SCENE.id:
|
|
951
|
+
return { due: true, state };
|
|
952
|
+
case WHEN_IDLE.id: {
|
|
953
|
+
if (m.event !== SYSTEM_TICK_EVENT)
|
|
954
|
+
break;
|
|
955
|
+
const last = m.lastInteractionAt;
|
|
956
|
+
if (last == null)
|
|
957
|
+
return no(state, 'nobody has played since the app started');
|
|
958
|
+
const quiet = m.at - last;
|
|
959
|
+
if (quiet < (isWhole(o.minutes) ? o.minutes : 30) * MINUTE)
|
|
960
|
+
return no(state, 'the session is not quiet long enough yet');
|
|
961
|
+
if (state.firedFor === last)
|
|
962
|
+
return no(state, 'already ran for this quiet stretch');
|
|
963
|
+
return { due: true, state: { firedFor: last } };
|
|
964
|
+
}
|
|
965
|
+
case ON_EVENT.id: {
|
|
966
|
+
if (m.event !== o.event)
|
|
967
|
+
return no(state, `listens to ${String(o.event)}, not ${m.event}`);
|
|
968
|
+
return evaluateCondition(o.where, m.payload)
|
|
969
|
+
? { due: true, state }
|
|
970
|
+
: no(state, "the event's fields do not match");
|
|
971
|
+
}
|
|
972
|
+
case WHEN_VALUE.id: {
|
|
973
|
+
if (m.values === undefined)
|
|
974
|
+
return no(state, 'no published values came with the event');
|
|
975
|
+
const holds = evaluateCondition(o.when, m.values);
|
|
976
|
+
if (!holds)
|
|
977
|
+
return no({ held: false }, 'the condition does not hold');
|
|
978
|
+
// Edge-triggered: once when it becomes true, not on every change while it stays true.
|
|
979
|
+
return state.held === true
|
|
980
|
+
? no({ held: true }, 'the condition already held')
|
|
981
|
+
: { due: true, state: { held: true } };
|
|
982
|
+
}
|
|
983
|
+
case SYSTEM_CRON.id: {
|
|
984
|
+
if (m.event !== SYSTEM_TICK_EVENT)
|
|
985
|
+
break;
|
|
986
|
+
const unit = SYSTEM_UNITS.includes(o.unit)
|
|
987
|
+
? o.unit
|
|
988
|
+
: 'hours';
|
|
989
|
+
const interval = (isWhole(o.every) && o.every >= 1 ? o.every : 1) * UNIT_MS[unit];
|
|
990
|
+
const nextAt = typeof state.nextAt === 'number' ? state.nextAt : undefined;
|
|
991
|
+
// Counted from the first tick it sees — after a restart, from the
|
|
992
|
+
// first interaction (the host clears the state, R21).
|
|
993
|
+
if (nextAt === undefined)
|
|
994
|
+
return no({ nextAt: m.at + interval }, 'counting from now');
|
|
995
|
+
if (m.at < nextAt)
|
|
996
|
+
return no(state, 'not due yet');
|
|
997
|
+
// Once, however many intervals passed (no catch-up, R19), and the
|
|
998
|
+
// next time counts from this run.
|
|
999
|
+
return { due: true, state: { nextAt: m.at + interval } };
|
|
1000
|
+
}
|
|
1001
|
+
case TIMELINE_CRON.id: {
|
|
1002
|
+
if (m.event !== STORY_CLOCK_MOVED_EVENT)
|
|
1003
|
+
break;
|
|
1004
|
+
const cal = m.calendar ?? null;
|
|
1005
|
+
if (compareStoryTimes(m.to, m.from) <= 0)
|
|
1006
|
+
return no(state, 'the story clock did not move forward');
|
|
1007
|
+
const unit = STORY_UNITS.includes(o.unit)
|
|
1008
|
+
? o.unit
|
|
1009
|
+
: 'days';
|
|
1010
|
+
const every = isWhole(o.every) && o.every >= 1 ? o.every : 1;
|
|
1011
|
+
let next = typeof state.nextAt === 'string' ? parseStoryTime(state.nextAt) : null;
|
|
1012
|
+
if (!next) {
|
|
1013
|
+
const first = advanceStoryTime(m.from, every, unit, cal);
|
|
1014
|
+
if (!first.time)
|
|
1015
|
+
return no(state, first.problem);
|
|
1016
|
+
next = first.time;
|
|
1017
|
+
}
|
|
1018
|
+
const kept = { nextAt: storyTimeText(next) };
|
|
1019
|
+
if (o.maxJump && jumpsPast(m.from, m.to, o.maxJump, cal))
|
|
1020
|
+
return no(kept, `Skipped: the clock jumped more than ${spanText(o.maxJump)}`);
|
|
1021
|
+
if (compareStoryTimes(m.to, next) < 0)
|
|
1022
|
+
return no(kept, 'not due yet');
|
|
1023
|
+
// Once per move (R17), and the next time counts from where the clock stands.
|
|
1024
|
+
const after = advanceStoryTime(m.to, every, unit, cal);
|
|
1025
|
+
return { due: true, state: after.time ? { nextAt: storyTimeText(after.time) } : {} };
|
|
1026
|
+
}
|
|
1027
|
+
case SCHEDULE.id: {
|
|
1028
|
+
const at = o.at;
|
|
1029
|
+
if (state.done === true)
|
|
1030
|
+
return no(state, 'a once schedule already ran');
|
|
1031
|
+
const once = !!at && 'once' in at;
|
|
1032
|
+
if (o.clock === 'story') {
|
|
1033
|
+
if (m.event !== STORY_CLOCK_MOVED_EVENT)
|
|
1034
|
+
return no(state, 'a story-clock schedule sleeps at the system tick');
|
|
1035
|
+
const cal = m.calendar ?? null;
|
|
1036
|
+
if (compareStoryTimes(m.to, m.from) <= 0)
|
|
1037
|
+
return no(state, 'the story clock did not move forward');
|
|
1038
|
+
if (o.maxJump && jumpsPast(m.from, m.to, o.maxJump, cal))
|
|
1039
|
+
return no(state, `Skipped: the clock jumped more than ${spanText(o.maxJump)}`);
|
|
1040
|
+
const occ = nextStoryOccurrence(m.from, at, cal);
|
|
1041
|
+
if (!occ)
|
|
1042
|
+
return no(state, 'the story clock cannot place this schedule');
|
|
1043
|
+
if (compareStoryTimes(occ, m.to) > 0)
|
|
1044
|
+
return no(state, 'not due yet');
|
|
1045
|
+
return { due: true, state: once ? { done: true } : state };
|
|
1046
|
+
}
|
|
1047
|
+
if (m.event !== SYSTEM_TICK_EVENT)
|
|
1048
|
+
return no(state, 'a system schedule sleeps when the story clock moves');
|
|
1049
|
+
const last = typeof state.lastAt === 'number' ? state.lastAt : undefined;
|
|
1050
|
+
if (last === undefined)
|
|
1051
|
+
return no({ lastAt: m.at }, 'counting from now');
|
|
1052
|
+
const due = m.at > last && systemScheduleDue(last, m.at, at, m.timeZone ?? 'UTC');
|
|
1053
|
+
if (!due)
|
|
1054
|
+
return no({ lastAt: m.at }, 'not due yet');
|
|
1055
|
+
return { due: true, state: once ? { lastAt: m.at, done: true } : { lastAt: m.at } };
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return no(state, `${cadenceSlugOf(def.id)} has nothing to say at ${eventWord(e.event)}`);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Drive a cadence through a list of events — a fake clock for an author's
|
|
1062
|
+
* test (A17). Returns each event's answer, the indexes it fired at, and the
|
|
1063
|
+
* state left. A plugin's cadence passes `evaluate` (what its script would
|
|
1064
|
+
* answer — handed each event as it was given); core's are evaluated as the
|
|
1065
|
+
* host does.
|
|
1066
|
+
*
|
|
1067
|
+
* ```ts
|
|
1068
|
+
* const run = simulateCadence(everyNTurns({ n: 5 }), turns(1, 12))
|
|
1069
|
+
* run.fired // [4, 9] — turns 5 and 10
|
|
1070
|
+
* ```
|
|
1071
|
+
* @experimental
|
|
1072
|
+
* @ruling A17
|
|
1073
|
+
*/
|
|
1074
|
+
export function simulateCadence(ref, events, opts = {}) {
|
|
1075
|
+
let state = opts.state ?? {};
|
|
1076
|
+
const steps = [];
|
|
1077
|
+
const fired = [];
|
|
1078
|
+
const def = getCadence(ref.id);
|
|
1079
|
+
events.forEach((given, i) => {
|
|
1080
|
+
const event = cadenceEventOf(given);
|
|
1081
|
+
let verdict;
|
|
1082
|
+
if (opts.evaluate && (!def || def.evaluate !== 'host')) {
|
|
1083
|
+
if (def && !cadenceWakesOn(def, event.event))
|
|
1084
|
+
verdict = no(state, `${cadenceSlugOf(def.id)} sleeps at ${eventWord(event.event)}`);
|
|
1085
|
+
else {
|
|
1086
|
+
const r = opts.evaluate(given, ref.options ?? {}, state);
|
|
1087
|
+
verdict = typeof r === 'boolean' ? { due: r, state } : r;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
else
|
|
1091
|
+
verdict = cadenceDue(ref, given, state);
|
|
1092
|
+
state = verdict.state;
|
|
1093
|
+
steps.push({
|
|
1094
|
+
event,
|
|
1095
|
+
moment: given,
|
|
1096
|
+
due: verdict.due,
|
|
1097
|
+
...(verdict.reason ? { reason: verdict.reason } : {}),
|
|
1098
|
+
});
|
|
1099
|
+
if (verdict.due)
|
|
1100
|
+
fired.push(i);
|
|
1101
|
+
});
|
|
1102
|
+
return { steps, fired, state };
|
|
1103
|
+
}
|
|
1104
|
+
/** 🚧 `turn-ended` events for turns `from` … `to` — a simulation's turns. @experimental */
|
|
1105
|
+
export const turnEvents = (from, to) => {
|
|
1106
|
+
const out = [];
|
|
1107
|
+
for (let t = from; t <= to; t++)
|
|
1108
|
+
out.push({ event: TURN_ENDED_EVENT, turn: t });
|
|
1109
|
+
return out;
|
|
1110
|
+
};
|
|
1111
|
+
/** ⏳ `turn-ended` moments in the shape before events — say `turnEvents`. @experimental */
|
|
1112
|
+
export const turnMoments = (from, to) => {
|
|
1113
|
+
const out = [];
|
|
1114
|
+
for (let t = from; t <= to; t++)
|
|
1115
|
+
out.push({ kind: 'turn-ended', turn: t });
|
|
1116
|
+
return out;
|
|
1117
|
+
};
|
|
1118
|
+
//# sourceMappingURL=cadences.js.map
|