@rohal12/spindle 0.59.32 → 0.59.33

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.32",
3
+ "version": "0.59.33",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,12 @@
1
1
  import { emit } from './event-emitter';
2
+ import {
3
+ checkFields,
4
+ checkObject,
5
+ isBoolean,
6
+ isString,
7
+ type Fail,
8
+ type FieldCheck,
9
+ } from './utils/field-checks';
2
10
 
3
11
  export type ActionType =
4
12
  | 'link'
@@ -46,6 +54,60 @@ export const OPTIONAL_ACTION_FIELDS = [
46
54
  'disabled',
47
55
  ] as const;
48
56
 
57
+ export interface ActionMatcher extends Partial<
58
+ Pick<StoryAction, 'id' | 'target' | 'variable' | 'label'>
59
+ > {
60
+ type?: string;
61
+ /** `true` matches only disabled actions, `false` only enabled ones. */
62
+ disabled?: boolean;
63
+ }
64
+
65
+ /** The matcher fields compared with the action field of the same name. */
66
+ const MATCHED_FIELDS = ['id', 'type', 'target', 'variable', 'label'] as const;
67
+
68
+ /**
69
+ * Whether an action satisfies every field the matcher sets. Unset matcher
70
+ * fields match anything.
71
+ */
72
+ export function actionMatches(
73
+ action: Omit<StoryAction, 'perform'>,
74
+ matcher: ActionMatcher,
75
+ ): boolean {
76
+ return (
77
+ MATCHED_FIELDS.every(
78
+ (field) =>
79
+ matcher[field] === undefined || action[field] === matcher[field],
80
+ ) &&
81
+ // An action that does not set `disabled` is enabled
82
+ (matcher.disabled === undefined || !!action.disabled === matcher.disabled)
83
+ );
84
+ }
85
+
86
+ const MATCHER_FIELDS: Record<string, [FieldCheck, string]> = {
87
+ type: [isString, 'a string'],
88
+ id: [isString, 'a string'],
89
+ target: [isString, 'a string'],
90
+ variable: [isString, 'a string'],
91
+ label: [isString, 'a string'],
92
+ disabled: [isBoolean, 'true or false'],
93
+ };
94
+
95
+ /**
96
+ * A copy of `value` as an ActionMatcher, or `fail` naming `what` when it is not an
97
+ * object of matcher fields with the right types. The automation YAML and
98
+ * Story.setObservedActions() take matchers from authors.
99
+ */
100
+ export function checkActionMatcher(
101
+ value: unknown,
102
+ what: string,
103
+ fail: Fail,
104
+ ): ActionMatcher {
105
+ const matcher = checkObject(value, what, Object.keys(MATCHER_FIELDS), fail);
106
+ checkFields(matcher, what, MATCHER_FIELDS, fail);
107
+ // A copy: the author's object may change after it was checked
108
+ return { ...matcher } as ActionMatcher;
109
+ }
110
+
49
111
  /** A mounted control's hold on its action ID. */
50
112
  export interface ActionRegistration {
51
113
  /**
@@ -59,6 +121,8 @@ export interface ActionRegistration {
59
121
 
60
122
  interface Entry {
61
123
  action: StoryAction;
124
+ /** The dialog the control renders in (its close function), if any. */
125
+ dialog: (() => void) | null;
62
126
  }
63
127
 
