@rohal12/spindle 0.62.1 → 0.62.2

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.
@@ -3682,13 +3682,15 @@ var BLOCK_MACROS = new NameSet([
3682
3682
  * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3683
3683
  */
3684
3684
  var BLOCK_WIDGETS = new NameSet();
3685
+ /** All widgets, including inline ones, override built-in parsing semantics. */
3686
+ var WIDGETS = new NameSet();
3685
3687
  /** Classification owned by defineMacro, independent of explicit registrations. */
3686
3688
  var DEFINED_BLOCK_MACROS = new NameSet();
3687
3689
  /** Macros whose body is JavaScript source, kept verbatim. */
3688
3690
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3689
3691
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
3690
- function isRawMacro(name) {
3691
- return RAW_BODY_MACROS.has(name);
3692
+ function isRawMacro(name, widget = WIDGETS.has(name)) {
3693
+ return RAW_BODY_MACROS.has(name.toLowerCase()) && !widget;
3692
3694
  }
3693
3695
  /** Whether a macro takes a body closed by `{/name}`. */
3694
3696
  function isBlockMacro(name) {
@@ -3747,7 +3749,8 @@ function astNode({ token, body }) {
3747
3749
  };
3748
3750
  if (!body) return withSelectors$1(node, token);
3749
3751
  const children = buildAst(body.children);
3750
- if (!BRANCHING.has(name) && body.branches.length === 0) {
3752
+ const branching = BRANCHING.has(name) && !WIDGETS.has(name);
3753
+ if (!branching && body.branches.length === 0) {
3751
3754
  node.children = children;
3752
3755
  return withSelectors$1(node, token);
3753
3756
  }
@@ -3755,9 +3758,9 @@ function astNode({ token, body }) {
3755
3758
  rawArgs: tag.rawArgs,
3756
3759
  children: branchChildren
3757
3760
  }, tag);
3758
- if (!BRANCHING.has(name)) node.children = children;
3759
- node.branches = [...BRANCHING.has(name) ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
3760
- return BRANCHING.has(name) ? node : withSelectors$1(node, token);
3761
+ if (!branching) node.children = children;
3762
+ node.branches = [...branching ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
3763
+ return branching ? node : withSelectors$1(node, token);
3761
3764
  }
3762
3765
  }
3763
3766
  }
@@ -3777,6 +3780,25 @@ function lineColumn(text, offset) {
3777
3780
  column: offset - lineStart + 1
3778
3781
  };
3779
3782
  }
3783
+ /** Index one source once; offsets and columns count UTF-16 code units. */
3784
+ function sourcePositions(text) {
3785
+ const starts = [0];
3786
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
3787
+ return (offset) => {
3788
+ let low = 0;
3789
+ let high = starts.length;
3790
+ while (low < high) {
3791
+ const mid = low + high >>> 1;
3792
+ if (starts[mid] <= offset) low = mid + 1;
3793
+ else high = mid;
3794
+ }
3795
+ const line = Math.max(1, low);
3796
+ return {
3797
+ line,
3798
+ column: offset - starts[line - 1] + 1
3799
+ };
3800
+ };
3801
+ }
3780
3802
  //#endregion
3781
3803
  //#region src/markup/pair.ts
3782
3804
  /**
@@ -3828,9 +3850,11 @@ function pairMarkup(tokens, options = {}) {
3828
3850
  };
3829
3851
  const errors = [];
3830
3852
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
3853
+ let position;
3831
3854
  const where = (offset) => {
3832
3855
  if (options.source === void 0) return `offset ${offset}`;
3833
- const { line, column } = lineColumn(options.source, offset);
3856
+ position ?? (position = sourcePositions(options.source));
3857
+ const { line, column } = position(offset);
3834
3858
  return `line ${line}, column ${column}`;
3835
3859
  };
3836
3860
  const report = (code, token, message, noticedAt, data) => {
@@ -10243,7 +10267,8 @@ function analyzeMarkup(source, options = {}) {
10243
10267
  };
10244
10268
  const inDamage = (start) => errors.some((e, i) => start >= damage[i] && start <= e.offset);
10245
10269
  const noticed = errors.map((e, i) => [damage[i] + .5, e]);
10246
- for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(source, error)]);
10270
+ const position = paired.errors.length ? sourcePositions(source) : void 0;
10271
+ for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(position, error)]);
10247
10272
  noticed.sort((a, b) => a[0] - b[0]);
10248
10273
  return {
10249
10274
  tokens,
@@ -10262,8 +10287,8 @@ function parseMarkup(source, options = {}) {
10262
10287
  return buildAst(nodes);
10263
10288
  }
10264
10289
  /** A pairing problem as the MarkupError it is for `source`. */
10265
- function pairingError(source, error) {
10266
- const { line, column } = lineColumn(source, error.start);
10290
+ function pairingError(position, error) {
10291
+ const { line, column } = position(error.start);
10267
10292
  return new MarkupError(error.message, error.start, line, column, error.code, error.end, error.data);
10268
10293
  }
10269
10294
  /**
@@ -10310,6 +10335,7 @@ function scanMarkupTolerant(source, options = {}) {
10310
10335
  const tokens = [];
10311
10336
  const errors = [];
10312
10337
  const damage = [];
10338
+ let position;
10313
10339
  const lastBrace = source.lastIndexOf("}");
10314
10340
  const { closeBrace } = {
10315
10341
  ...defaultHooks,
@@ -10340,7 +10366,8 @@ function scanMarkupTolerant(source, options = {}) {
10340
10366
  break;
10341
10367
  }
10342
10368
  const at = base + result.offset;
10343
- const { line, column } = lineColumn(source, at);
10369
+ position ?? (position = sourcePositions(source));
10370
+ const { line, column } = position(at);
10344
10371
  errors.push(new MarkupError(result.reason, at, line, column, result.code, base + result.end));
10345
10372
  let cut = result.offset;
10346
10373
  let prefix = attempt(rest.slice(0, cut), base);
@@ -11219,14 +11246,16 @@ function* codeAndText(src, tokens, parametersOf) {
11219
11246
  * `src`. In source order, a nested piece after the text it is in.
11220
11247
  */
11221
11248
  function* passagePiecesOf(src, tokens, parametersOf, options = {}) {
11222
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0);
11249
+ let position;
11250
+ const locate = (offset) => (position ?? (position = sourcePositions(src)))(offset);
11251
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate);
11223
11252
  }
11224
11253
  /**
11225
11254
  * The pieces of `tokens`, the tokens of `src`, which is the text described by
11226
11255
  * `where` (none for `root`, the markup of the whole passage), and whose
11227
11256
  * offsets `toRoot` turns into offsets in `root`.
11228
11257
  */
11229
- function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11258
+ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate) {
11230
11259
  for (const flat of codeAndText(src, tokens, parametersOf)) {
11231
11260
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
11232
11261
  if (flat.kind !== "text" || !flat.text.includes("{")) {
@@ -11236,17 +11265,20 @@ function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11236
11265
  const toText = (i) => toRoot(pieceOffset(flat, i));
11237
11266
  const inner = analyzeMarkup(flat.text, {
11238
11267
  text: true,
11239
- hooks: options.isBlock && { isBlock: options.isBlock }
11268
+ hooks: {
11269
+ ...options.isBlock && { isBlock: options.isBlock },
11270
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11271
+ }
11240
11272
  });
11241
11273
  yield {
11242
11274
  ...piece,
11243
11275
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
11244
11276
  errors: inner.errors.map((e) => {
11245
- const { line, column } = lineColumn(root, toText(e.offset));
11277
+ const { line, column } = locate(toText(e.offset));
11246
11278
  return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
11247
11279
  })
11248
11280
  };
11249
- yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where);
11281
+ yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate);
11250
11282
  }
