@rohal12/spindle 0.59.23 → 0.59.26

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) {
@@ -34,12 +46,7 @@ function tokensOf(text: string, textMode: boolean): Token[] {
34
46
  }
35
47
 
36
48
  export type VarType =
37
- | 'number'
38
- | 'string'
39
- | 'boolean'
40
- | 'array'
41
- | 'object'
42
- | 'null';
49
+ 'number' | 'string' | 'boolean' | 'array' | 'object' | 'null';
43
50
 
44
51
  export interface FieldSchema {
45
52
  type: VarType;
@@ -55,8 +62,8 @@ function declarationRegex(sigil: string): RegExp {
55
62
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
56
63
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
57
64
  }
58
- /** A `$name` reference with its dot path, at a `$` the lexer found. */
59
- const VAR_PATH_RE = /\$(\w+(?:\.\w+)*)/y;
65
+ /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
66
+ const VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
60
67
  /** Quoted first argument of an input macro naming a story variable. */
61
68
  const QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
62
69
 
@@ -287,29 +294,86 @@ export function parseStoryVariables(
287
294
  return schema;
288
295
  }
289
296
 
297
+ /** A reference to a story (`$`) or transient (`%`) variable in markup. */
298
+ export interface VariableReference {
299
+ sigil: '$' | '%';
300
+ /** The variable, without the sigil. */
301
+ name: string;
302
+ /** The fields accessed with dots (`$a.b.c`: `['b', 'c']`). */
303
+ path: string[];
304
+ /** Where `$a.b.c` is written in the markup, as `[start, end)` UTF-16 offsets. */
305
+ start: number;
306
+ end: number;
307
+ }
308
+
309
+ /** What a check of a variable reference found wrong with it. */
310
+ export type VariableDiagnosticCode =
311
+ | 'undeclared-variable'
312
+ | 'undeclared-transient'
313
+ | 'reserved-name'
314
+ | 'primitive-field';
315
+
316
+ /** A variable reference that is not valid against the declarations. */
317
+ export interface VariableDiagnostic {
318
+ passage: string;
319
+ code: VariableDiagnosticCode;
320
+ /** The variable, without the sigil. */
321
+ name: string;
322
+ /** The fields accessed with dots. */
323
+ path?: string[];
324
+ /** The reference, as offsets into the passage content. */
325
+ start: number;
326
+ end: number;
327
+ message: string;
328
+ }
329
+
290
330
  /**
291
- * Validate a single variable reference path (e.g. "player.health") against
292
- * the schema. Returns an error message or null if valid.
331
+ * What is declared: the schema of each variable, which is absent for one
332
+ * whose initializer is not static (`parseDeclarations`): it is declared, but
333
+ * its fields are not checked.
293
334
  */
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;
335
+ export interface VariableDeclarations {
336
+ variables: ReadonlyMap<string, FieldSchema | undefined>;
337
+ /**
338
+ * The transients (`%`). They are not checked when absent, as the story
339
+ * start does not check them.
340
+ */
341
+ transients?: ReadonlyMap<string, FieldSchema | undefined>;
342
+ }
303
343
 
304
- const rootSchema = schema.get(rootName);
305
- if (!rootSchema) {
306
- return `Undeclared variable: $${ref}`;
344
+ /**
345
+ * Check a reference against the declarations: the error code and message, or
346
+ * null if it is valid. (Unknown fields of objects are valid: classes
347
+ * registered with Story.registerClass() can add members that are not in the
348
+ * defaults.)
349
+ */
350
+ function checkReference(
351
+ ref: VariableReference,
352
+ declared: VariableDeclarations,
353
+ ): { code: VariableDiagnosticCode; message: string } | null {
354
+ const label = (path: readonly string[]) =>
355
+ ref.sigil + [ref.name, ...path].join('.');
356
+ const nameError = variableNameError(ref.name, ref.sigil + ref.name);
357
+ if (nameError) return { code: 'reserved-name', message: nameError };
358
+
359
+ const schema = ref.sigil === '$' ? declared.variables : declared.transients;
360
+ if (!schema) return null;
361
+ if (!schema.has(ref.name)) {
362
+ return ref.sigil === '$'
363
+ ? {
364
+ code: 'undeclared-variable',
365
+ message: `Undeclared variable: ${label(ref.path)}`,
366
+ }
367
+ : {
368
+ code: 'undeclared-transient',
369
+ message: `Undeclared transient: ${label(ref.path)}`,
370
+ };
307
371
  }
308
372
 
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;
373
+ // Walk through the field access path
374
+ let current = schema.get(ref.name);
375
+ for (let i = 0; current && i < ref.path.length; i++) {
376
+ const part = ref.path[i]!;
313
377
 
314
378
  // Arrays have built-in methods/properties (push, find, length, etc.)
315
379
  // so any field access on an array is allowed.
@@ -329,15 +393,12 @@ function validateRef(
329
393
  }
330
394
 
331
395
  if (current.type !== 'object' || !current.fields) {
332
- return `Cannot access field "${part}" on $${parts.slice(0, i).join('.')} (type: ${current.type})`;
396
+ return {
397
+ code: 'primitive-field',
398
+ message: `Cannot access field "${part}" on ${label(ref.path.slice(0, i))} (type: ${current.type})`,
399
+ };
333
400
  }
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;
401
+ current = current.fields.get(part);
341
402
  }
342
403
 
343
404
  return null;
@@ -357,17 +418,49 @@ const BUILTIN_STORE_VAR_MACROS: readonly string[] = [
357
418
  'textbox',
358
419
  ];
359
420
 
360
- type RefCallback = (ref: string) => void;
421
+ /** What reading the variable references of markup depends on. */
422
+ interface ReferenceOptions {
423
+ /** The (lowercase) names of the input macros that bind a variable. */
424
+ storeVarMacros: ReadonlySet<string>;
425
+ parametersOf: ParametersOf;
426
+ /** Read half-typed markup: skip its malformed tags (default: none read). */
427
+ tolerant?: boolean;
428
+ }
429
+
430
+ /** Where index `i` of a text is in the markup being read. */
431
+ type At = (i: number) => number;
432
+
433
+ type Emit = (ref: VariableReference) => void;
361
434
 
362
435
  const NO_STORE_VAR_MACROS: ReadonlySet<string> = new Set();
363
436
 
437
+ /** A reference written at `index` of `code`, with its dot path. */
438
+ function referenceAt(
439
+ code: string,
440
+ index: number,
441
+ at: At,
442
+ ): VariableReference | undefined {
443
+ VAR_PATH_RE.lastIndex = index;
444
+ const match = VAR_PATH_RE.exec(code);
445
+ if (!match) return undefined;
446
+ const [name, ...path] = match[2]!.split('.');
447
+ return {
448
+ sigil: match[1] as '$' | '%',
449
+ name: name!,
450
+ path,
451
+ start: at(index),
452
+ end: at(index + match[0].length),
453
+ };
454
+ }
455
+
364
456
  /**
365
457
  * Scan the value of a code attribute (`onclick`, see isCodeAttribute) for
366
- * the `{$…}` references resolved in it; its other braces are code.
458
+ * the `{$…}` references resolved in it; its other braces are code. `at` is
459
+ * where the value is.
367
460
  */
368
- function scanSigilReferences(value: string, onRef: RefCallback): void {
369
- for (const part of splitSigilTemplate(value)) {
370
- if ('expr' in part) scanCode(part.expr, onRef);
461
+ function scanSigilReferences(value: string, at: At, emit: Emit): void {
462
+ for (const { expr, at: k } of sigilExpressions(value)) {
463
+ scanCode(expr, (i) => at(k + i), emit);
371
464
  }
372
465
  }
373
466
 
@@ -379,11 +472,12 @@ function scanSigilReferences(value: string, onRef: RefCallback): void {
379
472
  */
380
473
  function scanInterpolations(
381
474
  text: string,
382
- onRef: RefCallback,
383
- storeVarMacros: ReadonlySet<string> = NO_STORE_VAR_MACROS,
475
+ at: At,
476
+ emit: Emit,
477
+ options: ReferenceOptions,
384
478
  ): void {
385
479
  if (!text.includes('{')) return;
386
- collectTokenRefs(text, tokensOf(text, true), storeVarMacros, onRef);
480
+ collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
387
481
  }
388
482
 
389
483
  /**
@@ -396,34 +490,36 @@ function scanInterpolations(
396
490
  */
397
491
  function scanCode(
398
492
  code: string,
399
- onRef: RefCallback,
493
+ at: At,
494
+ emit: Emit,
400
495
  goal: JsGoal = 'expression',
401
496
  ): void {
402
497
  const parsed = parseOrError(code, goal);
403
498
  if (parsed instanceof CodeSyntaxError) {
404
- scanCodeLeniently(code, onRef, goal);
499
+ scanCodeLeniently(code, at, emit, goal);
405
500
  return;
406
501
  }
407
502
  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]!);
503
+ if (ref.sigil !== '$' && ref.sigil !== '%') continue;
504
+ const found = referenceAt(code, ref.start, at);
505
+ if (found) emit(found);
411
506
  }
412
507
  }
413
508
 
414
509
  /** `scanCode` for code acorn can't parse: lexed leniently. */
415
510
  function scanCodeLeniently(
416
511
  code: string,
417
- onRef: RefCallback,
512
+ at: At,
513
+ emit: Emit,
418
514
  goal: JsGoal,
419
515
  ): void {
420
516
  lexJs(
421
517
  code,
422
518
  {
423
519
  variable(sigil, _name, index) {
424
- if (sigil !== '$') return;
425
- VAR_PATH_RE.lastIndex = index;
426
- onRef(VAR_PATH_RE.exec(code)![1]!);
520
+ if (sigil !== '$' && sigil !== '%') return;
521
+ const found = referenceAt(code, index, at);
522
+ if (found) emit(found);
427
523
  },
428
524
  // Strings, regex literals and comments hold no references
429
525
  literal() {},
@@ -432,29 +528,6 @@ function scanCodeLeniently(
432
528
  );
433
529
  }
434
530
 
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
531
  /**
459
532
  * Report the references in the arguments of a macro by what its parameters
460
533
  * say each holds (see ParameterDef.holds): code is scanned as code and
@@ -465,55 +538,111 @@ function collectPassageRefs(
465
538
  function scanArgs(
466
539
  token: Extract<Token, { type: 'macro' }>,
467
540
  params: readonly ParameterDef[] | undefined,
468
- onRef: RefCallback,
541
+ at: At,
542
+ emit: Emit,
543
+ options: ReferenceOptions,
469
544
  ): void {
470
545
  if (!token.rawArgs) return;
471
546
  if (params) {
472
- const pieces = [...argPieces(token.rawArgs, 0, params, token.name, '')];
547
+ const pieces = [
548
+ ...argPieces(token.rawArgs, token.argsStart, params, token.name, ''),
549
+ ];
473
550
  if (!pieces.some((piece) => piece.kind === 'argument-error')) {
474
551
  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);
552
+ const pieceAt: At = (i) => at(pieceOffset(piece, i));
553
+ if (piece.kind === 'code') {
554
+ scanCode(piece.code, pieceAt, emit, piece.goal);
555
+ } else if (piece.kind === 'text') {
556
+ scanInterpolations(piece.text, pieceAt, emit, {
557
+ ...options,
558
+ storeVarMacros: NO_STORE_VAR_MACROS,
559
+ });
560
+ }
477
561
  }
478
562
  return;
479
563
  }
480
564
  }
481
- scanCode(token.rawArgs, onRef);
565
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
482
566
  }
483
567
 
484
568
  /** Report the `$var` references in the tokens of `content`. */
485
569
  function collectTokenRefs(
486
570
  content: string,
487
571
  tokens: Token[],
488
- storeVarMacros: ReadonlySet<string>,
489
- onRef: RefCallback,
490
- parametersOf: ParametersOf = () => undefined,
572
+ at: At,
573
+ emit: Emit,
574
+ options: ReferenceOptions,
491
575
  ): void {
576
+ const { storeVarMacros, parametersOf } = options;
492
577
  for (let t = 0; t < tokens.length; t++) {
493
578
  const token = tokens[t]!;
494
579
  if (token.type === 'variable') {
495
- if (token.scope === 'variable' && token.name) onRef(token.name);
580
+ if (
581
+ (token.scope === 'variable' || token.scope === 'transient') &&
582
+ token.name
583
+ ) {
584
+ const [name, ...path] = token.name.split('.');
585
+ emit({
586
+ sigil: token.scope === 'variable' ? '$' : '%',
587
+ name: name!,
588
+ path,
589
+ start: at(token.nameStart - 1),
590
+ end: at(token.nameEnd),
591
+ });
592
+ }
496
593
  } else if (token.type === 'link') {
497
- scanInterpolations(token.display, onRef);
594
+ scanInterpolations(
595
+ token.display,
596
+ (i) => at(token.displayStart + i),
597
+ emit,
598
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
599
+ );
498
600
  } else if (token.type === 'expression') {
499
- scanCode(token.expression, onRef);
601
+ scanCode(token.expression, (i) => at(token.expressionStart + i), emit);
500
602
  } 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);
603
+ for (const { name, value, at: valueAt } of attributeValues(
604
+ content,
605
+ token,
606
+ )) {
607
+ const valueIn: At = (i) => at(valueAt + i);
608
+ if (isCodeAttribute(name)) scanSigilReferences(value, valueIn, emit);
609
+ else scanInterpolations(value, valueIn, emit, options);
504
610
  }
505
611
  } else if (token.type === 'macro' && !token.isClose) {
506
- scanArgs(token, parametersOf(token.name), onRef);
612
+ scanArgs(token, parametersOf(token.name), at, emit, options);
507
613
  // Selectors (`{.{$cls} button}`) are interpolated when rendered
508
- if (token.className) scanInterpolations(token.className, onRef);
509
- if (token.id) scanInterpolations(token.id, onRef);
614
+ if (
615
+ token.selectorsStart !== undefined &&
616
+ token.selectorsEnd !== undefined
617
+ ) {
618
+ const from = token.selectorsStart;
619
+ scanInterpolations(
620
+ content.slice(from, token.selectorsEnd),
621
+ (i) => at(from + i),
622
+ emit,
623
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
624
+ );
625
+ }
510
626
 
511
627
  if (storeVarMacros.has(token.name.toLowerCase())) {
628
+ const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
512
629
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? '';
513
630
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
514
- if (quoted) onRef(quoted[1]!);
631
+ if (quoted) {
632
+ const [name, ...path] = quoted[1]!.split('.');
633
+ const start = token.argsStart + lead + 1;
634
+ emit({
635
+ sigil: '$',
636
+ name: name!,
637
+ path,
638
+ start: at(start),
639
+ end: at(start + 1 + quoted[1]!.length),
640
+ });
641
+ }
515
642
  // Unquoted, the variable is an argument of no declared role
516
- else if (!/^["'`]/.test(first)) scanCode(first, onRef);
643
+ else if (!/^["'`]/.test(first)) {
644
+ scanCode(first, (i) => at(token.argsStart + lead + i), emit);
645
+ }
517
646
  }
518
647
 
519
648
  if (token.name.toLowerCase() === 'do') {
@@ -533,7 +662,7 @@ function collectTokenRefs(
533
662
  }
534
663
  if (close < tokens.length) {
535
664
  const body = content.slice(token.end, tokens[close]!.start);
536
- scanCode(body, onRef, 'statements');
665
+ scanCode(body, (i) => at(token.end + i), emit, 'statements');
537
666
  t = close;
538
667
  }
539
668
  }
@@ -541,6 +670,60 @@ function collectTokenRefs(
541
670
  }
542
671
  }
543
672
 
673
+ /**
674
+ * The `$` and `%` variable references a passage evaluates at runtime, in
675
+ * source order: `{$var}` displays, `{$expr}` expressions, macro arguments and
676
+ * `{do}` bodies (as code), quoted variable names bound by input macros, and
677
+ * `{$…}` interpolations in labels and HTML attributes. Prose is literal text
678
+ * and not scanned.
679
+ */
680
+ export function collectVariableReferences(
681
+ content: string,
682
+ options: ReferenceOptions,
683
+ ): VariableReference[] {
684
+ const found: VariableReference[] = [];
685
+ withParseCache(() =>
686
+ collectTokenRefs(
687
+ content,
688
+ tokensOf(content, false, options),
689
+ (i) => i,
690
+ (ref) => found.push(ref),
691
+ options,
692
+ ),
693
+ );
694
+ return found;
695
+ }
696
+
697
+ /**
698
+ * The invalid variable references of the passages, against what is declared,
699
+ * with their positions. The passages that hold no markup (the declarations
700
+ * themselves, SaveTitle) are skipped.
701
+ */
702
+ export function checkVariableReferences(
703
+ passages: Iterable<{ name: string; content: string }>,
704
+ declared: VariableDeclarations,
705
+ options: ReferenceOptions,
706
+ ): VariableDiagnostic[] {
707
+ const diagnostics: VariableDiagnostic[] = [];
708
+ for (const passage of passages) {
709
+ if (NOT_MARKUP.has(passage.name)) continue;
710
+ for (const ref of collectVariableReferences(passage.content, options)) {
711
+ const error = checkReference(ref, declared);
712
+ if (!error) continue;
713
+ diagnostics.push({
714
+ passage: passage.name,
715
+ code: error.code,
716
+ name: ref.name,
717
+ ...(ref.path.length > 0 ? { path: ref.path } : {}),
718
+ start: ref.start,
719
+ end: ref.end,
720
+ message: error.message,
721
+ });
722
+ }
723
+ }
724
+ return diagnostics;
725
+ }
726
+
544
727
  /**
545
728
  * Check the `$var` references of all passages against the schema, at story
546
729
  * start. Returns the error messages (empty = valid). (The syntax of their
@@ -555,29 +738,16 @@ export function validatePassages(
555
738
  storeVarMacros: Iterable<string> = BUILTIN_STORE_VAR_MACROS,
556
739
  parametersOf: ParametersOf = getMacroParameters,
557
740
  ): 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
- },
741
+ return checkVariableReferences(
742
+ passages.values(),
743
+ { variables: schema },
744
+ {
745
+ storeVarMacros: new Set(
746
+ Array.from(storeVarMacros, (m) => m.toLowerCase()),
747
+ ),
576
748
  parametersOf,
577
- );
578
- }
579
-
580
- return errors;
749
+ },
750
+ ).map((d) => `Passage "${d.passage}": ${d.message}`);
581
751
  }
582
752
 
583
753
  /**
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
+ }