@rohal12/spindle 0.59.23 → 0.59.25

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.
@@ -1,7 +1,11 @@
1
1
  import type { Passage } from './parser';
2
2
  import type { Spans, Token } from './markup/tokens';
3
- import { MarkupError, tokenizeMarkup } from './markup/parse';
4
- import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
3
+ import {
4
+ MarkupError,
5
+ tokenizeMarkup,
6
+ tokenizeMarkupTolerant,
7
+ } from './markup/parse';
8
+ import { isCodeAttribute } from './markup/code-attributes';
5
9
  import { errorMessage } from './utils/error-message';
6
10
  import {
7
11
  CodeSyntaxError,
@@ -11,7 +15,10 @@ import {
11
15
  } from './js-lexer';
12
16
  import {
13
17
  argPieces,
18
+ attributeValues,
19
+ sigilExpressions,
14
20
  parseOrError,
21
+ pieceOffset,
15
22
  withParseCache,
16
23
  type ParametersOf,
17
24
  } from './code-check';
@@ -21,10 +28,15 @@ import { createNamespace, variableNameError } from './utils/namespace';
21
28
  import { staticLiteral, type LiteralShape } from './static-literal';
22
29
 
23
30
  /**
24
- * The tokens of markup, or none if it is malformed: validateMarkup reports
25
- * that, with its position.
31
+ * The tokens of markup, or none if it is malformed (validateMarkup reports
32
+ * that, with its position); in tolerant mode, those of the well-formed parts.
26
33
  */
27
- function tokensOf(text: string, textMode: boolean): Token[] {
34
+ function tokensOf(
35
+ text: string,
36
+ textMode: boolean,
37
+ { tolerant }: { tolerant?: boolean } = {},
38
+ ): Token[] {
39
+ if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
28
40
  try {
29
41
  return tokenizeMarkup(text, { text: textMode });
30
42
  } catch (err) {
@@ -55,8 +67,8 @@ function declarationRegex(sigil: string): RegExp {
55
67
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
68
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
57
69
  }
58
- /** A `$name` reference with its dot path, at a `$` the lexer found. */
59
- const VAR_PATH_RE = /\$(\w+(?:\.\w+)*)/y;
70
+ /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
71
+ const VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
60
72
  /** Quoted first argument of an input macro naming a story variable. */
61
73
  const QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
62
74
 
@@ -287,29 +299,86 @@ export function parseStoryVariables(
287
299
  return schema;
288
300
  }
289
301
 
302
+ /** A reference to a story (`$`) or transient (`%`) variable in markup. */
303
+ export interface VariableReference {
304
+ sigil: '$' | '%';
305
+ /** The variable, without the sigil. */
306
+ name: string;
307
+ /** The fields accessed with dots (`$a.b.c`: `['b', 'c']`). */
308
+ path: string[];
309
+ /** Where `$a.b.c` is written in the markup, as `[start, end)` UTF-16 offsets. */
310
+ start: number;
311
+ end: number;
312
+ }
313
+
314
+ /** What a check of a variable reference found wrong with it. */
315
+ export type VariableDiagnosticCode =
316
+ | 'undeclared-variable'
317
+ | 'undeclared-transient'
318
+ | 'reserved-name'
319
+ | 'primitive-field';
320
+
321
+ /** A variable reference that is not valid against the declarations. */
322
+ export interface VariableDiagnostic {
323
+ passage: string;
324
+ code: VariableDiagnosticCode;
325
+ /** The variable, without the sigil. */
326
+ name: string;
327
+ /** The fields accessed with dots. */
328
+ path?: string[];
329
+ /** The reference, as offsets into the passage content. */
330
+ start: number;
331
+ end: number;
332
+ message: string;
333
+ }
334
+
290
335
  /**
291
- * Validate a single variable reference path (e.g. "player.health") against
292
- * the schema. Returns an error message or null if valid.
336
+ * What is declared: the schema of each variable, which is absent for one
337
+ * whose initializer is not static (`parseDeclarations`): it is declared, but
338
+ * its fields are not checked.
293
339
  */
294
- function validateRef(
295
- ref: string,
296
- schema: Map<string, VariableSchema>,
297
- ): string | null {
298
- const parts = ref.split('.');
299
- const rootName = parts[0]!;
300
-
301
- const nameError = variableNameError(rootName, '$' + rootName);
302
- if (nameError) return nameError;
340
+ export interface VariableDeclarations {
341
+ variables: ReadonlyMap<string, FieldSchema | undefined>;
342
+ /**
343
+ * The transients (`%`). They are not checked when absent, as the story
344
+ * start does not check them.
345
+ */
346
+ transients?: ReadonlyMap<string, FieldSchema | undefined>;
347
+ }
303
348
 
304
- const rootSchema = schema.get(rootName);
305
- if (!rootSchema) {
306
- return `Undeclared variable: $${ref}`;
349
+ /**
350
+ * Check a reference against the declarations: the error code and message, or
351
+ * null if it is valid. (Unknown fields of objects are valid: classes
352
+ * registered with Story.registerClass() can add members that are not in the
353
+ * defaults.)
354
+ */
355
+ function checkReference(
356
+ ref: VariableReference,
357
+ declared: VariableDeclarations,
358
+ ): { code: VariableDiagnosticCode; message: string } | null {
359
+ const label = (path: readonly string[]) =>
360
+ ref.sigil + [ref.name, ...path].join('.');
361
+ const nameError = variableNameError(ref.name, ref.sigil + ref.name);
362
+ if (nameError) return { code: 'reserved-name', message: nameError };
363
+
364
+ const schema = ref.sigil === '$' ? declared.variables : declared.transients;
365
+ if (!schema) return null;
366
+ if (!schema.has(ref.name)) {
367
+ return ref.sigil === '$'
368
+ ? {
369
+ code: 'undeclared-variable',
370
+ message: `Undeclared variable: ${label(ref.path)}`,
371
+ }
372
+ : {
373
+ code: 'undeclared-transient',
374
+ message: `Undeclared transient: ${label(ref.path)}`,
375
+ };
307
376
  }
308
377
 
309
- // Walk through field access path
310
- let current: FieldSchema = rootSchema;
311
- for (let i = 1; i < parts.length; i++) {
312
- const part = parts[i] as string;
378
+ // Walk through the field access path
379
+ let current = schema.get(ref.name);
380
+ for (let i = 0; current && i < ref.path.length; i++) {
381
+ const part = ref.path[i]!;
313
382
 
314
383
  // Arrays have built-in methods/properties (push, find, length, etc.)
315
384
  // so any field access on an array is allowed.
@@ -329,15 +398,12 @@ function validateRef(
329
398
  }
330
399
 
331
400
  if (current.type !== 'object' || !current.fields) {
332
- return `Cannot access field "${part}" on $${parts.slice(0, i).join('.')} (type: ${current.type})`;
401
+ return {
402
+ code: 'primitive-field',
403
+ message: `Cannot access field "${part}" on ${label(ref.path.slice(0, i))} (type: ${current.type})`,
404
+ };
333
405
  }
334
- const fieldSchema = current.fields.get(part);
335
- if (!fieldSchema) {
336
- // Unknown fields on objects are allowed — classes registered via
337
- // Story.registerClass() can add methods/getters not in the defaults.
338
- return null;
339
- }
340
- current = fieldSchema;
406
+ current = current.fields.get(part);
341
407
  }
342
408
 
343
409
  return null;
@@ -357,17 +423,49 @@ const BUILTIN_STORE_VAR_MACROS: readonly string[] = [
357
423
  'textbox',
358
424
  ];
359
425
 
360
- type RefCallback = (ref: string) => void;
426
+ /** What reading the variable references of markup depends on. */
427
+ interface ReferenceOptions {
428
+ /** The (lowercase) names of the input macros that bind a variable. */
429
+ storeVarMacros: ReadonlySet<string>;
430
+ parametersOf: ParametersOf;
431
+ /** Read half-typed markup: skip its malformed tags (default: none read). */
432
+ tolerant?: boolean;
433
+ }
434
+
435
+ /** Where index `i` of a text is in the markup being read. */
436
+ type At = (i: number) => number;
437
+
438
+ type Emit = (ref: VariableReference) => void;
361
439
 
362
440
  const NO_STORE_VAR_MACROS: ReadonlySet<string> = new Set();
363
441
 
442
+ /** A reference written at `index` of `code`, with its dot path. */
443
+ function referenceAt(
444
+ code: string,
445
+ index: number,
446
+ at: At,
447
+ ): VariableReference | undefined {
448
+ VAR_PATH_RE.lastIndex = index;
449
+ const match = VAR_PATH_RE.exec(code);
450
+ if (!match) return undefined;
451
+ const [name, ...path] = match[2]!.split('.');
452
+ return {
453
+ sigil: match[1] as '$' | '%',
454
+ name: name!,
455
+ path,
456
+ start: at(index),
457
+ end: at(index + match[0].length),
458
+ };
459
+ }
460
+
364
461
  /**
365
462
  * Scan the value of a code attribute (`onclick`, see isCodeAttribute) for
366
- * the `{$…}` references resolved in it; its other braces are code.
463
+ * the `{$…}` references resolved in it; its other braces are code. `at` is
464
+ * where the value is.
367
465
  */
368
- function scanSigilReferences(value: string, onRef: RefCallback): void {
369
- for (const part of splitSigilTemplate(value)) {
370
- if ('expr' in part) scanCode(part.expr, onRef);
466
+ function scanSigilReferences(value: string, at: At, emit: Emit): void {
467
+ for (const { expr, at: k } of sigilExpressions(value)) {
468
+ scanCode(expr, (i) => at(k + i), emit);
371
469
  }
372
470
  }
373
471
 
@@ -379,11 +477,12 @@ function scanSigilReferences(value: string, onRef: RefCallback): void {
379
477
  */
380
478
  function scanInterpolations(
381
479
  text: string,
382
- onRef: RefCallback,
383
- storeVarMacros: ReadonlySet<string> = NO_STORE_VAR_MACROS,
480
+ at: At,
481
+ emit: Emit,
482
+ options: ReferenceOptions,
384
483
  ): void {
385
484
  if (!text.includes('{')) return;
386
- collectTokenRefs(text, tokensOf(text, true), storeVarMacros, onRef);
485
+ collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
387
486
  }
388
487
 
389
488
  /**
@@ -396,34 +495,36 @@ function scanInterpolations(
396
495
  */
397
496
  function scanCode(
398
497
  code: string,
399
- onRef: RefCallback,
498
+ at: At,
499
+ emit: Emit,
400
500
  goal: JsGoal = 'expression',
401
501
  ): void {
402
502
  const parsed = parseOrError(code, goal);
403
503
  if (parsed instanceof CodeSyntaxError) {
404
- scanCodeLeniently(code, onRef, goal);
504
+ scanCodeLeniently(code, at, emit, goal);
405
505
  return;
406
506
  }
407
507
  for (const ref of parsed.refs) {
408
- if (ref.sigil !== '$') continue;
409
- VAR_PATH_RE.lastIndex = ref.start;
410
- onRef(VAR_PATH_RE.exec(code)![1]!);
508
+ if (ref.sigil !== '$' && ref.sigil !== '%') continue;
509
+ const found = referenceAt(code, ref.start, at);
510
+ if (found) emit(found);
411
511
  }
412
512
  }
413
513
 
414
514
  /** `scanCode` for code acorn can't parse: lexed leniently. */
415
515
  function scanCodeLeniently(
416
516
  code: string,
417
- onRef: RefCallback,
517
+ at: At,
518
+ emit: Emit,
418
519
  goal: JsGoal,
419
520
  ): void {
420
521
  lexJs(
421
522
  code,
422
523
  {
423
524
  variable(sigil, _name, index) {
424
- if (sigil !== '$') return;
425
- VAR_PATH_RE.lastIndex = index;
426
- onRef(VAR_PATH_RE.exec(code)![1]!);
525
+ if (sigil !== '$' && sigil !== '%') return;
526
+ const found = referenceAt(code, index, at);
527
+ if (found) emit(found);
427
528
  },
428
529
  // Strings, regex literals and comments hold no references
429
530
  literal() {},
@@ -432,29 +533,6 @@ function scanCodeLeniently(
432
533
  );
433
534
  }
434
535
 
435
- /**
436
- * Report the `$var` references a passage evaluates at runtime: `{$var}`
437
- * displays, `{$expr}` expressions, macro arguments and `{do}` bodies (as
438
- * code), quoted variable names bound by input macros, and `{$…}`
439
- * interpolations in HTML attributes. Prose is literal text and not scanned.
440
- */
441
- function collectPassageRefs(
442
- content: string,
443
- storeVarMacros: ReadonlySet<string>,
444
- onRef: RefCallback,
445
- parametersOf: ParametersOf,
446
- ): void {
447
- withParseCache(() =>
448
- collectTokenRefs(
449
- content,
450
- tokensOf(content, false),
451
- storeVarMacros,
452
- onRef,
453
- parametersOf,
454
- ),
455
- );
456
- }
457
-
458
536
  /**
459
537
  * Report the references in the arguments of a macro by what its parameters
460
538
  * say each holds (see ParameterDef.holds): code is scanned as code and
@@ -465,55 +543,111 @@ function collectPassageRefs(
465
543
  function scanArgs(
466
544
  token: Extract<Token, { type: 'macro' }>,
467
545
  params: readonly ParameterDef[] | undefined,
468
- onRef: RefCallback,
546
+ at: At,
547
+ emit: Emit,
548
+ options: ReferenceOptions,
469
549
  ): void {
470
550
  if (!token.rawArgs) return;
471
551
  if (params) {
472
- const pieces = [...argPieces(token.rawArgs, 0, params, token.name, '')];
552
+ const pieces = [
553
+ ...argPieces(token.rawArgs, token.argsStart, params, token.name, ''),
554
+ ];
473
555
  if (!pieces.some((piece) => piece.kind === 'argument-error')) {
474
556
  for (const piece of pieces) {
475
- if (piece.kind === 'code') scanCode(piece.code, onRef, piece.goal);
476
- else if (piece.kind === 'text') scanInterpolations(piece.text, onRef);
557
+ const pieceAt: At = (i) => at(pieceOffset(piece, i));
558
+ if (piece.kind === 'code') {
559
+ scanCode(piece.code, pieceAt, emit, piece.goal);
560
+ } else if (piece.kind === 'text') {
561
+ scanInterpolations(piece.text, pieceAt, emit, {
562
+ ...options,
563
+ storeVarMacros: NO_STORE_VAR_MACROS,
564
+ });
565
+ }
477
566
  }
478
567
  return;
479
568
  }
480
569
  }
481
- scanCode(token.rawArgs, onRef);
570
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
482
571
  }
483
572
 
484
573
  /** Report the `$var` references in the tokens of `content`. */
485
574
  function collectTokenRefs(
486
575
  content: string,
487
576
  tokens: Token[],
488
- storeVarMacros: ReadonlySet<string>,
489
- onRef: RefCallback,
490
- parametersOf: ParametersOf = () => undefined,
577
+ at: At,
578
+ emit: Emit,
579
+ options: ReferenceOptions,
491
580
  ): void {
581
+ const { storeVarMacros, parametersOf } = options;
492
582
  for (let t = 0; t < tokens.length; t++) {
493
583
  const token = tokens[t]!;
494
584
  if (token.type === 'variable') {
495
- if (token.scope === 'variable' && token.name) onRef(token.name);
585
+ if (
586
+ (token.scope === 'variable' || token.scope === 'transient') &&
587
+ token.name
588
+ ) {
589
+ const [name, ...path] = token.name.split('.');
590
+ emit({
591
+ sigil: token.scope === 'variable' ? '$' : '%',
592
+ name: name!,
593
+ path,
594
+ start: at(token.nameStart - 1),
595
+ end: at(token.nameEnd),
596
+ });
597
+ }
496
598
  } else if (token.type === 'link') {
497
- scanInterpolations(token.display, onRef);
599
+ scanInterpolations(
600
+ token.display,
601
+ (i) => at(token.displayStart + i),
602
+ emit,
603
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
604
+ );
498
605
  } else if (token.type === 'expression') {
499
- scanCode(token.expression, onRef);
606
+ scanCode(token.expression, (i) => at(token.expressionStart + i), emit);
500
607
  } else if (token.type === 'html') {
501
- for (const [name, value] of Object.entries(token.attributes)) {
502
- if (isCodeAttribute(name)) scanSigilReferences(value, onRef);
503
- else scanInterpolations(value, onRef, storeVarMacros);
608
+ for (const { name, value, at: valueAt } of attributeValues(
609
+ content,
610
+ token,
611
+ )) {
612
+ const valueIn: At = (i) => at(valueAt + i);
613
+ if (isCodeAttribute(name)) scanSigilReferences(value, valueIn, emit);
614
+ else scanInterpolations(value, valueIn, emit, options);
504
615
  }
505
616
  } else if (token.type === 'macro' && !token.isClose) {
506
- scanArgs(token, parametersOf(token.name), onRef);
617
+ scanArgs(token, parametersOf(token.name), at, emit, options);
507
618
  // Selectors (`{.{$cls} button}`) are interpolated when rendered
508
- if (token.className) scanInterpolations(token.className, onRef);
509
- if (token.id) scanInterpolations(token.id, onRef);
619
+ if (
620
+ token.selectorsStart !== undefined &&
621
+ token.selectorsEnd !== undefined
622
+ ) {
623
+ const from = token.selectorsStart;
624
+ scanInterpolations(
625
+ content.slice(from, token.selectorsEnd),
626
+ (i) => at(from + i),
627
+ emit,
628
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
629
+ );
630
+ }
510
631
 
511
632
  if (storeVarMacros.has(token.name.toLowerCase())) {
633
+ const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
512
634
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? '';
513
635
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
514
- if (quoted) onRef(quoted[1]!);
636
+ if (quoted) {
637
+ const [name, ...path] = quoted[1]!.split('.');
638
+ const start = token.argsStart + lead + 1;
639
+ emit({
640
+ sigil: '$',
641
+ name: name!,
642
+ path,
643
+ start: at(start),
644
+ end: at(start + 1 + quoted[1]!.length),
645
+ });
646
+ }
515
647
  // Unquoted, the variable is an argument of no declared role
516
- else if (!/^["'`]/.test(first)) scanCode(first, onRef);
648
+ else if (!/^["'`]/.test(first)) {
649
+ scanCode(first, (i) => at(token.argsStart + lead + i), emit);
650
+ }
517
651
  }
518
652
 
519
653
  if (token.name.toLowerCase() === 'do') {
@@ -533,7 +667,7 @@ function collectTokenRefs(
533
667
  }
534
668
  if (close < tokens.length) {
535
669
  const body = content.slice(token.end, tokens[close]!.start);
536
- scanCode(body, onRef, 'statements');
670
+ scanCode(body, (i) => at(token.end + i), emit, 'statements');
537
671
  t = close;
538
672
  }
539
673
  }
@@ -541,6 +675,60 @@ function collectTokenRefs(
541
675
  }
542
676
  }
543
677
 
678
+ /**
679
+ * The `$` and `%` variable references a passage evaluates at runtime, in
680
+ * source order: `{$var}` displays, `{$expr}` expressions, macro arguments and
681
+ * `{do}` bodies (as code), quoted variable names bound by input macros, and
682
+ * `{$…}` interpolations in labels and HTML attributes. Prose is literal text
683
+ * and not scanned.
684
+ */
685
+ export function collectVariableReferences(
686
+ content: string,
687
+ options: ReferenceOptions,
688
+ ): VariableReference[] {
689
+ const found: VariableReference[] = [];
690
+ withParseCache(() =>
691
+ collectTokenRefs(
692
+ content,
693
+ tokensOf(content, false, options),
694
+ (i) => i,
695
+ (ref) => found.push(ref),
696
+ options,
697
+ ),
698
+ );
699
+ return found;
700
+ }
701
+
702
+ /**
703
+ * The invalid variable references of the passages, against what is declared,
704
+ * with their positions. The passages that hold no markup (the declarations
705
+ * themselves, SaveTitle) are skipped.
706
+ */
707
+ export function checkVariableReferences(
708
+ passages: Iterable<{ name: string; content: string }>,
709
+ declared: VariableDeclarations,
710
+ options: ReferenceOptions,
711
+ ): VariableDiagnostic[] {
712
+ const diagnostics: VariableDiagnostic[] = [];
713
+ for (const passage of passages) {
714
+ if (NOT_MARKUP.has(passage.name)) continue;
715
+ for (const ref of collectVariableReferences(passage.content, options)) {
716
+ const error = checkReference(ref, declared);
717
+ if (!error) continue;
718
+ diagnostics.push({
719
+ passage: passage.name,
720
+ code: error.code,
721
+ name: ref.name,
722
+ ...(ref.path.length > 0 ? { path: ref.path } : {}),
723
+ start: ref.start,
724
+ end: ref.end,
725
+ message: error.message,
726
+ });
727
+ }
728
+ }
729
+ return diagnostics;
730
+ }
731
+
544
732
  /**
545
733
  * Check the `$var` references of all passages against the schema, at story
546
734
  * start. Returns the error messages (empty = valid). (The syntax of their
@@ -555,29 +743,16 @@ export function validatePassages(
555
743
  storeVarMacros: Iterable<string> = BUILTIN_STORE_VAR_MACROS,
556
744
  parametersOf: ParametersOf = getMacroParameters,
557
745
  ): string[] {
558
- const errors: string[] = [];
559
- const storeVarSet = new Set(
560
- Array.from(storeVarMacros, (m) => m.toLowerCase()),
561
- );
562
-
563
- for (const [name, passage] of passages) {
564
- // Don't validate the declarations or the SaveTitle code themselves
565
- if (NOT_MARKUP.has(name)) continue;
566
-
567
- collectPassageRefs(
568
- passage.content,
569
- storeVarSet,
570
- (ref) => {
571
- const error = validateRef(ref, schema);
572
- if (error) {
573
- errors.push(`Passage "${name}": ${error}`);
574
- }
575
- },
746
+ return checkVariableReferences(
747
+ passages.values(),
748
+ { variables: schema },
749
+ {
750
+ storeVarMacros: new Set(
751
+ Array.from(storeVarMacros, (m) => m.toLowerCase()),
752
+ ),
576
753
  parametersOf,
577
- );
578
- }
579
-
580
- return errors;
754
+ },
755
+ ).map((d) => `Passage "${d.passage}": ${d.message}`);
581
756
  }
582
757
 
583
758
  /**
package/src/tooling.ts CHANGED
@@ -19,10 +19,27 @@ import {
19
19
  type PassageReference,
20
20
  type Piece,
21
21
  } from './code-check';
22
- import { blockWidgetNames } from './widgets/widget-def';
22
+ import {
23
+ blockWidgetNames,
24
+ widgetDefinitions as readWidgetDefinitions,
25
+ type WidgetDefinition,
26
+ } from './widgets/widget-def';
27
+ import {
28
+ checkVariableReferences,
29
+ collectVariableReferences,
30
+ type VariableDeclarations,
31
+ type VariableDiagnostic,
32
+ type VariableReference,
33
+ } from './story-variables';
23
34
  import type { ParameterDef } from './registry';
24
35
 
25
36
  export { parseDeclarations, parseStoryVariables } from './story-variables';
37
+ export type {
38
+ VariableDeclarations,
39
+ VariableDiagnostic,
40
+ VariableDiagnosticCode,
41
+ VariableReference,
42
+ } from './story-variables';
26
43
  export type {
27
44
  Declaration,
28
45
  DeclarationError,
@@ -33,6 +50,8 @@ export type {
33
50
  } from './story-variables';
34
51
  export { checkParameterTypes } from './registry';
35
52
  export { formatDiagnostic } from './markup/validate';
53
+ export { parseWidgetDef } from './widgets/widget-def';
54
+ export type { WidgetDef, WidgetDefinition } from './widgets/widget-def';
36
55
 
37
56
  // The parsing rules (see "Tooling API" in docs/tooling.md): the leaf rules
38
57
  // the runtime parses with, so editor tooling needn't mirror them.
@@ -130,6 +149,8 @@ export interface ToolingMacro {
130
149
  parameters?: readonly ParameterDef[];
131
150
  /** Whether it resolves markup: its strings hold markup by default. */
132
151
  interpolate?: boolean;
152
+ /** Whether its first argument names the story variable it binds. */
153
+ storeVar?: boolean;
133
154
  }
134
155
 
135
156
  /**
@@ -210,3 +231,70 @@ export function collectStoryPassageReferences(
210
231
  ): PassageReference[] {
211
232
  return referencesOf(passagePieces(source, macros));
212
233
  }
234
+
235
+ /**
236
+ * The widgets the story defines, as the runtime reads them: those of
237
+ * StoryInit and of the passages tagged `widget`, with their parameters,
238
+ * whether their body renders `{@children}` (a block widget) and where they
239
+ * are written, in source order. Half-typed definitions are reported without a
240
+ * `closeStart`. The macros are those the markup may use, built-in and
241
+ * user-defined (a `{@children}` in an attribute or label counts).
242
+ */
243
+ export function widgetDefinitions(
244
+ passages: Iterable<MarkupPassage>,
245
+ macros: Iterable<ToolingMacro> = [],
246
+ ): WidgetDefinition[] {
247
+ return readWidgetDefinitions(passages, parameterLookup([...macros]));
248
+ }
249
+
250
+ /** Passages tagged so hold code or styles, not markup. */
251
+ const NOT_MARKUP_TAGS = ['script', 'stylesheet'];
252
+
253
+ /** What reading the variable references of markup depends on. */
254
+ function referenceOptions(macros: Iterable<ToolingMacro>) {
255
+ const all = [...macros];
256
+ return {
257
+ storeVarMacros: new Set(
258
+ all.filter((m) => m.storeVar).map((m) => m.name.toLowerCase()),
259
+ ),
260
+ parametersOf: parameterLookup(all),
261
+ tolerant: true,
262
+ };
263
+ }
264
+
265
+ /**
266
+ * The `$` and `%` variable references that the markup of a passage evaluates,
267
+ * in source order, with the dotted path of fields accessed and where each is
268
+ * written (offsets into `source`, UTF-16): `{$var}` displays, code in
269
+ * expressions, conditions, `{do}` bodies and macro arguments, quoted names
270
+ * bound by input macros, and the markup in labels and HTML attributes. Prose
271
+ * is literal text. Malformed tags are skipped, so it reads half-typed markup.
272
+ * The macros are those the markup may use, built-in and user-defined.
273
+ */
274
+ export function variableReferences(
275
+ source: string,
276
+ macros: Iterable<ToolingMacro> = [],
277
+ ): VariableReference[] {
278
+ return collectVariableReferences(source, referenceOptions(macros));
279
+ }
280
+
281
+ /**
282
+ * The variable references of the passages' markup that are not valid against
283
+ * the declarations, as the story start checks them: a variable (or, when
284
+ * `transients` is given, a transient) that is not declared, and a field of a
285
+ * primitive that it has no member of. Built on `variableReferences`:
286
+ * tolerant of half-typed markup, and it evaluates no project code.
287
+ */
288
+ export function validateVariableReferences(
289
+ passages: Iterable<MarkupPassage>,
290
+ declarations: VariableDeclarations,
291
+ macros: Iterable<ToolingMacro> = [],
292
+ ): VariableDiagnostic[] {
293
+ return checkVariableReferences(
294
+ [...passages].filter(
295
+ (p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t)),
296
+ ),
297
+ declarations,
298
+ referenceOptions(macros),
299
+ );
300
+ }