11251
11283
  }
11252
11284
  /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
@@ -11774,14 +11806,23 @@ function distance(a, b) {
11774
11806
  }
11775
11807
  /** The known name closest to `name`, if one is close. */
11776
11808
  function closestName(name, names) {
11809
+ if (name.length > 256) return void 0;
11777
11810
  const lower = name.toLowerCase();
11778
11811
  let best;
11779
11812
  let bestDistance = Math.max(2, Math.floor(lower.length / 3)) + 1;
11813
+ let budget = 1e5;
11814
+ let candidates = 1e3;
11780
11815
  for (const candidate of names) {
11816
+ if (--candidates < 0) break;
11817
+ if (candidate.length > 256) continue;
11818
+ if (Math.abs(candidate.length - lower.length) >= bestDistance) continue;
11819
+ budget -= lower.length * candidate.length;
11820
+ if (budget < 0) break;
11781
11821
  const d = distance(lower, candidate.toLowerCase());
11782
11822
  if (d < bestDistance) {
11783
11823
  best = candidate;
11784
11824
  bestDistance = d;
11825
+ if (d === 0) break;
11785
11826
  }
11786
11827
  }
11787
11828
  return best;
@@ -11806,12 +11847,19 @@ function widgetName(rawArgs) {
11806
11847
  */
11807
11848
  function validateMarkup(passages, options) {
11808
11849
  const diagnostics = [];
11850
+ const positions = /* @__PURE__ */ new Map();
11809
11851
  const hooks = {
11810
11852
  ...options.isBlockMacro && { isBlock: options.isBlockMacro },
11811
- ...options.branchParents && { branchParents: options.branchParents }
11853
+ ...options.branchParents && { branchParents: options.branchParents },
11854
+ isRaw: (name) => isRawMacro(name, options.parametersOf ? options.parametersOf.widget?.(name) !== void 0 : void 0)
11812
11855
  };
11813
11856
  const report = (passage, start, end, code, message, data) => {
11814
- const { line, column } = lineColumn(passage.content, start);
11857
+ let position = positions.get(passage);
11858
+ if (!position) {
11859
+ position = sourcePositions(passage.content);
11860
+ positions.set(passage, position);
11861
+ }
11862
+ const { line, column } = position(start);
11815
11863
  const d = {
11816
11864
  passage: passage.name,
11817
11865
  line,
@@ -11857,7 +11905,7 @@ function validateMarkup(passages, options) {
11857
11905
  continue;
11858
11906
  }
11859
11907
  try {
11860
- const tokens = tokenizeMarkup(passage.content);
11908
+ const tokens = tokenizeMarkup(passage.content, { hooks });
11861
11909
  addWidgets(tokens);
11862
11910
  if (!reported) continue;
11863
11911
  parseMarkup(passage.content, { hooks });
@@ -12356,10 +12404,14 @@ var Reader = class {
12356
12404
  * The tokens of markup, or none if it is malformed (validateMarkup reports
12357
12405
  * that, with its position); in tolerant mode, those of the well-formed parts.
12358
12406
  */
12359
- function tokensOf(text, textMode, { tolerant } = {}) {
12360
- if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
12407
+ function tokensOf(text, textMode, { tolerant, parametersOf } = {}) {
12408
+ const options = {
12409
+ text: textMode,
12410
+ hooks: parametersOf && { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) }
12411
+ };
12412
+ if (tolerant) return tokenizeMarkupTolerant(text, options).tokens;
12361
12413
  try {
12362
- return tokenizeMarkup(text, { text: textMode });
12414
+ return tokenizeMarkup(text, options);
12363
12415
  } catch (err) {
12364
12416
  if (err instanceof MarkupError) return [];
12365
12417
  throw err;
@@ -12895,6 +12947,8 @@ var Bindings = class {
12895
12947
  this.byOpen = /* @__PURE__ */ new Map();
12896
12948
  this.byClose = /* @__PURE__ */ new Map();
12897
12949
  this.functions = /* @__PURE__ */ new Map();
12950
+ this.functionStarts = /* @__PURE__ */ new Map();
12951
+ this.facts = /* @__PURE__ */ new Map();
12898
12952
  this.top = {
12899
12953
  start: -1,
12900
12954
  end: Infinity
@@ -12910,6 +12964,18 @@ var Bindings = class {
12910
12964
  * (given another, or one of its `properties` set) where the use can follow.
12911
12965
  */
12912
12966
  objectOf(name, at, properties) {
12967
+ let names = this.facts.get(properties);
12968
+ if (!names) this.facts.set(properties, names = /* @__PURE__ */ new Map());
12969
+ let bindings = names.get(name);
12970
+ if (!bindings) {
12971
+ bindings = this.readBindings(name, properties);
12972
+ names.set(name, bindings);
12973
+ }
12974
+ const found = this.innermostVisible(bindings, at);
12975
+ return found.length === 1 ? found[0].object : void 0;
12976
+ }
12977
+ /** Declaration and write facts are immutable for this source and property set. */
12978
+ readBindings(name, properties) {
12913
12979
  const { code } = this;
12914
12980
  const escaped = name.replace(/\$/g, "\\$");
12915
12981
  const bindings = [];
@@ -12919,8 +12985,7 @@ var Bindings = class {
12919
12985
  }
12920
12986
  const declarations = bindings.filter((b) => !b.write);
12921
12987
  for (const b of bindings) if (b.write) b.scope = this.innermostVisible(declarations, b.at)[0]?.scope ?? this.top;
12922
- const found = this.innermostVisible(bindings, at);
12923
- return found.length === 1 ? found[0].object : void 0;
12988
+ return bindings;
12924
12989
  }
12925
12990
  /**
12926
12991
  * Of the `bindings` the use at `at` can see, those in the innermost scope:
@@ -12997,7 +13062,13 @@ var Bindings = class {
12997
13062
  }
12998
13063
  /** The start of the function that has `index` in its body, or -1. */
12999
13064
  functionStart(index) {
13000
- for (let g = this.innermost(index, "{"); g; g = g.parent) if (g.kind === "{" && this.isFunctionBody(g)) return g.open;
13065
+ const known = this.functionStarts.get(index);
13066
+ if (known !== void 0) return known;
13067
+ for (let g = this.innermost(index, "{"); g; g = g.parent) if (g.kind === "{" && this.isFunctionBody(g)) {
13068
+ this.functionStarts.set(index, g.open);
13069
+ return g.open;
13070
+ }
13071
+ this.functionStarts.set(index, -1);
13001
13072
  return -1;
13002
13073
  }
13003
13074
  scopeOf(group) {
@@ -13564,6 +13635,7 @@ function macroOf(config) {
13564
13635
  function discoverMacros(source) {
13565
13636
  const { code, regexes } = codeOnly(source);
13566
13637
  const found = [];
13638
+ const configs = /* @__PURE__ */ new Map();
13567
13639
  let bindings;
13568
13640
  for (const call of code.matchAll(CALL_RE)) {
13569
13641
  let at = call.index + call[0].length;
@@ -13575,12 +13647,15 @@ function discoverMacros(source) {
13575
13647
  if (object === void 0) continue;
13576
13648
  at = object;
13577
13649
  }
13578
- const reader = new ConfigReader(source, {
13579
- goal: "statements",
13580
- regexes
13581
- });
13582
- reader.i = at;
13583
- const config = reader.datum();
13650
+ if (!configs.has(at)) {
13651
+ const reader = new ConfigReader(source, {
13652
+ goal: "statements",
13653
+ regexes
13654
+ });
13655
+ reader.i = at;
13656
+ configs.set(at, reader.datum());
13657
+ }
13658
+ const config = configs.get(at);
13584
13659
  const macro = config && macroOf(config);
13585
13660
  if (macro) found.push(macro);
13586
13661
  }
@@ -24447,18 +24522,8 @@ function markdownOptions(options) {
24447
24522
  //#region src/format/source-lines.ts
24448
24523
  /** Index a source once; locate zero-based lines without rescanning its prefixes. */
24449
24524
  function sourceLines(source) {
24450
- const starts = [0];
24451
- for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
24452
- return (offset) => {
24453
- let low = 0;
24454
- let high = starts.length;
24455
- while (low < high) {
24456
- const middle = low + high >>> 1;
24457
- if (starts[middle] <= offset) low = middle + 1;
24458
- else high = middle;
24459
- }
24460
- return Math.max(0, low - 1);
24461
- };
24525
+ const position = sourcePositions(source);
24526
+ return (offset) => position(offset).line - 1;
24462
24527
  }
24463
24528
  //#endregion
24464
24529
  //#region src/format/markdown-lines.ts
@@ -25361,7 +25426,9 @@ function blockLookup(macros) {
25361
25426
  * The macros are those the markup may use, built-in and user-defined.
25362
25427
  */
25363
25428
  function passagePieces(source, macros = []) {
25364
- return passagePiecesOfTokens(source, macros, tokenizeMarkupTolerant(source).tokens);
25429
+ const all = [...macros];
25430
+ const parametersOf = parameterLookup(all);
25431
+ return passagePiecesOfTokens(source, all, tokenizeMarkupTolerant(source, { hooks: { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) } }).tokens);
25365
25432
  }
25366
25433
  /**
25367
25434
  * `passagePieces` for a caller that has the tokens of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.1",
3
+ "version": "0.62.2",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -28,12 +28,7 @@
28
28
  */
29
29
  import type { HtmlToken, Token } from './markup/tokens';
30
30
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
31
- import {
32
- analyzeMarkup,
33
- lineColumn,
34
- MarkupError,
35
- mapOffsets,
36
- } from './markup/parse';
31
+ import { analyzeMarkup, MarkupError, mapOffsets } from './markup/parse';
37
32
  import {
38
33
  CodeSyntaxError,
39
34
  parseCode,
@@ -53,6 +48,8 @@ import { subMacroParameters } from './components/macros/option-utils';
53
48
  import { splitArgSpans } from './components/macros/arg-utils';
54
49
  import { NameMap } from './utils/macro-names';
55
50
  import { hasOwn } from './utils/namespace';
51
+ import { isRawMacro } from './markup/ast';
52
+ import { sourcePositions } from './markup/line-column';
56
53
 
57
54
  /** While a pass runs: the code it parsed so far, by goal and source. */
58
55
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -471,7 +468,19 @@ export function* passagePiecesOf(
471
468
  parametersOf: ParametersOf,
472
469
  options: PieceOptions = {},
473
470
  ): Generator<Piece> {
474
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, undefined);
471
+ let position: ReturnType<typeof sourcePositions> | undefined;
472
+ const locate = (offset: number) =>
473
+ (position ??= sourcePositions(src))(offset);
474
+ yield* expand(
475
+ src,
476
+ src,
477
+ tokens,
478
+ parametersOf,
479
+ options,
480
+ (i) => i,
481
+ undefined,
482
+ locate,
483
+ );
475
484
  }
476
485
 
477
486
  /**
@@ -487,6 +496,7 @@ function* expand(
487
496
  options: PieceOptions,
488
497
  toRoot: (offset: number) => number,
489
498
  where: string | undefined,
499
+ locate: ReturnType<typeof sourcePositions>,
490
500
  ): Generator<Piece> {
491
501
  for (const flat of codeAndText(src, tokens, parametersOf)) {
492
502
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -498,13 +508,17 @@ function* expand(
498
508
  const toText = (i: number) => toRoot(pieceOffset(flat, i));
499
509
  const inner = analyzeMarkup(flat.text, {
500
510
  text: true,
501
- hooks: options.isBlock && { isBlock: options.isBlock },
511
+ hooks: {
512
+ ...(options.isBlock && { isBlock: options.isBlock }),
513
+ isRaw: (name) =>
514
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
515
+ },
502
516
  });
503
517
  yield {
504
518
  ...(piece as TextPiece),
505
519
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
506
520
  errors: inner.errors.map((e) => {
507
- const { line, column } = lineColumn(root, toText(e.offset));
521
+ const { line, column } = locate(toText(e.offset));
508
522
  return new MarkupError(
509
523
  e.reason,
510
524
  toText(e.offset),
@@ -524,6 +538,7 @@ function* expand(
524
538
  options,
525
539
  toText,
526
540
  flat.where,
541
+ locate,
527
542
  );
528
543
  }
529
544
  }
@@ -1,17 +1,7 @@
1
+ import { sourcePositions } from '../markup/line-column';
2
+
1
3
  /** Index a source once; locate zero-based lines without rescanning its prefixes. */
2
4
  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
- };
5
+ const position = sourcePositions(source);
6
+ return (offset) => position(offset).line - 1;
17
7
  }