@rohal12/spindle 0.61.3 → 0.61.5
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 +104 -37
- package/dist/pkg/play.js +2 -0
- package/dist/pkg/story-variables.js +47 -13
- package/package.json +1 -1
- package/src/automation/runner.ts +24 -3
- package/src/class-registry.ts +16 -8
- package/src/components/macros/VarDisplay.tsx +6 -4
- package/src/components/macros/arg-utils.ts +2 -9
- package/src/components/macros/macro-args.ts +1 -1
- package/src/define-macro.ts +38 -4
- package/src/format/format-passage.ts +19 -5
- package/src/format/markdown-lines.ts +16 -4
- package/src/format/placeholders.ts +1 -1
- package/src/format/source-lines.ts +17 -0
- package/src/js-lexer.ts +18 -0
- package/src/play/session.ts +10 -0
- package/src/saves/format.ts +21 -4
- package/src/structural.ts +57 -32
- package/src/utils/stable-key.ts +8 -5
- package/src/utils/value-kinds.ts +4 -0
- package/types/play.d.ts +5 -0
package/src/define-macro.ts
CHANGED
|
@@ -25,9 +25,10 @@ import {
|
|
|
25
25
|
import type { ASTNode } from './markup/ast';
|
|
26
26
|
import { executeMutation, mutateState, readState } from './execute-mutation';
|
|
27
27
|
import { evaluateDisplay } from './expression';
|
|
28
|
-
import {
|
|
28
|
+
import { useStoryFields } from './hooks/use-story-fields';
|
|
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',
|
|
@@ -265,7 +299,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
|
|
|
265
299
|
);
|
|
266
300
|
}
|
|
267
301
|
ctx.varName = varExpr;
|
|
268
|
-
ctx.value =
|
|
302
|
+
ctx.value = getByPath(useStoryFields('variables').variables, segments);
|
|
269
303
|
// In program order, also when mutation code performs the input
|
|
270
304
|
ctx.getValue = () => getByPath(readState().variables, segments);
|
|
271
305
|
ctx.setValue = displayOnly
|
|
@@ -4,6 +4,7 @@ import type { PairedNode } from '../markup/pair';
|
|
|
4
4
|
import type { MacroToken } from '../markup/tokens';
|
|
5
5
|
import { segmentRegions } from './segment';
|
|
6
6
|
import { markdownLines } from './markdown-lines';
|
|
7
|
+
import { sourceLines } from './source-lines';
|
|
7
8
|
import {
|
|
8
9
|
formatJS,
|
|
9
10
|
formatCSS,
|
|
@@ -379,6 +380,7 @@ function whitespaceSensitiveLines(
|
|
|
379
380
|
): Set<number> {
|
|
380
381
|
const lines = new Set<number>();
|
|
381
382
|
if (!WHITESPACE_AS_WRITTEN.test(source)) return lines;
|
|
383
|
+
const lineAt = sourceLines(source);
|
|
382
384
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
383
385
|
function visit(nodes: PairedNode[]): void {
|
|
384
386
|
for (const node of nodes) {
|
|
@@ -391,8 +393,8 @@ function whitespaceSensitiveLines(
|
|
|
391
393
|
name.toLowerCase() === 'style' && /white-space\s*:/i.test(value),
|
|
392
394
|
))
|
|
393
395
|
) {
|
|
394
|
-
const first =
|
|
395
|
-
const last =
|
|
396
|
+
const first = lineAt(node.start);
|
|
397
|
+
const last = lineAt(node.end - 1);
|
|
396
398
|
for (let line = first; line <= last; line++) lines.add(line);
|
|
397
399
|
} else if (body) {
|
|
398
400
|
visit(body.children);
|
|
@@ -609,12 +611,14 @@ const NO_WRAP = new Set([
|
|
|
609
611
|
'atxHeading',
|
|
610
612
|
'setextHeading',
|
|
611
613
|
'table',
|
|
612
|
-
'
|
|
614
|
+
'listOrdered',
|
|
615
|
+
'listUnordered',
|
|
613
616
|
'blockQuote',
|
|
614
617
|
'definition',
|
|
615
618
|
'thematicBreak',
|
|
616
619
|
'htmlFlow',
|
|
617
620
|
'codeText',
|
|
621
|
+
'codeFenced',
|
|
618
622
|
'link',
|
|
619
623
|
'image',
|
|
620
624
|
]);
|
|
@@ -666,6 +670,15 @@ function wrapLines(
|
|
|
666
670
|
const indent = indentMatch?.[1] ?? '';
|
|
667
671
|
|
|
668
672
|
const wrapped = wordWrap(trimmed, maxLen, indent);
|
|
673
|
+
// A new line before inline punctuation can turn prose into a heading,
|
|
674
|
+
// list, quote, fence, etc. Keep the source line when wrapping adds syntax.
|
|
675
|
+
if (
|
|
676
|
+
wrapped.length > 1 &&
|
|
677
|
+
markdownLines(wrapped.join('\n'), isBlock, NO_WRAP).size
|
|
678
|
+
) {
|
|
679
|
+
result.push(line);
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
669
682
|
// Keep a Markdown hard break on the last wrapped line
|
|
670
683
|
if (line.endsWith(' ')) wrapped[wrapped.length - 1] += ' ';
|
|
671
684
|
result.push(...wrapped);
|
|
@@ -678,9 +691,10 @@ function wrapLines(
|
|
|
678
691
|
function doBodyLines(lines: string[]): Set<number> {
|
|
679
692
|
const found = new Set<number>();
|
|
680
693
|
const text = lines.join('\n');
|
|
694
|
+
const lineAt = sourceLines(text);
|
|
681
695
|
for (const block of scanSpindleMarkup(text).doBlocks) {
|
|
682
|
-
const first =
|
|
683
|
-
const last =
|
|
696
|
+
const first = lineAt(block.bodyStart);
|
|
697
|
+
const last = lineAt(block.bodyEnd);
|
|
684
698
|
for (let i = first; i <= last; i++) found.add(i);
|
|
685
699
|
}
|
|
686
700
|
return found;
|
|
@@ -2,6 +2,7 @@ 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
7
|
/** Source lines belonging to the given constructs in runtime Markdown documents. */
|
|
7
8
|
export function markdownLines(
|
|
@@ -14,6 +15,7 @@ export function markdownLines(
|
|
|
14
15
|
if (types.size === 1 && types.has('codeFenced') && !/`{3}|~{3}/.test(source))
|
|
15
16
|
return found;
|
|
16
17
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
18
|
+
const lineAt = sourceLines(source);
|
|
17
19
|
|
|
18
20
|
function visit(nodes: PairedNode[]): void {
|
|
19
21
|
let markdown = '';
|
|
@@ -29,7 +31,7 @@ export function markdownLines(
|
|
|
29
31
|
spans.push({ start, end: markdown.length, node });
|
|
30
32
|
if (
|
|
31
33
|
node.body &&
|
|
32
|
-
!(node.token.type === 'macro' && node.token.name === 'do')
|
|
34
|
+
!(node.token.type === 'macro' && node.token.name.toLowerCase() === 'do')
|
|
33
35
|
) {
|
|
34
36
|
visit(node.body.children);
|
|
35
37
|
for (const branch of node.body.branches) visit(branch.children);
|
|
@@ -42,15 +44,25 @@ export function markdownLines(
|
|
|
42
44
|
);
|
|
43
45
|
for (const [event, token] of events) {
|
|
44
46
|
if (event !== 'enter' || !types.has(token.type)) continue;
|
|
45
|
-
|
|
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;
|
|
46
58
|
const start = Math.max(token.start.offset, span.start);
|
|
47
59
|
const end = Math.min(token.end.offset, span.end);
|
|
48
60
|
if (start >= end) continue;
|
|
49
61
|
const text = span.node.token.type === 'text';
|
|
50
62
|
const a = text ? span.node.start + start - span.start : span.node.start;
|
|
51
63
|
const b = text ? span.node.start + end - span.start : span.node.end;
|
|
52
|
-
const first =
|
|
53
|
-
const last =
|
|
64
|
+
const first = lineAt(a);
|
|
65
|
+
const last = lineAt(Math.max(a, b - 1));
|
|
54
66
|
for (let line = first; line <= last; line++) found.add(line);
|
|
55
67
|
}
|
|
56
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/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,8 @@
|
|
|
3
3
|
|
|
4
4
|
import { assertTrustedWatchers } from '../triggers';
|
|
5
5
|
import { deserialize, serialize } from '../class-registry';
|
|
6
|
-
import {
|
|
6
|
+
import { assertArrayLengths } from '../structural';
|
|
7
|
+
import { createCounts, hasOwn } from '../utils/namespace';
|
|
7
8
|
import type { SavePayload } from './types';
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -13,6 +14,9 @@ import type { SavePayload } from './types';
|
|
|
13
14
|
*/
|
|
14
15
|
export const SAVE_FORMAT_VERSION = 1;
|
|
15
16
|
|
|
17
|
+
// Immer and author-facing array methods may scan logical slots, even holes.
|
|
18
|
+
const MAX_SAVE_ARRAY_LENGTH = 1_000_000;
|
|
19
|
+
|
|
16
20
|
/**
|
|
17
21
|
* A payload as stored: `data` is the payload serialized in one piece (see
|
|
18
22
|
* serialize() in class-registry.ts), so values the history moments share
|
|
@@ -94,6 +98,7 @@ function variablePathError(err: unknown): unknown {
|
|
|
94
98
|
*/
|
|
95
99
|
export function encodePayload(payload: SavePayload): EncodedPayload {
|
|
96
100
|
try {
|
|
101
|
+
assertArrayLengths(payload, MAX_SAVE_ARRAY_LENGTH);
|
|
97
102
|
return {
|
|
98
103
|
formatVersion: SAVE_FORMAT_VERSION,
|
|
99
104
|
data: serialize({
|
|
@@ -136,10 +141,22 @@ const isMoment = (value: unknown): boolean =>
|
|
|
136
141
|
typeof value.timestamp === 'number' &&
|
|
137
142
|
isOptionalPRNGSnapshot(value.prng);
|
|
138
143
|
|
|
144
|
+
/** Visit holes too, rejecting malformed metadata before copying any entries. */
|
|
145
|
+
function everyEntry(
|
|
146
|
+
value: unknown[],
|
|
147
|
+
valid: (entry: unknown) => boolean,
|
|
148
|
+
): boolean {
|
|
149
|
+
for (let i = 0; i < value.length; i++) {
|
|
150
|
+
if (!hasOwn(value, i) || !valid(value[i])) return false;
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
139
155
|
const isWatchers = (value: unknown): boolean =>
|
|
140
156
|
value === undefined ||
|
|
141
157
|
(Array.isArray(value) &&
|
|
142
|
-
|
|
158
|
+
everyEntry(
|
|
159
|
+
value,
|
|
143
160
|
(w) =>
|
|
144
161
|
isRecord(w) && typeof w.condition === 'string' && isRecord(w.options),
|
|
145
162
|
));
|
|
@@ -160,9 +177,8 @@ function isPayload(value: unknown): value is Record<string, unknown> {
|
|
|
160
177
|
return false;
|
|
161
178
|
}
|
|
162
179
|
const { history, historyIndex } = value;
|
|
163
|
-
// Array.from: every() skips the holes of a sparse array
|
|
164
180
|
if (!Array.isArray(history) || history.length === 0) return false;
|
|
165
|
-
if (!
|
|
181
|
+
if (!everyEntry(history, isMoment)) return false;
|
|
166
182
|
if (
|
|
167
183
|
typeof historyIndex !== 'number' ||
|
|
168
184
|
!Number.isInteger(historyIndex) ||
|
|
@@ -200,6 +216,7 @@ export function decodePayload(encoded: unknown): SavePayload {
|
|
|
200
216
|
if (typeof data !== 'string') throw invalid();
|
|
201
217
|
const body = deserialize(migrate(formatVersion, data));
|
|
202
218
|
if (!isPayload(body)) throw invalid();
|
|
219
|
+
assertArrayLengths(body, MAX_SAVE_ARRAY_LENGTH);
|
|
203
220
|
assertTrustedWatchers(
|
|
204
221
|
(body.watchers ?? []) as NonNullable<SavePayload['watchers']>,
|
|
205
222
|
);
|
package/src/structural.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { hasOwn, setOwn } from './utils/namespace';
|
|
|
14
14
|
import { deleteByPath, getByPath, setByPath } from './utils/object-path';
|
|
15
15
|
import {
|
|
16
16
|
ERROR_HIDDEN_KEYS,
|
|
17
|
+
arrayIndices,
|
|
17
18
|
collectionSize,
|
|
18
19
|
extraKeys,
|
|
19
20
|
isAtomic,
|
|
@@ -182,9 +183,8 @@ export function deepClone<T>(value: T, options: DeepCloneOptions = {}): T {
|
|
|
182
183
|
if (Array.isArray(val)) {
|
|
183
184
|
// Holes stay holes
|
|
184
185
|
const arr = builtin(obj, new Array(val.length) as unknown[]);
|
|
185
|
-
for (
|
|
186
|
-
|
|
187
|
-
}
|
|
186
|
+
for (const key of arrayIndices(val))
|
|
187
|
+
arr[Number(key)] = clone(val[Number(key)]);
|
|
188
188
|
return arr;
|
|
189
189
|
}
|
|
190
190
|
|
|
@@ -360,9 +360,7 @@ export function shareEqual<T>(prev: unknown, curr: T): T {
|
|
|
360
360
|
}
|
|
361
361
|
if (Array.isArray(c) && Array.isArray(p)) {
|
|
362
362
|
const out = collection(new Array(c.length) as unknown[]);
|
|
363
|
-
for (
|
|
364
|
-
if (i in c) out[i] = share(p[i], c[i]);
|
|
365
|
-
}
|
|
363
|
+
for (const key of arrayIndices(c)) out[Number(key)] = shareKey(key);
|
|
366
364
|
return out;
|
|
367
365
|
}
|
|
368
366
|
if (mergesWith(p, c, false)) {
|
|
@@ -521,10 +519,10 @@ function equal(a: unknown, b: unknown, assumed: Pairs): boolean {
|
|
|
521
519
|
if (Array.isArray(a)) {
|
|
522
520
|
const bc = b as unknown[];
|
|
523
521
|
if (a.length !== bc.length) return false;
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
522
|
+
return (
|
|
523
|
+
equalKeys(a, b, assumed, (v) => arrayIndices(v as unknown[])) &&
|
|
524
|
+
equalExtraKeys(a, b, assumed)
|
|
525
|
+
);
|
|
528
526
|
}
|
|
529
527
|
|
|
530
528
|
return equalKeys(a, b, assumed);
|
|
@@ -626,16 +624,21 @@ export function keyChanges(
|
|
|
626
624
|
if (Array.isArray(after)) {
|
|
627
625
|
const b = before as unknown as unknown[];
|
|
628
626
|
const a = after as unknown[];
|
|
629
|
-
|
|
627
|
+
const indices = [...new Set([...arrayIndices(b), ...arrayIndices(a)])].sort(
|
|
628
|
+
(x, y) => Number(x) - Number(y),
|
|
629
|
+
);
|
|
630
|
+
for (const key of indices) {
|
|
631
|
+
const i = Number(key);
|
|
632
|
+
if (i >= Math.min(b.length, a.length)) continue;
|
|
630
633
|
// A hole is no element: not the same as an undefined one
|
|
631
|
-
const key = String(i);
|
|
632
634
|
if (i in b && i in a) compare(key, b[i], a[i]);
|
|
633
635
|
else if (i in b) changes.push({ key, kind: 'deleted', hole: true });
|
|
634
636
|
else if (i in a) changes.push({ key, kind: 'added', after: a[i] });
|
|
635
637
|
}
|
|
636
638
|
let next = b.length;
|
|
637
|
-
for (
|
|
638
|
-
|
|
639
|
+
for (const key of arrayIndices(a)) {
|
|
640
|
+
const i = Number(key);
|
|
641
|
+
if (i < b.length) continue;
|
|
639
642
|
const gap = i - next;
|
|
640
643
|
changes.push({
|
|
641
644
|
key: String(i),
|
|
@@ -645,9 +648,9 @@ export function keyChanges(
|
|
|
645
648
|
});
|
|
646
649
|
next = i + 1;
|
|
647
650
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
+
// One truncation also removes trailing holes, however large the gap.
|
|
652
|
+
if (a.length < b.length)
|
|
653
|
+
changes.push({ key: String(a.length), kind: 'deleted' });
|
|
651
654
|
// Holes at the end are in no index, only in the length
|
|
652
655
|
if (a.length > next) {
|
|
653
656
|
changes.push({ key: 'length', kind: 'holes', after: a.length - next });
|
|
@@ -824,11 +827,11 @@ export function underChange(
|
|
|
824
827
|
|
|
825
828
|
/**
|
|
826
829
|
* The segment standing for the entry `index` of a Map or Set in a path, or
|
|
827
|
-
* for the `cause` or `errors` of an Error ('c', 'e'), or for
|
|
828
|
-
* typed array or DataView views ('b').
|
|
830
|
+
* for the `message`, `cause` or `errors` of an Error ('m', 'c', 'e'), or for
|
|
831
|
+
* the buffer a typed array or DataView views ('b').
|
|
829
832
|
*/
|
|
830
833
|
interface EntrySegment {
|
|
831
|
-
kind: 'k' | 'v' | 's' | 'c' | 'e' | 'b';
|
|
834
|
+
kind: 'k' | 'v' | 's' | 'm' | 'c' | 'e' | 'b';
|
|
832
835
|
index: number;
|
|
833
836
|
}
|
|
834
837
|
|
|
@@ -847,8 +850,9 @@ export const isEntryKey = (
|
|
|
847
850
|
|
|
848
851
|
/**
|
|
849
852
|
* What a Map, Set, Error or view holds in place of properties (keys and
|
|
850
|
-
* values, members, `cause` and `errors`, the buffer), each with
|
|
851
|
-
* a path (see entryKey); undefined for any
|
|
853
|
+
* values, members, `message`, `cause` and `errors`, the buffer), each with
|
|
854
|
+
* the segment standing for it in a path (see entryKey); undefined for any
|
|
855
|
+
* other value.
|
|
852
856
|
*/
|
|
853
857
|
function entryChildren(value: object): [EntrySegment, unknown][] | undefined {
|
|
854
858
|
const children: [EntrySegment, unknown][] = [];
|
|
@@ -864,10 +868,10 @@ function entryChildren(value: object): [EntrySegment, unknown][] | undefined {
|
|
|
864
868
|
children.push([entryKey('s', index++), member]);
|
|
865
869
|
}
|
|
866
870
|
} else if (value instanceof Error) {
|
|
867
|
-
for (const key of
|
|
871
|
+
for (const key of ERROR_HIDDEN_KEYS) {
|
|
868
872
|
if (hasOwn(value, key)) {
|
|
869
873
|
children.push([
|
|
870
|
-
entryKey(key === 'cause' ? 'c' : 'e', 0),
|
|
874
|
+
entryKey(key === 'message' ? 'm' : key === 'cause' ? 'c' : 'e', 0),
|
|
871
875
|
(value as any)[key],
|
|
872
876
|
]);
|
|
873
877
|
}
|
|
@@ -922,11 +926,17 @@ function setEntryValue(
|
|
|
922
926
|
}
|
|
923
927
|
|
|
924
928
|
/**
|
|
925
|
-
* The own enumerable fields of
|
|
926
|
-
* registered subclass may hold some besides its built-in
|
|
929
|
+
* The own enumerable fields of an Error, Map, Set, Date or RegExp (an
|
|
930
|
+
* instance of a registered subclass may hold some besides its built-in
|
|
931
|
+
* content, #412). Hidden Error data is visited through entryChildren;
|
|
927
932
|
* none for any other value.
|
|
928
933
|
*/
|
|
929
934
|
function builtinFields(value: object): string[] {
|
|
935
|
+
if (value instanceof Error) {
|
|
936
|
+
return Object.keys(value).filter(
|
|
937
|
+
(key) => !ERROR_HIDDEN_KEYS.some((hidden) => hidden === key),
|
|
938
|
+
);
|
|
939
|
+
}
|
|
930
940
|
return value instanceof Map ||
|
|
931
941
|
value instanceof Set ||
|
|
932
942
|
value instanceof Date ||
|
|
@@ -945,16 +955,16 @@ function sameBuiltin(x: object, y: object): boolean {
|
|
|
945
955
|
|
|
946
956
|
/**
|
|
947
957
|
* Every path each object (or array, or other value) of `root` is at, the
|
|
948
|
-
* first appearance first, in depth-first order. Plain objects and arrays
|
|
949
|
-
* entered, where first met only (an
|
|
950
|
-
*
|
|
951
|
-
* of `skip` is left out.
|
|
958
|
+
* first appearance first, in depth-first order. Plain objects and arrays
|
|
959
|
+
* (including non-enumerable indices) are entered, where first met only (an
|
|
960
|
+
* object held in an array is one object, however it was reached); other
|
|
961
|
+
* values are leaves. A path at or below one of `skip` is left out.
|
|
952
962
|
*
|
|
953
963
|
* With `entries`, the objects held in a Map or Set (as key, value or member)
|
|
954
964
|
* are placed too, after everything else: one met nowhere else is at the path
|
|
955
965
|
* of its Map or Set and the entry's segment (see entryKey), which is no path
|
|
956
966
|
* a value can be read at (see getByEntryPath), so only to tell where an
|
|
957
|
-
* object is from; so are the `cause` and `errors` of an Error.
|
|
967
|
+
* object is from; so are the `message`, `cause` and `errors` of an Error.
|
|
958
968
|
*/
|
|
959
969
|
function objectPaths(
|
|
960
970
|
root: object,
|
|
@@ -980,7 +990,9 @@ function objectPaths(
|
|
|
980
990
|
function walk(
|
|
981
991
|
node: Record<string, unknown>,
|
|
982
992
|
path: ObjectPath,
|
|
983
|
-
keys: string[] =
|
|
993
|
+
keys: string[] = Array.isArray(node)
|
|
994
|
+
? [...arrayIndices(node), ...extraKeys(node)]
|
|
995
|
+
: Object.keys(node),
|
|
984
996
|
): void {
|
|
985
997
|
for (const key of keys) {
|
|
986
998
|
const value = node[key];
|
|
@@ -1013,6 +1025,19 @@ function firstPaths(
|
|
|
1013
1025
|
);
|
|
1014
1026
|
}
|
|
1015
1027
|
|
|
1028
|
+
/**
|
|
1029
|
+
* Refuse arrays whose logical length would make downstream slot scans
|
|
1030
|
+
* (including Immer's array freezing) excessive. Inspect populated keys and
|
|
1031
|
+
* collection entries only, sharing the graph walk used for structural diffs.
|
|
1032
|
+
*/
|
|
1033
|
+
export function assertArrayLengths(root: object, maxLength: number): void {
|
|
1034
|
+
for (const value of objectPaths({ root }, undefined, true).keys()) {
|
|
1035
|
+
if (Array.isArray(value) && value.length > maxLength) {
|
|
1036
|
+
throw new RangeError(`Save arrays cannot exceed ${maxLength} elements`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1016
1041
|
/**
|
|
1017
1042
|
* The objects `root` holds at more than one path (an object two variables
|
|
1018
1043
|
* refer to, or one that refers to itself), with every path they are at,
|
package/src/utils/stable-key.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { hasOwn } from './namespace';
|
|
|
2
2
|
import { registeredClassName } from '../class-registry';
|
|
3
3
|
import {
|
|
4
4
|
ERROR_HIDDEN_KEYS,
|
|
5
|
+
arrayIndices,
|
|
5
6
|
extraKeys,
|
|
6
7
|
isBoxed,
|
|
7
8
|
isTemporal,
|
|
@@ -42,9 +43,6 @@ export function stableKey(value: unknown): string {
|
|
|
42
43
|
}
|
|
43
44
|
}
|
|
44
45
|
|
|
45
|
-
/** The key of an array slot that holds no element. */
|
|
46
|
-
const HOLE = '<hole>';
|
|
47
|
-
|
|
48
46
|
/**
|
|
49
47
|
* The key of `val`. `seen` numbers the objects keyed so far, in the order
|
|
50
48
|
* they were first met.
|
|
@@ -106,9 +104,14 @@ function keyOf(val: unknown, seen: Map<object, number>): string {
|
|
|
106
104
|
// A hole is no element, not an undefined one (#497), as for deepEqual
|
|
107
105
|
// and a save; a plain `map` would skip it, giving `[,]` the key of `[]`
|
|
108
106
|
const items: string[] = [];
|
|
109
|
-
|
|
110
|
-
|
|
107
|
+
let next = 0;
|
|
108
|
+
for (const index of arrayIndices(val)) {
|
|
109
|
+
const i = Number(index);
|
|
110
|
+
if (i > next) items.push(`<holes ${i - next}>`);
|
|
111
|
+
items.push(keyOf(val[i], seen));
|
|
112
|
+
next = i + 1;
|
|
111
113
|
}
|
|
114
|
+
if (val.length > next) items.push(`<holes ${val.length - next}>`);
|
|
112
115
|
return withFields(`[${items.join(',')}]`);
|
|
113
116
|
}
|
|
114
117
|
const atomic = atomicKey(obj, seen);
|
package/src/utils/value-kinds.ts
CHANGED
|
@@ -53,6 +53,10 @@ export const ERROR_HIDDEN_KEYS = ['message', 'cause', 'errors'] as const;
|
|
|
53
53
|
export const isIndexKey = (key: string): boolean =>
|
|
54
54
|
key !== '4294967295' && String(Number(key) >>> 0) === key;
|
|
55
55
|
|
|
56
|
+
/** Populated own array indices, in order, without visiting holes. */
|
|
57
|
+
export const arrayIndices = (value: unknown[]): string[] =>
|
|
58
|
+
Object.getOwnPropertyNames(value).filter(isIndexKey);
|
|
59
|
+
|
|
56
60
|
/**
|
|
57
61
|
* The own enumerable string keys of a collection (an Array, Map or Set) that
|
|
58
62
|
* are not its elements: what an instance of a subclass may hold besides
|
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
|