@rohal12/spindle 0.61.2 → 0.61.4
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/pkg/format.js +1 -1
- package/dist/pkg/headless.js +609 -335
- package/dist/pkg/play.js +2 -0
- package/dist/pkg/story-variables.js +486 -225
- package/package.json +1 -1
- package/src/automation/runner.ts +24 -3
- package/src/define-macro.ts +36 -2
- package/src/format/format-passage.ts +33 -7
- package/src/format/{fenced-code.ts → markdown-lines.ts} +22 -8
- package/src/format/placeholders.ts +1 -1
- package/src/format/source-lines.ts +17 -0
- package/src/js-lexer.ts +18 -0
- package/src/markup/spindle.peggy +6 -0
- package/src/observe/observable-text.ts +19 -7
- package/src/observe/observe.ts +30 -5
- package/src/play/session.ts +10 -0
- package/src/saves/format.ts +15 -4
- package/src/story-context-passage.ts +2 -1
- package/src/utils/element-visibility.ts +15 -10
- package/types/index.d.ts +13 -2
- package/types/play.d.ts +5 -0
package/package.json
CHANGED
package/src/automation/runner.ts
CHANGED
|
@@ -23,9 +23,30 @@ export async function runAutomation(
|
|
|
23
23
|
let stepsRun = 0;
|
|
24
24
|
|
|
25
25
|
// Navigate to start passage if specified
|
|
26
|
-
if (script.start) {
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
if (script.start !== undefined) {
|
|
27
|
+
let started = false;
|
|
28
|
+
// Observe the supplied runtime, which may come from a separate package
|
|
29
|
+
// bundle. Valid destinations emit before rendering (and any redirects).
|
|
30
|
+
const unsubscribe = story.on('beforenavigate', (passage) => {
|
|
31
|
+
if (passage === script.start) started = true;
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
story.goto(script.start);
|
|
35
|
+
if (!started) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Cannot start automation at passage "${script.start}": navigation was refused`,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
await story.waitForActions();
|
|
41
|
+
} catch (err) {
|
|
42
|
+
return {
|
|
43
|
+
success: false,
|
|
44
|
+
stepsRun: 0,
|
|
45
|
+
errors: [{ step: -1, message: errorMessage(err) }],
|
|
46
|
+
};
|
|
47
|
+
} finally {
|
|
48
|
+
unsubscribe();
|
|
49
|
+
}
|
|
29
50
|
}
|
|
30
51
|
|
|
31
52
|
for (let i = 0; i < script.steps.length; i++) {
|
package/src/define-macro.ts
CHANGED
|
@@ -28,6 +28,7 @@ import { evaluateDisplay } from './expression';
|
|
|
28
28
|
import { useStoryStore } from './store';
|
|
29
29
|
import { getByPath, setByPath } from './utils/object-path';
|
|
30
30
|
import { RESERVED_NAME } from './utils/namespace';
|
|
31
|
+
import { parseMemberIdentifier, parseReferencePath } from './js-lexer';
|
|
31
32
|
import { useAction } from './hooks/use-action';
|
|
32
33
|
import type { UseActionOptions } from './hooks/use-action';
|
|
33
34
|
import { collectText } from './utils/extract-text';
|
|
@@ -255,8 +256,41 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
|
|
|
255
256
|
);
|
|
256
257
|
}
|
|
257
258
|
|
|
258
|
-
|
|
259
|
-
|
|
259
|
+
if (
|
|
260
|
+
!firstToken.startsWith('$') &&
|
|
261
|
+
firstToken.split('.')[0]!.includes('\\')
|
|
262
|
+
) {
|
|
263
|
+
return h(MacroError, {
|
|
264
|
+
macro: config.name,
|
|
265
|
+
error: new Error(
|
|
266
|
+
'Escaped binding identifiers require a literal $ story-variable sigil',
|
|
267
|
+
),
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let segments: string[];
|
|
272
|
+
try {
|
|
273
|
+
segments = firstToken
|
|
274
|
+
.replace(/^\$/, '')
|
|
275
|
+
.split('.')
|
|
276
|
+
.map((segment, index) => {
|
|
277
|
+
if (!segment.includes('\\')) return segment;
|
|
278
|
+
// Members follow JavaScript's identifier grammar, which accepts
|
|
279
|
+
// more names than story-variable roots (for example $foo and é).
|
|
280
|
+
if (index > 0) {
|
|
281
|
+
const name = parseMemberIdentifier(segment);
|
|
282
|
+
if (name === null) throw new Error('Invalid bound identifier');
|
|
283
|
+
return name;
|
|
284
|
+
}
|
|
285
|
+
const reference = parseReferencePath(`$${segment}`);
|
|
286
|
+
if (!reference || reference.nested)
|
|
287
|
+
throw new Error('Invalid bound identifier');
|
|
288
|
+
return reference.name;
|
|
289
|
+
});
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return h(MacroError, { macro: config.name, error });
|
|
292
|
+
}
|
|
293
|
+
const varExpr = segments.join('.');
|
|
260
294
|
if (segments.includes(RESERVED_NAME)) {
|
|
261
295
|
return h(
|
|
262
296
|
'span',
|
|
@@ -3,7 +3,8 @@ import { analyzeMarkup, tokenizeMarkupTolerant } from '../markup/parse';
|
|
|
3
3
|
import type { PairedNode } from '../markup/pair';
|
|
4
4
|
import type { MacroToken } from '../markup/tokens';
|
|
5
5
|
import { segmentRegions } from './segment';
|
|
6
|
-
import {
|
|
6
|
+
import { markdownLines } from './markdown-lines';
|
|
7
|
+
import { sourceLines } from './source-lines';
|
|
7
8
|
import {
|
|
8
9
|
formatJS,
|
|
9
10
|
formatCSS,
|
|
@@ -215,7 +216,7 @@ async function formatLf(
|
|
|
215
216
|
const literalSentinel = newlineSentinel(body + sentinel);
|
|
216
217
|
const literalLines = new Map<string, string>();
|
|
217
218
|
const literalMarkers = new Set<string>();
|
|
218
|
-
const fenced =
|
|
219
|
+
const fenced = markdownLines(body, isBlock, new Set(['codeFenced']));
|
|
219
220
|
const literalHtml = whitespaceSensitiveLines(body, isBlock);
|
|
220
221
|
body = body
|
|
221
222
|
.split('\n')
|
|
@@ -336,7 +337,12 @@ async function formatLf(
|
|
|
336
337
|
literalMarkers,
|
|
337
338
|
);
|
|
338
339
|
if (options.maxLineLength) {
|
|
339
|
-
indented = wrapLines(
|
|
340
|
+
indented = wrapLines(
|
|
341
|
+
indented,
|
|
342
|
+
options.maxLineLength,
|
|
343
|
+
literalLines,
|
|
344
|
+
isBlock,
|
|
345
|
+
);
|
|
340
346
|
}
|
|
341
347
|
for (const line of indented) {
|
|
342
348
|
if (line.endsWith(' ')) hardBreakLines.add(lines.length);
|
|
@@ -374,6 +380,7 @@ function whitespaceSensitiveLines(
|
|
|
374
380
|
): Set<number> {
|
|
375
381
|
const lines = new Set<number>();
|
|
376
382
|
if (!WHITESPACE_AS_WRITTEN.test(source)) return lines;
|
|
383
|
+
const lineAt = sourceLines(source);
|
|
377
384
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
378
385
|
function visit(nodes: PairedNode[]): void {
|
|
379
386
|
for (const node of nodes) {
|
|
@@ -386,8 +393,8 @@ function whitespaceSensitiveLines(
|
|
|
386
393
|
name.toLowerCase() === 'style' && /white-space\s*:/i.test(value),
|
|
387
394
|
))
|
|
388
395
|
) {
|
|
389
|
-
const first =
|
|
390
|
-
const last =
|
|
396
|
+
const first = lineAt(node.start);
|
|
397
|
+
const last = lineAt(node.end - 1);
|
|
391
398
|
for (let line = first; line <= last; line++) lines.add(line);
|
|
392
399
|
} else if (body) {
|
|
393
400
|
visit(body.children);
|
|
@@ -599,6 +606,21 @@ function indentColumn(line: string): number {
|
|
|
599
606
|
// Line wrapping
|
|
600
607
|
// ---------------------------------------------------------------------------
|
|
601
608
|
|
|
609
|
+
/** Constructs whose line breaks or continuation prefixes carry Markdown syntax. */
|
|
610
|
+
const NO_WRAP = new Set([
|
|
611
|
+
'atxHeading',
|
|
612
|
+
'setextHeading',
|
|
613
|
+
'table',
|
|
614
|
+
'listItem',
|
|
615
|
+
'blockQuote',
|
|
616
|
+
'definition',
|
|
617
|
+
'thematicBreak',
|
|
618
|
+
'htmlFlow',
|
|
619
|
+
'codeText',
|
|
620
|
+
'link',
|
|
621
|
+
'image',
|
|
622
|
+
]);
|
|
623
|
+
|
|
602
624
|
/**
|
|
603
625
|
* Wrap lines that exceed maxLen at word boundaries.
|
|
604
626
|
* Preserves leading indentation. Skips pure macro lines and choice/link
|
|
@@ -608,15 +630,18 @@ function wrapLines(
|
|
|
608
630
|
lines: string[],
|
|
609
631
|
maxLen: number,
|
|
610
632
|
literalLines: ReadonlyMap<string, string>,
|
|
633
|
+
isBlock: (name: string) => boolean,
|
|
611
634
|
): string[] {
|
|
612
635
|
const result: string[] = [];
|
|
613
636
|
const javaScript = doBodyLines(lines);
|
|
637
|
+
const structured = markdownLines(lines.join('\n'), isBlock, NO_WRAP);
|
|
614
638
|
|
|
615
639
|
for (const [index, line] of lines.entries()) {
|
|
616
640
|
// A `{do}` body is JavaScript: a line break there can change the program
|
|
617
641
|
if (
|
|
618
642
|
line.length <= maxLen ||
|
|
619
643
|
javaScript.has(index) ||
|
|
644
|
+
structured.has(index) ||
|
|
620
645
|
literalLines.has(line.trim())
|
|
621
646
|
) {
|
|
622
647
|
result.push(line);
|
|
@@ -655,9 +680,10 @@ function wrapLines(
|
|
|
655
680
|
function doBodyLines(lines: string[]): Set<number> {
|
|
656
681
|
const found = new Set<number>();
|
|
657
682
|
const text = lines.join('\n');
|
|
683
|
+
const lineAt = sourceLines(text);
|
|
658
684
|
for (const block of scanSpindleMarkup(text).doBlocks) {
|
|
659
|
-
const first =
|
|
660
|
-
const last =
|
|
685
|
+
const first = lineAt(block.bodyStart);
|
|
686
|
+
const last = lineAt(block.bodyEnd);
|
|
661
687
|
for (let i = first; i <= last; i++) found.add(i);
|
|
662
688
|
}
|
|
663
689
|
return found;
|
|
@@ -2,16 +2,20 @@ import { parse, postprocess, preprocess } from 'micromark';
|
|
|
2
2
|
import { analyzeMarkup } from '../markup/parse';
|
|
3
3
|
import { markdownOptions } from '../markup/markdown';
|
|
4
4
|
import type { PairedNode } from '../markup/pair';
|
|
5
|
+
import { sourceLines } from './source-lines';
|
|
5
6
|
|
|
6
|
-
/** Source lines
|
|
7
|
-
export function
|
|
7
|
+
/** Source lines belonging to the given constructs in runtime Markdown documents. */
|
|
8
|
+
export function markdownLines(
|
|
8
9
|
source: string,
|
|
9
10
|
isBlock: (name: string) => boolean,
|
|
11
|
+
types: ReadonlySet<string>,
|
|
10
12
|
): Set<number> {
|
|
11
13
|
const found = new Set<number>();
|
|
12
14
|
// Most passages contain no fence; avoid parsing their Markdown again.
|
|
13
|
-
if (!/`{3}|~{3}/.test(source))
|
|
15
|
+
if (types.size === 1 && types.has('codeFenced') && !/`{3}|~{3}/.test(source))
|
|
16
|
+
return found;
|
|
14
17
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
18
|
+
const lineAt = sourceLines(source);
|
|
15
19
|
|
|
16
20
|
function visit(nodes: PairedNode[]): void {
|
|
17
21
|
let markdown = '';
|
|
@@ -27,7 +31,7 @@ export function fencedCodeLines(
|
|
|
27
31
|
spans.push({ start, end: markdown.length, node });
|
|
28
32
|
if (
|
|
29
33
|
node.body &&
|
|
30
|
-
!(node.token.type === 'macro' && node.token.name === 'do')
|
|
34
|
+
!(node.token.type === 'macro' && node.token.name.toLowerCase() === 'do')
|
|
31
35
|
) {
|
|
32
36
|
visit(node.body.children);
|
|
33
37
|
for (const branch of node.body.branches) visit(branch.children);
|
|
@@ -39,16 +43,26 @@ export function fencedCodeLines(
|
|
|
39
43
|
.write(preprocess()(markdown, undefined, true)),
|
|
40
44
|
);
|
|
41
45
|
for (const [event, token] of events) {
|
|
42
|
-
if (event !== 'enter' || token.type
|
|
43
|
-
|
|
46
|
+
if (event !== 'enter' || !types.has(token.type)) continue;
|
|
47
|
+
// Spans are ordered and disjoint. Locate only those this token overlaps.
|
|
48
|
+
let low = 0;
|
|
49
|
+
let high = spans.length;
|
|
50
|
+
while (low < high) {
|
|
51
|
+
const middle = (low + high) >>> 1;
|
|
52
|
+
if (spans[middle]!.end <= token.start.offset) low = middle + 1;
|
|
53
|
+
else high = middle;
|
|
54
|
+
}
|
|
55
|
+
for (let i = low; i < spans.length; i++) {
|
|
56
|
+
const span = spans[i]!;
|
|
57
|
+
if (span.start >= token.end.offset) break;
|
|
44
58
|
const start = Math.max(token.start.offset, span.start);
|
|
45
59
|
const end = Math.min(token.end.offset, span.end);
|
|
46
60
|
if (start >= end) continue;
|
|
47
61
|
const text = span.node.token.type === 'text';
|
|
48
62
|
const a = text ? span.node.start + start - span.start : span.node.start;
|
|
49
63
|
const b = text ? span.node.start + end - span.start : span.node.end;
|
|
50
|
-
const first =
|
|
51
|
-
const last =
|
|
64
|
+
const first = lineAt(a);
|
|
65
|
+
const last = lineAt(Math.max(a, b - 1));
|
|
52
66
|
for (let line = first; line <= last; line++) found.add(line);
|
|
53
67
|
}
|
|
54
68
|
}
|
|
@@ -82,7 +82,7 @@ export function scanSpindleMarkup(text: string): MarkupScan {
|
|
|
82
82
|
}
|
|
83
83
|
} else if (t.type !== 'text') {
|
|
84
84
|
// The body of {do} is one text token, so nothing in it is a token
|
|
85
|
-
if (t.type === 'macro' && t.name === 'do') {
|
|
85
|
+
if (t.type === 'macro' && t.name.toLowerCase() === 'do') {
|
|
86
86
|
if (!t.isClose) open = t;
|
|
87
87
|
else if (open) {
|
|
88
88
|
doBlocks.push({
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Index a source once; locate zero-based lines without rescanning its prefixes. */
|
|
2
|
+
export function sourceLines(source: string): (offset: number) => number {
|
|
3
|
+
const starts = [0];
|
|
4
|
+
for (let i = 0; i < source.length; i++) {
|
|
5
|
+
if (source[i] === '\n') starts.push(i + 1);
|
|
6
|
+
}
|
|
7
|
+
return (offset) => {
|
|
8
|
+
let low = 0;
|
|
9
|
+
let high = starts.length;
|
|
10
|
+
while (low < high) {
|
|
11
|
+
const middle = (low + high) >>> 1;
|
|
12
|
+
if (starts[middle]! <= offset) low = middle + 1;
|
|
13
|
+
else high = middle;
|
|
14
|
+
}
|
|
15
|
+
return Math.max(0, low - 1);
|
|
16
|
+
};
|
|
17
|
+
}
|
package/src/js-lexer.ts
CHANGED
|
@@ -587,6 +587,24 @@ export function parseReferencePath(src: string): ReferencePath | null {
|
|
|
587
587
|
return { sigil: sigil[0], name: sigil[1], nested };
|
|
588
588
|
}
|
|
589
589
|
|
|
590
|
+
/** Decode one dot-member identifier, including keywords and Unicode names. */
|
|
591
|
+
export function parseMemberIdentifier(src: string): string | null {
|
|
592
|
+
const { ast } = parseWithAst(`x.${src}`, 'expression');
|
|
593
|
+
if (ast.type !== 'MemberExpression' || ast.computed) return null;
|
|
594
|
+
const object = ast.object as AnyNode;
|
|
595
|
+
const property = ast.property as AnyNode;
|
|
596
|
+
if (
|
|
597
|
+
object.type !== 'Identifier' ||
|
|
598
|
+
object.start !== 0 ||
|
|
599
|
+
object.end !== 1 ||
|
|
600
|
+
property.type !== 'Identifier' ||
|
|
601
|
+
property.start !== 2 ||
|
|
602
|
+
property.end !== src.length + 2
|
|
603
|
+
)
|
|
604
|
+
return null;
|
|
605
|
+
return property.name as string;
|
|
606
|
+
}
|
|
607
|
+
|
|
590
608
|
/**
|
|
591
609
|
* Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
|
|
592
610
|
* noting where it read a transient in `transientsRead`.
|
package/src/markup/spindle.peggy
CHANGED
|
@@ -207,6 +207,7 @@ TokenItem
|
|
|
207
207
|
/ Comment
|
|
208
208
|
/ LinkLexeme
|
|
209
209
|
/ EmailAutolink
|
|
210
|
+
/ &{ return !textMode; } UriAutolink
|
|
210
211
|
/ &{ return !textMode; } tag:HtmlOpen { return tag; }
|
|
211
212
|
/ &{ return !textMode; } tag:HtmlClose { return VOID_TAGS.has(tag.lower) ? null : tag; }
|
|
212
213
|
/ Value
|
|
@@ -369,6 +370,11 @@ EmailAutolink
|
|
|
369
370
|
&{ return EMAIL_AUTOLINK.test(value); }
|
|
370
371
|
{ return lexeme('text', location(), { value }); }
|
|
371
372
|
|
|
373
|
+
/** URI autolinks take precedence over HTML; Spindle markup stays active. */
|
|
374
|
+
UriAutolink
|
|
375
|
+
= value:$("<" [a-zA-Z] [a-zA-Z0-9+.-]|1..31| ":" (!"[[" [^\x00-\x20\x7F<>{}])* ">")
|
|
376
|
+
{ return lexeme('text', location(), { value }); }
|
|
377
|
+
|
|
372
378
|
HtmlOpen
|
|
373
379
|
= "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? ">" {
|
|
374
380
|
const lower = tag.toLowerCase();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isHidden } from '../utils/element-visibility';
|
|
1
|
+
import { isHidden, isRendered } from '../utils/element-visibility';
|
|
2
2
|
import { getAction } from '../action-registry';
|
|
3
3
|
|
|
4
4
|
/** Elements that start and end a line. */
|
|
@@ -66,9 +66,14 @@ function controlMarker(el: Element): string {
|
|
|
66
66
|
* The text a reader sees in the element, as lines: blocks and `<br>` break
|
|
67
67
|
* lines, hidden elements are left out, and a control with a `data-action`
|
|
68
68
|
* becomes a marker such as `[textbox $name: "Alice"]`. Elements inside `el`
|
|
69
|
-
* that match `skip` are left out with their content.
|
|
69
|
+
* that match `skip` are left out with their content. `visibilityRoot` bounds
|
|
70
|
+
* ancestor checks when reading StoryContext inside its hidden host.
|
|
70
71
|
*/
|
|
71
|
-
export function observableText(
|
|
72
|
+
export function observableText(
|
|
73
|
+
el: Element,
|
|
74
|
+
skip?: string,
|
|
75
|
+
visibilityRoot?: Element,
|
|
76
|
+
): string {
|
|
72
77
|
let out = '';
|
|
73
78
|
const endLine = () => {
|
|
74
79
|
if (out !== '' && !out.endsWith('\n')) out += '\n';
|
|
@@ -76,6 +81,8 @@ export function observableText(el: Element, skip?: string): string {
|
|
|
76
81
|
|
|
77
82
|
const walk = (node: Node, inPre: boolean) => {
|
|
78
83
|
if (node.nodeType === 3) {
|
|
84
|
+
if (node.parentElement && !isRendered(node.parentElement, visibilityRoot))
|
|
85
|
+
return;
|
|
79
86
|
const data = node.textContent ?? '';
|
|
80
87
|
if (inPre) out += data;
|
|
81
88
|
else {
|
|
@@ -95,11 +102,12 @@ export function observableText(el: Element, skip?: string): string {
|
|
|
95
102
|
(child.matches('input, textarea, select') ||
|
|
96
103
|
getAction(child.getAttribute('data-action')!)?.type === 'cycle')
|
|
97
104
|
) {
|
|
105
|
+
if (!isRendered(child, visibilityRoot)) return;
|
|
98
106
|
out += controlMarker(child);
|
|
99
107
|
return;
|
|
100
108
|
}
|
|
101
109
|
if (child.tagName === 'BR') {
|
|
102
|
-
out += '\n';
|
|
110
|
+
if (isRendered(child, visibilityRoot)) out += '\n';
|
|
103
111
|
return;
|
|
104
112
|
}
|
|
105
113
|
const block = BLOCKS.has(child.tagName);
|
|
@@ -134,7 +142,11 @@ export function observableText(el: Element, skip?: string): string {
|
|
|
134
142
|
* the reader can't see (inside a hidden element, as observableText() does)
|
|
135
143
|
* and those inside an element within `el` that matches `skip`.
|
|
136
144
|
*/
|
|
137
|
-
export function observableErrors(
|
|
145
|
+
export function observableErrors(
|
|
146
|
+
el: Element,
|
|
147
|
+
skip?: string,
|
|
148
|
+
visibilityRoot?: Element,
|
|
149
|
+
): string[] {
|
|
138
150
|
const left = (e: Element) => {
|
|
139
151
|
for (let at: Element | null = e; at; at = at.parentElement) {
|
|
140
152
|
if (isHidden(at)) return true;
|
|
@@ -144,6 +156,6 @@ export function observableErrors(el: Element, skip?: string): string[] {
|
|
|
144
156
|
return false;
|
|
145
157
|
};
|
|
146
158
|
return Array.from(el.querySelectorAll('.error'))
|
|
147
|
-
.filter((e) => !left(e))
|
|
148
|
-
.map((e) => (e
|
|
159
|
+
.filter((e) => !left(e) && isRendered(e, visibilityRoot))
|
|
160
|
+
.map((e) => observableText(e, skip, visibilityRoot).trim());
|
|
149
161
|
}
|
package/src/observe/observe.ts
CHANGED
|
@@ -15,9 +15,31 @@ import { storyContextElement } from '../story-context-passage';
|
|
|
15
15
|
import { innermostOpenDialog, openDialogPanels } from '../triggers';
|
|
16
16
|
import { checkObject, type Fail } from '../utils/field-checks';
|
|
17
17
|
import { observableErrors, observableText } from './observable-text';
|
|
18
|
+
import { stableKey } from '../utils/stable-key';
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
-
export type
|
|
20
|
+
/** A JSON value in an observation, detached from live story state. */
|
|
21
|
+
export type ObservedValue =
|
|
22
|
+
| string
|
|
23
|
+
| number
|
|
24
|
+
| boolean
|
|
25
|
+
| null
|
|
26
|
+
| ObservedValue[]
|
|
27
|
+
| { [key: string]: ObservedValue };
|
|
28
|
+
|
|
29
|
+
/** An action as an observation lists it, with a portable value and no perform. */
|
|
30
|
+
export type ObservedAction = Omit<StoryAction, 'perform' | 'value'> & {
|
|
31
|
+
value?: ObservedValue;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** JSON trees as snapshots; other values use the shared value description. */
|
|
35
|
+
function observedValue(value: unknown): ObservedValue {
|
|
36
|
+
const description = stableKey(value);
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(description);
|
|
39
|
+
} catch {
|
|
40
|
+
return description;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
21
43
|
|
|
22
44
|
/** Which actions an observation offers, besides the default ones. */
|
|
23
45
|
export interface ObservedActionRules {
|
|
@@ -76,7 +98,9 @@ export function filterObservedActions(
|
|
|
76
98
|
(!DEFAULT_EXCLUDED.has(action.type) ||
|
|
77
99
|
matchesAny(action, rules.include)),
|
|
78
100
|
)
|
|
79
|
-
.map(({ perform: _perform, ...rest }) =>
|
|
101
|
+
.map(({ perform: _perform, value, ...rest }) =>
|
|
102
|
+
value === undefined ? rest : { ...rest, value: observedValue(value) },
|
|
103
|
+
);
|
|
80
104
|
}
|
|
81
105
|
|
|
82
106
|
let observedRules: ObservedActionRules = {};
|
|
@@ -145,7 +169,8 @@ export function observe(): Observation {
|
|
|
145
169
|
text: body ? observableText(body, DIALOG) : '',
|
|
146
170
|
}));
|
|
147
171
|
const errors = [passageEl, ...bodies.map((d) => d.body), contextEl].flatMap(
|
|
148
|
-
(el) =>
|
|
172
|
+
(el) =>
|
|
173
|
+
el ? observableErrors(el, DIALOG, el === contextEl ? el : undefined) : [],
|
|
149
174
|
);
|
|
150
175
|
// The runtime errors shown (as banners) until dismissed, with what failed
|
|
151
176
|
for (const { context, message } of getRuntimeErrors()) {
|
|
@@ -154,7 +179,7 @@ export function observe(): Observation {
|
|
|
154
179
|
return {
|
|
155
180
|
passage: currentPassage,
|
|
156
181
|
text: passageEl ? observableText(passageEl, DIALOG) : '',
|
|
157
|
-
context: contextEl ? observableText(contextEl) : null,
|
|
182
|
+
context: contextEl ? observableText(contextEl, undefined, contextEl) : null,
|
|
158
183
|
dialogs,
|
|
159
184
|
actions: filterObservedActions(offeredActions(), observedRules),
|
|
160
185
|
errors,
|
package/src/play/session.ts
CHANGED
|
@@ -11,6 +11,8 @@ import type { Op, Request, WorkerData, WorkerMessage } from './protocol';
|
|
|
11
11
|
|
|
12
12
|
export interface PlaySessionOptions {
|
|
13
13
|
html: string;
|
|
14
|
+
/** Explicitly allow story JavaScript to access host Node APIs. Default false. */
|
|
15
|
+
trusted?: boolean;
|
|
14
16
|
/** Per call. Default 10_000. */
|
|
15
17
|
stepTimeoutMs?: number;
|
|
16
18
|
/** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
|
|
@@ -73,6 +75,7 @@ export function workerExecArgv(execArgv: readonly string[]): string[] {
|
|
|
73
75
|
* Opens a session that runs the story in a worker. There `window` is
|
|
74
76
|
* happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
|
|
75
77
|
* globals, but `window.foo = 1` does not make a bare global `foo`.
|
|
78
|
+
* Requires `trusted: true`: story code has unrestricted host Node access.
|
|
76
79
|
*/
|
|
77
80
|
export function openPlaySession(
|
|
78
81
|
options: PlaySessionOptions,
|
|
@@ -90,6 +93,13 @@ export function openPlaySessionWith(
|
|
|
90
93
|
options: PlaySessionOptions,
|
|
91
94
|
urls: { workerUrl: URL; headlessUrl: URL },
|
|
92
95
|
): Promise<PlaySession> {
|
|
96
|
+
if (options.trusted !== true) {
|
|
97
|
+
return Promise.reject(
|
|
98
|
+
new Error(
|
|
99
|
+
'spindle: openPlaySession() requires trusted: true; story JavaScript has unrestricted access to host Node APIs, files and environment. Only run code you trust.',
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
93
103
|
const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
|
|
94
104
|
if (
|
|
95
105
|
typeof stepTimeoutMs !== 'number' ||
|
package/src/saves/format.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { assertTrustedWatchers } from '../triggers';
|
|
5
5
|
import { deserialize, serialize } from '../class-registry';
|
|
6
|
-
import { createCounts } from '../utils/namespace';
|
|
6
|
+
import { createCounts, hasOwn } from '../utils/namespace';
|
|
7
7
|
import type { SavePayload } from './types';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -136,10 +136,22 @@ const isMoment = (value: unknown): boolean =>
|
|
|
136
136
|
typeof value.timestamp === 'number' &&
|
|
137
137
|
isOptionalPRNGSnapshot(value.prng);
|
|
138
138
|
|
|
139
|
+
/** Visit holes too, rejecting malformed metadata before copying any entries. */
|
|
140
|
+
function everyEntry(
|
|
141
|
+
value: unknown[],
|
|
142
|
+
valid: (entry: unknown) => boolean,
|
|
143
|
+
): boolean {
|
|
144
|
+
for (let i = 0; i < value.length; i++) {
|
|
145
|
+
if (!hasOwn(value, i) || !valid(value[i])) return false;
|
|
146
|
+
}
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
139
150
|
const isWatchers = (value: unknown): boolean =>
|
|
140
151
|
value === undefined ||
|
|
141
152
|
(Array.isArray(value) &&
|
|
142
|
-
|
|
153
|
+
everyEntry(
|
|
154
|
+
value,
|
|
143
155
|
(w) =>
|
|
144
156
|
isRecord(w) && typeof w.condition === 'string' && isRecord(w.options),
|
|
145
157
|
));
|
|
@@ -160,9 +172,8 @@ function isPayload(value: unknown): value is Record<string, unknown> {
|
|
|
160
172
|
return false;
|
|
161
173
|
}
|
|
162
174
|
const { history, historyIndex } = value;
|
|
163
|
-
// Array.from: every() skips the holes of a sparse array
|
|
164
175
|
if (!Array.isArray(history) || history.length === 0) return false;
|
|
165
|
-
if (!
|
|
176
|
+
if (!everyEntry(history, isMoment)) return false;
|
|
166
177
|
if (
|
|
167
178
|
typeof historyIndex !== 'number' ||
|
|
168
179
|
!Number.isInteger(historyIndex) ||
|
|
@@ -78,7 +78,8 @@ function StoryContextView({ ast }: { ast: ASTNode[] }) {
|
|
|
78
78
|
* story has none. It is mounted on the first call, hidden from the page and
|
|
79
79
|
* with its controls registering no actions, and stays mounted: it follows the
|
|
80
80
|
* story's variables, also across a restart. The element itself is not hidden
|
|
81
|
-
* (its parent is), so
|
|
81
|
+
* (its parent is), so observations bound visibility checks at the container.
|
|
82
|
+
* A passage that can't be
|
|
82
83
|
* parsed or rendered shows its error as text in the element; this never
|
|
83
84
|
* throws.
|
|
84
85
|
*/
|
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
const NOT_TEXT = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Whether the
|
|
6
|
-
*
|
|
7
|
-
* `display: none` and `aria-hidden="true"`.
|
|
5
|
+
* Whether the element hides its whole subtree, including stylesheet rules.
|
|
6
|
+
* This needs computed styles but no layout, so it also works headlessly.
|
|
8
7
|
*/
|
|
9
8
|
export function isHidden(el: Element): boolean {
|
|
10
9
|
return (
|
|
11
10
|
el.hasAttribute('hidden') ||
|
|
12
11
|
el.getAttribute('aria-hidden') === 'true' ||
|
|
13
12
|
/(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute('style') ?? '') ||
|
|
13
|
+
el.ownerDocument.defaultView?.getComputedStyle(el).display === 'none' ||
|
|
14
14
|
NOT_TEXT.has(el.tagName) ||
|
|
15
15
|
(el.parentElement?.tagName === 'DETAILS' &&
|
|
16
16
|
!el.parentElement.hasAttribute('open') &&
|
|
@@ -25,8 +25,9 @@ export function isHidden(el: Element): boolean {
|
|
|
25
25
|
* Whether `el` is in a closed `<details>`, other than in the summary that
|
|
26
26
|
* toggles it: the browser renders none of that content (#389).
|
|
27
27
|
*/
|
|
28
|
-
function inClosedDetails(el: Element): boolean {
|
|
29
|
-
|
|
28
|
+
function inClosedDetails(el: Element, root?: Element): boolean {
|
|
29
|
+
const stop = root?.parentElement;
|
|
30
|
+
for (let e = el.parentElement; e && e !== stop; e = e.parentElement) {
|
|
30
31
|
if (e.localName !== 'details' || e.hasAttribute('open')) continue;
|
|
31
32
|
const summary = Array.from(e.children).find(
|
|
32
33
|
(c) => c.localName === 'summary',
|
|
@@ -40,15 +41,19 @@ function inClosedDetails(el: Element): boolean {
|
|
|
40
41
|
* Whether CSS leaves `el` in the tab sequence: not `visibility: hidden`
|
|
41
42
|
* (inherited, so the computed value covers ancestors), not inside a
|
|
42
43
|
* `display: none` element and not in the hidden content of a closed
|
|
43
|
-
* `<details>`.
|
|
44
|
+
* `<details>`. An optional root bounds ancestor checks, so observations can
|
|
45
|
+
* read StoryContext inside its deliberately hidden host.
|
|
44
46
|
*/
|
|
45
|
-
export function isRendered(el: Element): boolean {
|
|
46
|
-
const
|
|
47
|
+
export function isRendered(el: Element, root?: Element): boolean {
|
|
48
|
+
const style = (e: Element) =>
|
|
49
|
+
e.ownerDocument.defaultView?.getComputedStyle(e);
|
|
50
|
+
const visibility = style(el)?.visibility;
|
|
47
51
|
if (visibility === 'hidden' || visibility === 'collapse') return false;
|
|
48
52
|
for (let e: Element | null = el; e; e = e.parentElement) {
|
|
49
|
-
if (
|
|
53
|
+
if (style(e)?.display === 'none') return false;
|
|
54
|
+
if (e === root) break;
|
|
50
55
|
}
|
|
51
|
-
return !inClosedDetails(el);
|
|
56
|
+
return !inClosedDetails(el, root);
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
/** Visibility shared by reader observations and native control handling. */
|
package/types/index.d.ts
CHANGED
|
@@ -235,8 +235,19 @@ export interface ActionMatcher {
|
|
|
235
235
|
disabled?: boolean;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
-
/**
|
|
239
|
-
export type
|
|
238
|
+
/** A JSON value in an observation, detached from live story state. */
|
|
239
|
+
export type ObservedValue =
|
|
240
|
+
| string
|
|
241
|
+
| number
|
|
242
|
+
| boolean
|
|
243
|
+
| null
|
|
244
|
+
| ObservedValue[]
|
|
245
|
+
| { [key: string]: ObservedValue };
|
|
246
|
+
|
|
247
|
+
/** An action as `Story.observe()` lists it, with a portable value and no perform. */
|
|
248
|
+
export type ObservedAction = Omit<StoryAction, 'perform' | 'value'> & {
|
|
249
|
+
value?: ObservedValue;
|
|
250
|
+
};
|
|
240
251
|
|
|
241
252
|
/**
|
|
242
253
|
* Which actions `Story.observe()` offers. `exclude` removes what it
|
package/types/play.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export function resolveStoryHtml(input: StoryInput): Promise<ResolvedStory>;
|
|
|
26
26
|
/** Options for {@link openPlaySession}. */
|
|
27
27
|
export interface PlaySessionOptions {
|
|
28
28
|
html: string;
|
|
29
|
+
/** Explicitly allow story JavaScript to access host Node APIs. Default false. */
|
|
30
|
+
trusted?: boolean;
|
|
29
31
|
/** Per call. Default 10_000. */
|
|
30
32
|
stepTimeoutMs?: number;
|
|
31
33
|
/** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
|
|
@@ -67,6 +69,9 @@ export interface PlaySession {
|
|
|
67
69
|
* peer dependency) and resolve with a session once the first passage is
|
|
68
70
|
* shown. Calls run one at a time; a call that takes longer than
|
|
69
71
|
* `stepTimeoutMs` closes the session.
|
|
72
|
+
* Requires `trusted: true`: story JavaScript has unrestricted access to host
|
|
73
|
+
* Node APIs, files and environment. Worker threads and happy-dom are not a
|
|
74
|
+
* security sandbox. Only run code you trust.
|
|
70
75
|
*
|
|
71
76
|
* In the worker, `window` is happy-dom's window, not `globalThis`. Story code
|
|
72
77
|
* sees `Story` and the DOM globals as in a browser, but a property set on
|