64
128
  /**
@@ -105,9 +169,16 @@ export function generateActionId(
105
169
  return id;
106
170
  }
107
171
 
108
- export function registerAction(action: StoryAction): ActionRegistration {
172
+ /**
173
+ * Register `action`, of a control rendered in the dialog `dialog` (the
174
+ * dialog's DialogCloseContext value), or outside any when null.
175
+ */
176
+ export function registerAction(
177
+ action: StoryAction,
178
+ dialog: (() => void) | null = null,
179
+ ): ActionRegistration {
109
180
  const id = action.id;
110
- const entry: Entry = { action };
181
+ const entry: Entry = { action, dialog };
111
182
  const entries = actions.get(id);
112
183
  if (entries) {
113
184
  console.warn(
@@ -176,6 +247,17 @@ export function getActions(): StoryAction[] {
176
247
  return Array.from(actions.values(), listed);
177
248
  }
178
249
 
250
+ /**
251
+ * The actions of the controls rendered in the dialog `dialog` (its close
252
+ * function, see registerAction), its nested dialogs' left out.
253
+ */
254
+ export function getDialogActions(dialog: () => void): StoryAction[] {
255
+ return Array.from(actions.values())
256
+ .map((entries) => entries[entries.length - 1]!)
257
+ .filter((entry) => entry.dialog === dialog)
258
+ .map((entry) => entry.action);
259
+ }
260
+
179
261
  export function getAction(id: string): StoryAction | undefined {
180
262
  const entries = actions.get(id);
181
263
  return entries && listed(entries);
@@ -1,56 +1,17 @@
1
1
  import * as yaml from 'js-yaml';
2
2
  import type { AutomationScript, AutomationStep } from './types';
3
+ import { checkActionMatcher } from '../action-registry';
4
+ import {
5
+ checkFields,
6
+ checkObject,
7
+ isRecord,
8
+ isString,
9
+ type Fail,
10
+ type FieldCheck,
11
+ } from '../utils/field-checks';
3
12
 
4
- type Fail = (message: string) => never;
5
-
6
- function isRecord(value: unknown): value is Record<string, unknown> {
7
- return typeof value === 'object' && value !== null && !Array.isArray(value);
8
- }
9
-
10
- /** `value` as an object whose keys are all in `allowed`. */
11
- function checkObject(
12
- value: unknown,
13
- what: string,
14
- allowed: readonly string[],
15
- fail: Fail,
16
- ): Record<string, unknown> {
17
- if (!isRecord(value)) fail(`${what} must be an object`);
18
- for (const key of Object.keys(value)) {
19
- if (!allowed.includes(key)) {
20
- fail(`${what} has an unknown field "${key}" (${allowed.join(', ')})`);
21
- }
22
- }
23
- return value;
24
- }
25
-
26
- type FieldCheck = (value: unknown) => boolean;
27
-
28
- const isString: FieldCheck = (v) => typeof v === 'string';
29
- const isBoolean: FieldCheck = (v) => typeof v === 'boolean';
30
13
  const isCount: FieldCheck = (v) => Number.isInteger(v) && (v as number) >= 0;
31
14
 
32
- function checkFields(
33
- obj: Record<string, unknown>,
34
- what: string,
35
- checks: Record<string, [FieldCheck, string]>,
36
- fail: Fail,
37
- ): void {
38
- for (const [key, [valid, expected]] of Object.entries(checks)) {
39
- if (key in obj && !valid(obj[key])) {
40
- fail(`"${key}" of ${what} must be ${expected}`);
41
- }
42
- }
43
- }
44
-
45
- const MATCHER_FIELDS: Record<string, [FieldCheck, string]> = {
46
- type: [isString, 'a string'],
47
- id: [isString, 'a string'],
48
- target: [isString, 'a string'],
49
- variable: [isString, 'a string'],
50
- label: [isString, 'a string'],
51
- disabled: [isBoolean, 'true or false'],
52
- };
53
-
54
15
  const ASSERT_FIELDS: Record<string, [FieldCheck, string]> = {
55
16
  passage: [isString, 'a string'],
56
17
  variables: [isRecord, 'an object of variable names and values'],
@@ -67,13 +28,7 @@ function checkAssert(value: unknown, fail: Fail): void {
67
28
  );
68
29
  checkFields(assert, '"assert"', ASSERT_FIELDS, fail);
69
30
  for (const matcher of (assert.actions as unknown[] | undefined) ?? []) {
70
- const m = checkObject(
71
- matcher,
72
- 'an action matcher in "assert.actions"',
73
- Object.keys(MATCHER_FIELDS),
74
- fail,
75
- );
76
- checkFields(m, 'an action matcher', MATCHER_FIELDS, fail);
31
+ checkActionMatcher(matcher, 'an action matcher in "assert.actions"', fail);
77
32
  }
78
33
  }
79
34
 
@@ -6,7 +6,7 @@ import type {
6
6
  ActionMatcher,
7
7
  } from './types';
8
8
  import type { StoryAPI } from '../story-api';
9
- import type { StoryAction } from '../action-registry';
9
+ import { actionMatches, type StoryAction } from '../action-registry';
10
10
  import { errorMessage } from '../utils/error-message';
11
11
  import { deepEqual } from '../structural';
12
12
 
@@ -127,21 +127,9 @@ async function executeStep(
127
127
  }
128
128
  }
129
129
 
130
- /** The matcher fields compared with the action field of the same name. */
131
- const MATCHED_FIELDS = ['id', 'type', 'target', 'variable', 'label'] as const;
132
-
133
130
  function findMatchingAction(
134
131
  actions: StoryAction[],
135
132
  matcher: ActionMatcher,
136
133
  ): StoryAction | undefined {
137
- return actions.find(
138
- (action) =>
139
- MATCHED_FIELDS.every(
140
- (field) =>
141
- matcher[field] === undefined || action[field] === matcher[field],
142
- ) &&
143
- // An action that does not set `disabled` is enabled
144
- (matcher.disabled === undefined ||
145
- !!action.disabled === matcher.disabled),
146
- );
134
+ return actions.find((action) => actionMatches(action, matcher));
147
135
  }
@@ -1,12 +1,6 @@
1
- import type { StoryAction } from '../action-registry';
1
+ import type { ActionMatcher } from '../action-registry';
2
2
 
3
- export interface ActionMatcher extends Partial<
4
- Pick<StoryAction, 'id' | 'target' | 'variable' | 'label'>
5
- > {
6
- type?: string;
7
- /** `true` matches only disabled actions, `false` only enabled ones. */
8
- disabled?: boolean;
9
- }
3
+ export type { ActionMatcher };
10
4
 
11
5
  export interface AssertStep {
12
6
  passage?: string;
@@ -1,4 +1,3 @@
1
- import { createContext } from 'preact';
2
1
  import {
3
2
  useCallback,
4
3
  useId,
@@ -20,7 +19,9 @@ import { registerOpenDialog } from '../triggers';
20
19
  import { errorMessage } from '../utils/error-message';
21
20
  import { useAction } from '../hooks/use-action';
22
21
 
23
- export const DialogCloseContext = createContext<(() => void) | null>(null);
22
+ import { DialogCloseContext } from './dialog-close-context';
23
+
24
+ export { DialogCloseContext };
24
25
 
25
26
  interface PassageDialogProps {
26
27
  passageName?: string;
@@ -92,7 +93,10 @@ export function PassageDialog({
92
93
  useModalFocus(panelRef, '.dialog-body', dismissible, stableOnClose);
93
94
 
94
95
  // Be on the stack of displayed dialogs the Story dialog API works on.
95
- useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
96
+ useLayoutEffect(
97
+ () => registerOpenDialog(stableOnClose, panelRef.current),
98
+ [stableOnClose],
99
+ );
96
100
 
97
101
  // Name the dialog after its first heading when no label is given
98
102
  useLayoutEffect(() => {
@@ -133,6 +137,7 @@ export function PassageDialog({
133
137
  ref={panelRef}
134
138
  class={cls}
135
139
  role="dialog"
140
+ data-dialog-passage={passageName}
136
141
  aria-modal="true"
137
142
  aria-label={label ?? passageName}
138
143
  tabIndex={-1}
@@ -0,0 +1,10 @@
1
+ import { createContext } from 'preact';
2
+
3
+ /**
4
+ * The function that closes the dialog the content renders in, or null
5
+ * outside any dialog. Each PassageDialog provides its own stable one, so it
6
+ * also identifies the dialog: the dialog stack (registerOpenDialog) holds
7
+ * it, and useAction records it with the action, so Story.observe() can
8
+ * offer only the innermost dialog's actions.
9
+ */
10
+ export const DialogCloseContext = createContext<(() => void) | null>(null);
@@ -12,7 +12,7 @@ defineMacro({
12
12
  render(_props, ctx) {
13
13
  const label = ctx.args.label ?? '';
14
14
 
15
- useVariableAction(ctx, {
15
+ const actionId = useVariableAction(ctx, {
16
16
  type: 'checkbox',
17
17
  label: label || ctx.varName || '',
18
18
  value: !!ctx.value,
@@ -26,6 +26,7 @@ defineMacro({
26
26
  >
27
27
  <input
28
28
  type="checkbox"
29
+ data-action={actionId || undefined}
29
30
  checked={!!ctx.value}
30
31
  onChange={(e) =>
31
32
  ctx.setValue!((e.target as HTMLInputElement).checked)
@@ -18,7 +18,7 @@ defineMacro({
18
18
  ctx.setValue!(options[nextIndex]);
19
19
  };
20
20
 
21
- useVariableAction(ctx, {
21
+ const actionId = useVariableAction(ctx, {
22
22
  type: 'cycle',
23
23
  label: ctx.value == null ? options[0] || '' : String(ctx.value),
24
24
  options,
@@ -35,6 +35,7 @@ defineMacro({
35
35
  <button
36
36
  type="button"
37
37
  id={ctx.id}
38
+ data-action={actionId || undefined}
38
39
  class={ctx.cls}
39
40
  onClick={handleClick}
40
41
  >
@@ -11,7 +11,7 @@ defineMacro({
11
11
  render({ children = [] }, ctx) {
12
12
  const options = ctx.extractOptions(children);
13
13
 
14
- useVariableAction(ctx, {
14
+ const actionId = useVariableAction(ctx, {
15
15
  type: 'listbox',
16
16
  label: ctx.varName!,
17
17
  options,
@@ -23,6 +23,7 @@ defineMacro({
23
23
  return (
24
24
  <select
25
25
  id={ctx.id}
26
+ data-action={actionId || undefined}
26
27
  class={ctx.cls}
27
28
  value={display(ctx.value)}
28
29
  onChange={(e) => ctx.setValue!((e.target as HTMLSelectElement).value)}
@@ -17,7 +17,7 @@ defineMacro({
17
17
  // One group per variable in each view (see ViewScopeContext)
18
18
  const view = ctx.hooks.useContext(ViewScopeContext);
19
19
 
20
- useVariableAction(ctx, {
20
+ const actionId = useVariableAction(ctx, {
21
21
  type: 'radiobutton',
22
22
  key: `$${ctx.varName}:${radioValue}`,
23
23
  label: label || radioValue,
@@ -31,6 +31,8 @@ defineMacro({
31
31
  >
32
32
  <input
33
33
  type="radio"
34
+ value={radioValue}
35
+ data-action={actionId || undefined}
34
36
  name={view ? `radio-${view}-${ctx.varName}` : `radio-${ctx.varName}`}
35
37
  checked={ctx.value === radioValue}
36
38
  onChange={() => ctx.setValue!(radioValue)}
@@ -22,6 +22,8 @@ import { RepeatContext } from './Repeat';
22
22
  import { DialogCloseContext } from '../PassageDialog';
23
23
  import { NameSet } from '../../utils/macro-names';
24
24
  import { ItemEditContext } from '../../utils/control-edits';
25
+ import { DisplayOnlyContext } from '../../display-only';
26
+ import { ActionsDisabledContext } from '../../hooks/use-action';
25
27
 
26
28
  const frozenAlways = () => true;
27
29
 
@@ -89,7 +91,8 @@ function Settled({ onSettled }: { onSettled: () => void }) {
89
91
  * through a live view, so a local assigned earlier in the body is visible),
90
92
  * nobr/inline rendering, the enclosing block widget's {@children}, the
91
93
  * enclosing {repeat}'s {stop} and the enclosing dialog's close callback and whether it runs in a {for} iteration
92
- * (#411) and the owning passage's departure (#410).
94
+ * (#411), the owning passage's departure (#410), and whether it renders in
95
+ * display-only content (StoryContext), which a body may not change either.
93
96
  * The body then behaves as if it rendered in place.
94
97
  *
95
98
  * The body's macros read story state from the store. Run from mutation code
@@ -106,6 +109,8 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
106
109
  const closeDialog = useContext(DialogCloseContext);
107
110
  const inIteration = useContext(ItemEditContext);
108
111
  const hasLeft = useContext(OutgoingContext);
112
+ const displayOnly = useContext(DisplayOnlyContext);
113
+ const actionsDisabled = useContext(ActionsDisabledContext);
109
114
 
110
115
  const mounted = useRef<HTMLElement[]>([]);
111
116
  useEffect(() => {
@@ -150,13 +155,19 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
150
155
  <DialogCloseContext.Provider value={closeDialog}>
151
156
  <ItemEditContext.Provider value={inIteration}>
152
157
  <OutgoingContext.Provider value={hasLeft}>
153
- {renderNodes(children, {
154
- nobr,
155
- inline,
156
- structural,
157
- locals,
158
- })}
159
- {release && <Settled onSettled={release} />}
158
+ <DisplayOnlyContext.Provider value={displayOnly}>
159
+ <ActionsDisabledContext.Provider
160
+ value={actionsDisabled}
161
+ >
162
+ {renderNodes(children, {
163
+ nobr,
164
+ inline,
165
+ structural,
166
+ locals,
167
+ })}
168
+ {release && <Settled onSettled={release} />}
169
+ </ActionsDisabledContext.Provider>
170
+ </DisplayOnlyContext.Provider>
160
171
  </OutgoingContext.Provider>
161
172
  </ItemEditContext.Provider>
162
173
  </DialogCloseContext.Provider>
@@ -54,7 +54,7 @@ export function defineInputMacro(
54
54
  render(_props, ctx) {
55
55
  const placeholder = ctx.args.placeholder ?? '';
56
56
 
57
- useVariableAction(ctx, {
57
+ const actionId = useVariableAction(ctx, {
58
58
  type: name,
59
59
  label: placeholder || ctx.varName!,
60
60
  perform: (v) => ctx.setValue!(toValue(v)),
@@ -75,6 +75,7 @@ export function defineInputMacro(
75
75
  return h(type ? 'input' : 'textarea', {
76
76
  type,
77
77
  id: ctx.id,
78
+ 'data-action': actionId || undefined,
78
79
  class: ctx.cls,
79
80
  value: shown,
80
81
  placeholder,
@@ -40,6 +40,12 @@ import {
40
40
  readBoundVariable,
41
41
  } from './components/macros/macro-args';
42
42
  import { MacroError } from './components/macros/MacroError';
43
+ import {
44
+ ACTING_MACROS,
45
+ DisplayOnlyContext,
46
+ displayOnlyError,
47
+ } from './display-only';
48
+ import { NameSet } from './utils/macro-names';
43
49
  import {
44
50
  checkParameterTypes,
45
51
  registerMacro,
@@ -129,6 +135,8 @@ export interface MacroDefinition<
129
135
  ) => string;
130
136
  }
131
137
 
138
+ const actingMacros = new NameSet(ACTING_MACROS);
139
+
132
140
  const sharedHooks = {
133
141
  useState,
134
142
  useRef,
@@ -145,8 +153,22 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
145
153
  ): void {
146
154
  const parameters: readonly ParameterDef[] = config.parameters ?? [];
147
155
  checkParameterTypes(config.name, parameters);
156
+ const acts = actingMacros.has(config.name);
148
157
 
149
158
  function Wrapper(props: MacroProps) {
159
+ // In a display-only passage nothing may change the story (a mount's
160
+ // context never changes, so the hooks below run alike on every render)
161
+ const displayOnly = useContext(DisplayOnlyContext);
162
+ if (displayOnly && acts) {
163
+ return h(MacroError, {
164
+ macro: config.name,
165
+ error: displayOnlyError(config.name),
166
+ });
167
+ }
168
+ const refuse = () => {
169
+ throw displayOnlyError(config.name);
170
+ };
171
+
150
172
  // className/id resolved first (interpolate may transform them)
151
173
  let className = props.className;
152
174
  let id = props.id;
@@ -196,11 +218,13 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
196
218
  resolve,
197
219
  cls: macroClass(config.name, className),
198
220
  // Code run inside a {for} iteration edits the loop's items (#400)
199
- mutate: inIteration
200
- ? (code: string) =>
201
- runAsItemEdit(() => executeMutation(code, getValues(), update))
202
- : (code: string) => executeMutation(code, getValues(), update),
203
- update,
221
+ mutate: displayOnly
222
+ ? refuse
223
+ : inIteration
224
+ ? (code: string) =>
225
+ runAsItemEdit(() => executeMutation(code, getValues(), update))
226
+ : (code: string) => executeMutation(code, getValues(), update),
227
+ update: displayOnly ? refuse : update,
204
228
  getValues,
205
229
  wrap: (content: ComponentChildren): VNode<any> =>
206
230
  wrapContent(className, id, content),
@@ -245,17 +269,19 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
245
269
  ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
246
270
  // In program order, also when mutation code performs the input
247
271
  ctx.getValue = () => getByPath(readState().variables, segments);
248
- ctx.setValue = (value: unknown) => {
249
- noteControlEdit(segments);
250
- // The commit mutation code uses, which keeps the references among
251
- // variables: a write to a draft copies only the path written, and
252
- // other variables sharing the object would keep the old one.
253
- mutateState((work, adopt) => {
254
- setByPath(work.variables, segments, adopt(value), {
255
- createMissing: true,
256
- });
257
- });
258
- };
272
+ ctx.setValue = displayOnly
273
+ ? refuse
274
+ : (value: unknown) => {
275
+ noteControlEdit(segments);
276
+ // The commit mutation code uses, which keeps the references among
277
+ // variables: a write to a draft copies only the path written, and
278
+ // other variables sharing the object would keep the old one.
279
+ mutateState((work, adopt) => {
280
+ setByPath(work.variables, segments, adopt(value), {
281
+ createMissing: true,
282
+ });
283
+ });
284
+ };
259
285
  }
260
286
 
261
287
  try {
@@ -0,0 +1,30 @@
1
+ import { createContext } from 'preact';
2
+
3
+ /**
4
+ * The macros that change the story, or act when they mount. A display-only
5
+ * passage may not use them (see storyContextErrors), and under
6
+ * DisplayOnlyContext they render an error instead of running.
7
+ */
8
+ export const ACTING_MACROS: readonly string[] = [
9
+ 'set',
10
+ 'do',
11
+ 'unset',
12
+ 'computed',
13
+ 'goto',
14
+ 'watch',
15
+ ];
16
+
17
+ /**
18
+ * While true, the macros rendered underneath change nothing: the acting
19
+ * macros and every macro's `ctx.mutate`, `ctx.update` and `ctx.setValue`
20
+ * fail with displayOnlyError(). Provided around the `StoryContext` tree,
21
+ * which its static check can't see into ({include}, widget bodies).
22
+ */
23
+ export const DisplayOnlyContext = createContext(false);
24
+
25
+ /** The error of the macro `{name}` trying to change a display-only passage. */
26
+ export function displayOnlyError(name: string): Error {
27
+ return new Error(
28
+ `StoryContext is display-only: {${name}} cannot change the story`,
29
+ );
30
+ }
package/src/headless.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import { boot } from './index';
11
11
  import { useStoryStore } from './store';
12
12
  import type { StoryAPI } from './story-api';
13
+ import type { Observation } from './observe/observe';
13
14
 
14
15
  export interface BootStoryOptions {
15
16
  /**
@@ -84,4 +85,83 @@ export function bootStory(options: BootStoryOptions): Promise<StoryAPI> {
84
85
  });
85
86
  }
86
87
 
87
- export type { StoryAPI };
88
+ /** One recorded step: what the reader saw, and what they chose. */
89
+ export interface TranscriptEntry {
90
+ turn: number;
91
+ passage: string;
92
+ /** Left out when the transcript was created with `include.text: false`. */
93
+ text?: string;
94
+ /** Only with `include.context: true`. */
95
+ context?: string | null;
96
+ chose: { id: string; label: string; value?: unknown };
97
+ }
98
+
99
+ export interface TranscriptOptions {
100
+ /**
101
+ * How many of the latest entries to keep: a non-negative integer, or
102
+ * `Infinity` for all. Default 10. Anything else throws.
103
+ */
104
+ limit?: number;
105
+ /** Default `{ text: true, context: false }`. */
106
+ include?: { text?: boolean; context?: boolean };
107
+ }
108
+
109
+ export interface Transcript {
110
+ /**
111
+ * `Story.step()`, recording the observation it acted on and the choice.
112
+ * Await each step before the next: steps are not queued.
113
+ */
114
+ step(id: string, value?: unknown): Promise<Observation>;
115
+ readonly entries: readonly TranscriptEntry[];
116
+ }
117
+
118
+ /**
119
+ * Record a playthrough for stateless decision models, which need the last few
120
+ * steps sent with every call. A step that rejects records nothing.
121
+ */
122
+ export function createTranscript(
123
+ story: StoryAPI,
124
+ options: TranscriptOptions = {},
125
+ ): Transcript {
126
+ const limit = options.limit ?? 10;
127
+ if (
128
+ limit !== Infinity &&
129
+ !(typeof limit === 'number' && Number.isInteger(limit) && limit >= 0)
130
+ ) {
131
+ throw new Error(
132
+ `spindle: createTranscript(): "limit" must be a non-negative integer or Infinity, got ${typeof limit === 'string' ? JSON.stringify(limit) : String(limit)}`,
133
+ );
134
+ }
135
+ const withText = options.include?.text ?? true;
136
+ const withContext = options.include?.context ?? false;
137
+ const entries: TranscriptEntry[] = [];
138
+
139
+ return {
140
+ entries,
141
+ async step(id, value) {
142
+ const before = story.observe();
143
+ const action =
144
+ before.actions.find((a) => a.id === id) ??
145
+ story.getActions().find((a) => a.id === id);
146
+ const next = await story.step(id, value);
147
+
148
+ const chose: TranscriptEntry['chose'] = {
149
+ id,
150
+ label: action?.label ?? id,
151
+ };
152
+ if (value !== undefined) chose.value = value;
153
+ const entry: TranscriptEntry = {
154
+ turn: before.turn,
155
+ passage: before.passage,
156
+ chose,
157
+ };
158
+ if (withText) entry.text = before.text;
159
+ if (withContext) entry.context = before.context;
160
+ entries.push(entry);
161
+ if (entries.length > limit) entries.splice(0, entries.length - limit);
162
+ return next;
163
+ },
164
+ };
165
+ }
166
+
167
+ export type { Observation, StoryAPI };