@rohal12/spindle 0.64.33 → 0.64.34

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.
@@ -12,11 +12,7 @@ import {
12
12
  useMemo,
13
13
  } from 'preact/hooks';
14
14
  import { useInterpolate } from './hooks/use-interpolate';
15
- import {
16
- ItemEditContext,
17
- runAsControlEdit,
18
- runAsItemEdit,
19
- } from './utils/control-edits';
15
+ import { ItemEditContext, runAsItemEdit } from './utils/control-edits';
20
16
  import { useMergedLocals } from './hooks/use-merged-locals';
21
17
  import { useRenderOptions } from './hooks/use-render-options';
22
18
  import {
@@ -25,10 +21,10 @@ import {
25
21
  renderInlineNodes,
26
22
  } from './markup/render';
27
23
  import type { ASTNode } from './markup/ast';
28
- import { executeMutation, mutateState, readState } from './execute-mutation';
24
+ import { executeMutation, readState } from './execute-mutation';
29
25
  import { evaluateDisplay } from './expression';
30
26
  import { useStoryFields } from './hooks/use-story-fields';
31
- import { getByPath, setByPath } from './utils/object-path';
27
+ import { getByPath } from './utils/object-path';
32
28
  import { useAction } from './hooks/use-action';
33
29
  import type { UseActionOptions } from './hooks/use-action';
34
30
  import { collectText } from './utils/extract-text';
@@ -47,7 +43,7 @@ import {
47
43
  displayOnlyError,
48
44
  } from './display-only';
49
45
  import { NameSet } from './utils/macro-names';
50
- import { notifyVariableWrite } from './utils/variable-writes';
46
+ import { setControlValue } from './utils/control-bindings';
51
47
  import {
52
48
  checkParameterTypes,
53
49
  registerMacro,
@@ -254,19 +250,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
254
250
  ctx.getValue = () => getByPath(readState().variables, segments);
255
251
  ctx.setValue = displayOnly
256
252
  ? refuse
257
- : (value: unknown) => {
258
- notifyVariableWrite(segments);
259
- // The commit mutation code uses, which keeps the references among
260
- // variables: a write to a draft copies only the path written, and
261
- // other variables sharing the object would keep the old one.
262
- runAsControlEdit(segments, () => {
263
- mutateState((work, adopt) => {
264
- setByPath(work.variables, segments, adopt(value), {
265
- createMissing: true,
266
- });
267
- });
268
- });
269
- };
253
+ : (value: unknown) => setControlValue(segments, value);
270
254
  }
271
255
 
272
256
  try {
@@ -119,6 +119,10 @@ export class Bindings {
119
119
  private readonly byClose = new Map<number, Group>();
120
120
  private readonly functions = new Map<Group, boolean>();
121
121
  private readonly functionStarts = new Map<number, number>();
122
+ private readonly listKeywords = new Map<
123
+ number,
124
+ { floor: number; word: { text: string; start: number } | undefined }
125
+ >();
122
126
  private readonly facts = new Map<
123
127
  ReadonlySet<string>,
124
128
  Map<string, Binding[]>
@@ -508,9 +512,19 @@ export class Bindings {
508
512
  ): { text: string; start: number } | undefined {
509
513
  const { code } = this;
510
514
  const floor = this.innermost(comma)?.open ?? -1;
511
- for (let i = comma - 1; i > floor; i--) {
515
+ const visited: number[] = [];
516
+ let result: { text: string; start: number } | undefined;
517
+ for (let i = comma; i > floor; i--) {
512
518
  const c = code.charAt(i);
513
- if (c === ';') return undefined;
519
+ if (c === ';') break;
520
+ if (c === ',') {
521
+ const cached = this.listKeywords.get(i);
522
+ if (cached?.floor === floor) {
523
+ result = cached.word;
524
+ break;
525
+ }
526
+ visited.push(i);
527
+ }
514
528
  const group = CLOSERS[c] ? this.byClose.get(i) : undefined;
515
529
  if (group) i = group.open;
516
530
  else if (isWordChar(c)) {
@@ -519,12 +533,17 @@ export class Bindings {
519
533
  DECLARATIONS.has(word.text) &&
520
534
  code.charAt(word.start - 1) !== '.'
521
535
  ) {
522
- return word;
536
+ result = word;
537
+ break;
523
538
  }
524
539
  i = word.start;
525
540
  }
526
541
  }
527
- return undefined;
542
+ // Cache every traversed prefix, including misses, so lookup order does
543
+ // not matter. Retain the bracket floor for tolerant recovery contexts.
544
+ for (const at of visited)
545
+ this.listKeywords.set(at, { floor, word: result });
546
+ return result;
528
547
  }
529
548
 
530
549
  private nameEnd(at: number): number {
package/src/js-lexer.ts CHANGED
@@ -552,6 +552,46 @@ export interface ParsedCode {
552
552
  strings: string[];
553
553
  }
554
554
 
555
+ /** A binding write (empty path), or a member write, with the entire target span. */
556
+ export interface CodeMutation extends Span {
557
+ /** Null for an indirect target; null path segments are computed keys. */
558
+ target: { sigil: Sigil; name: string; path: (string | null)[] } | null;
559
+ /** Compound assignments and updates read the target as well as writing it. */
560
+ read: boolean;
561
+ }
562
+
563
+ /** A reason declaration-time shapes alone cannot justify a missing-member advisory. */
564
+ export interface CodeShapeUncertainty extends Span {
565
+ reason:
566
+ | 'computed-write'
567
+ | 'indirect-write'
568
+ | 'prototype-write'
569
+ | 'call'
570
+ | 'escape'
571
+ | 'dynamic-scope';
572
+ }
573
+
574
+ export interface CodeEffects {
575
+ mutations: CodeMutation[];
576
+ uncertain: CodeShapeUncertainty[];
577
+ }
578
+
579
+ /**
580
+ * Conservative shape effects, using the same grammar and target roles as
581
+ * parseCode. Includes nested functions and unreachable branches; does not
582
+ * attempt alias, call, control-flow or execution-order analysis.
583
+ */
584
+ export function analyzeCodeEffects(
585
+ src: string,
586
+ goal: JsGoal = 'expression',
587
+ ): CodeEffects {
588
+ const effects: CodeEffects = { mutations: [], uncertain: [] };
589
+ parseWithAst(src, goal, effects);
590
+ effects.mutations.sort((a, b) => a.start - b.start);
591
+ effects.uncertain.sort((a, b) => a.start - b.start);
592
+ return effects;
593
+ }
594
+
555
595
  /**
556
596
  * Parse `src` as `goal`, and find its variable references and string text.
557
597
  * Throws a `CodeSyntaxError` for code that is not well-formed, and for a
@@ -568,10 +608,11 @@ export function parseCode(
568
608
  function parseWithAst(
569
609
  src: string,
570
610
  goal: JsGoal,
611
+ effects?: CodeEffects,
571
612
  ): { out: ParsedCode; ast: AnyNode } {
572
613
  const ast = parseAst(src, goal);
573
614
  const out: ParsedCode = { refs: [], strings: [] };
574
- walk(ast, src, out, false, false);
615
+ walk(ast, src, out, false, false, 'read', effects);
575
616
  out.refs.sort((a, b) => a.start - b.start);
576
617
  return { out, ast };
577
618
  }
@@ -718,6 +759,28 @@ function propertyName(node: unknown, src: string): void {
718
759
  }
719
760
  }
720
761
 
762
+ /** Keep static member keys decoded; an arbitrary computed key stays unknown. */
763
+ function mutationTarget(
764
+ node: AnyNode,
765
+ src: string,
766
+ ): { root: [Sigil, string] | null; path: (string | null)[] } {
767
+ const path: (string | null)[] = [];
768
+ while (node.type === 'MemberExpression') {
769
+ const property = node.property as AnyNode;
770
+ path.push(
771
+ !node.computed && property.type === 'Identifier'
772
+ ? (property.name as string)
773
+ : property.type === 'Literal' &&
774
+ ['string', 'number'].includes(typeof property.value)
775
+ ? String(property.value)
776
+ : null,
777
+ );
778
+ node = node.object as AnyNode;
779
+ }
780
+ const sigil = node.type === 'Identifier' ? sigilOf(node, src) : null;
781
+ return { root: sigil, path: path.reverse() };
782
+ }
783
+
721
784
  /**
722
785
  * Collect the references and string text under `node`. `binding`: the
723
786
  * identifiers here are declared (a `let`, a parameter), where a sigil
@@ -730,13 +793,14 @@ function walk(
730
793
  binding: boolean,
731
794
  shorthand: boolean,
732
795
  access: 'read' | 'write' | 'readwrite' = 'read',
796
+ effects?: CodeEffects,
733
797
  ): void {
734
- type Visit = [unknown, boolean, boolean, typeof access];
735
- const pending: Visit[] = [[root, binding, shorthand, access]];
798
+ type Visit = [unknown, boolean, boolean, typeof access, boolean, boolean];
799
+ const pending: Visit[] = [[root, binding, shorthand, access, false, false]];
736
800
  while (pending.length) {
737
- const [node, bind, short, role] = pending.pop()!;
801
+ const [node, bind, short, role, memberObject, escapes] = pending.pop()!;
738
802
  const children: Visit[] = [];
739
- visit(node, bind, short, role, children);
803
+ visit(node, bind, short, role, memberObject, escapes, children);
740
804
  // Reverse only the work stack, retaining reference/string and error order.
741
805
  for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]!);
742
806
  }
@@ -746,10 +810,13 @@ function walk(
746
810
  binding: boolean,
747
811
  shorthand: boolean,
748
812
  access: Visit[3],
813
+ memberObject: boolean,
814
+ escapes: boolean,
749
815
  children: Visit[],
750
816
  ): void {
751
817
  if (Array.isArray(node)) {
752
- for (const n of node) children.push([n, binding, false, access]);
818
+ for (const n of node)
819
+ children.push([n, binding, false, access, false, escapes]);
753
820
  return;
754
821
  }
755
822
  if (!isNode(node)) return;
@@ -758,13 +825,39 @@ function walk(
758
825
  bind = false,
759
826
  short = false,
760
827
  role: typeof access = 'read',
828
+ member = false,
829
+ escape = escapes,
761
830
  ) => {
762
- children.push([child, bind, short, role]);
831
+ children.push([child, bind, short, role, member, escape]);
763
832
  };
833
+ const uncertain = (reason: CodeShapeUncertainty['reason']) =>
834
+ effects?.uncertain.push({ start: node.start, end: node.end, reason });
835
+ if (effects) {
836
+ if (
837
+ [
838
+ 'CallExpression',
839
+ 'NewExpression',
840
+ 'TaggedTemplateExpression',
841
+ ].includes(node.type)
842
+ )
843
+ uncertain('call');
844
+ if (node.type === 'WithStatement') uncertain('dynamic-scope');
845
+ if (escapes && node.type === 'ThisExpression') uncertain('escape');
846
+ }
764
847
  switch (node.type) {
765
848
  case 'Identifier': {
766
849
  const sigil = sigilOf(node, src);
767
- if (!sigil) return;
850
+ if (!sigil) {
851
+ if (
852
+ effects &&
853
+ escapes &&
854
+ !binding &&
855
+ !memberObject &&
856
+ access === 'read'
857
+ )
858
+ uncertain('escape');
859
+ return;
860
+ }
768
861
  if (binding) {
769
862
  throw new CodeSyntaxError(
770
863
  `"${node.name as string}" is a ${NAMESPACE_NAME[sigil[0]]} variable and can't be declared`,
@@ -781,6 +874,20 @@ function walk(
781
874
  read: access !== 'write',
782
875
  write: access !== 'read',
783
876
  });
877
+ if (effects) {
878
+ if (access !== 'read') {
879
+ effects.mutations.push({
880
+ start: node.start,
881
+ end: node.end,
882
+ target: { sigil: sigil[0], name: sigil[1], path: [] },
883
+ read: access !== 'write',
884
+ });
885
+ } else if (!memberObject) {
886
+ // A bare value may escape into an alias or foreign code. Without
887
+ // data flow, do not claim its declaration fixes its later shape.
888
+ uncertain('escape');
889
+ }
890
+ }
784
891
  return;
785
892
  }
786
893
  case 'Literal':
@@ -791,8 +898,29 @@ function walk(
791
898
  case 'TemplateElement':
792
899
  out.strings.push((node.value as { raw: string }).raw);
793
900
  return;
901
+ case 'ChainExpression':
902
+ // Optional chaining can wrap a delete target. Keep its write role
903
+ // so the member records the mutation and any shape uncertainty.
904
+ sub(node.expression, binding, shorthand, access, memberObject);
905
+ return;
794
906
  case 'MemberExpression':
795
- sub(node.object);
907
+ if (effects && escapes && !memberObject && access === 'read')
908
+ uncertain('escape');
909
+ if (effects && !binding && access !== 'read') {
910
+ const { root, path } = mutationTarget(node, src);
911
+ const target = root ? { sigil: root[0], name: root[1], path } : null;
912
+ effects.mutations.push({
913
+ start: node.start,
914
+ end: node.end,
915
+ target,
916
+ read: access !== 'write',
917
+ });
918
+ if (!target) uncertain('indirect-write');
919
+ if (path.includes(null)) uncertain('computed-write');
920
+ if (path.some((key) => key === 'prototype' || key === '__proto__'))
921
+ uncertain('prototype-write');
922
+ }
923
+ sub(node.object, false, false, 'read', true);
796
924
  if (node.computed) sub(node.property);
797
925
  else propertyName(node.property, src);
798
926
  return;
@@ -803,7 +931,7 @@ function walk(
803
931
  const value = node.value as AnyNode;
804
932
  if (value.type === 'AssignmentPattern') {
805
933
  sub(value.left, binding, true, access);
806
- sub(value.right);
934
+ sub(value.right, false, false, 'read', false, true);
807
935
  } else {
808
936
  sub(value, binding, true, access);
809
937
  }
@@ -815,7 +943,14 @@ function walk(
815
943
  case 'PropertyDefinition':
816
944
  if (node.computed) sub(node.key);
817
945
  else propertyName(node.key, src);
818
- sub(node.value);
946
+ sub(
947
+ node.value,
948
+ false,
949
+ false,
950
+ 'read',
951
+ false,
952
+ node.type === 'PropertyDefinition' || escapes,
953
+ );
819
954
  return;
820
955
  case 'LabeledStatement':
821
956
  sub(node.body);
@@ -827,7 +962,7 @@ function walk(
827
962
  return;
828
963
  case 'VariableDeclarator':
829
964
  sub(node.id, true);
830
- sub(node.init);
965
+ sub(node.init, false, false, 'read', false, true);
831
966
  return;
832
967
  case 'FunctionDeclaration':
833
968
  case 'FunctionExpression':
@@ -853,7 +988,12 @@ function walk(
853
988
  false,
854
989
  node.operator === '=' ? 'write' : 'readwrite',
855
990
  );
856
- sub(node.right);
991
+ sub(node.right, false, false, 'read', false, true);
992
+ return;
993
+ case 'ReturnStatement':
994
+ case 'ThrowStatement':
995
+ case 'YieldExpression':
996
+ sub(node.argument, false, false, 'read', false, true);
857
997
  return;
858
998
  case 'UnaryExpression':
859
999
  sub(
@@ -869,12 +1009,12 @@ function walk(
869
1009
  case 'ForInStatement':
870
1010
  case 'ForOfStatement':
871
1011
  sub(node.left, false, false, 'write');
872
- sub(node.right);
1012
+ sub(node.right, false, false, 'read', false, true);
873
1013
  sub(node.body);
874
1014
  return;
875
1015
  case 'AssignmentPattern':
876
1016
  sub(node.left, binding, false, access);
877
- sub(node.right);
1017
+ sub(node.right, false, false, 'read', false, true);
878
1018
  return;
879
1019
  case 'ObjectPattern':
880
1020
  case 'ArrayPattern':
package/src/tooling.ts CHANGED
@@ -93,11 +93,15 @@ export {
93
93
  lexJs,
94
94
  lexTemplate,
95
95
  parseCode,
96
+ analyzeCodeEffects,
96
97
  scanStringLiteral,
97
98
  } from './js-lexer';
98
99
  export { indexStrictCodeEnds } from './markup/code-end';
99
100
  export type {
100
101
  ParsedCode,
102
+ CodeEffects,
103
+ CodeMutation,
104
+ CodeShapeUncertainty,
101
105
  VariableRef,
102
106
  FindCodeEndOptions,
103
107
  JsGoal,
@@ -116,6 +116,16 @@ type ToolingChecks = [
116
116
  PublishedTooling.VariableReference
117
117
  >,
118
118
  Same<typeof SourceTooling.parseCode, typeof PublishedTooling.parseCode>,
119
+ Same<
120
+ typeof SourceTooling.analyzeCodeEffects,
121
+ typeof PublishedTooling.analyzeCodeEffects
122
+ >,
123
+ SameShape<SourceTooling.CodeEffects, PublishedTooling.CodeEffects>,
124
+ SameShape<SourceTooling.CodeMutation, PublishedTooling.CodeMutation>,
125
+ SameShape<
126
+ SourceTooling.CodeShapeUncertainty,
127
+ PublishedTooling.CodeShapeUncertainty
128
+ >,
119
129
  Same<
120
130
  typeof SourceTooling.macroArgumentSpans,
121
131
  typeof PublishedTooling.macroArgumentSpans
@@ -0,0 +1,52 @@
1
+ import { mutateState } from '../execute-mutation';
2
+ import { runAsControlEdits } from './control-edits';
3
+ import { setByPath } from './object-path';
4
+ import { notifyVariableWrite } from './variable-writes';
5
+
6
+ interface ControlWrite {
7
+ segments: readonly string[];
8
+ value: unknown;
9
+ }
10
+
11
+ let pending: ControlWrite[] | undefined;
12
+
13
+ /** Commit related bindings together, preserving references and item edits. */
14
+ function commit(writes: readonly ControlWrite[]): void {
15
+ if (!writes.length) return;
16
+ runAsControlEdits(
17
+ writes.map(({ segments }) => segments),
18
+ () => {
19
+ mutateState((work, adopt) => {
20
+ for (const { segments, value } of writes) {
21
+ setByPath(work.variables, segments, adopt(value), {
22
+ createMissing: true,
23
+ });
24
+ }
25
+ });
26
+ },
27
+ );
28
+ }
29
+
30
+ /** A control write, or one part of the form reset currently being collected. */
31
+ export function setControlValue(
32
+ segments: readonly string[],
33
+ value: unknown,
34
+ ): void {
35
+ notifyVariableWrite(segments);
36
+ const write = { segments, value };
37
+ if (pending) pending.push(write);
38
+ else commit([write]);
39
+ }
40
+
41
+ /** Subscribers see the complete reset, never a partially reset form. */
42
+ export function batchControlValues(run: () => void): void {
43
+ if (pending) return run();
44
+ const writes: ControlWrite[] = [];
45
+ pending = writes;
46
+ try {
47
+ run();
48
+ } finally {
49
+ pending = undefined;
50
+ }
51
+ commit(writes);
52
+ }
@@ -65,7 +65,18 @@ export function runAsControlEdit(
65
65
  segments: readonly string[],
66
66
  run: () => void,
67
67
  ): void {
68
- withEdits([['variables', ...segments]], run);
68
+ runAsControlEdits([segments], run);
69
+ }
70
+
71
+ /** Attribute every binding of an atomic form reset to its own path. */
72
+ export function runAsControlEdits(
73
+ paths: readonly (readonly string[])[],
74
+ run: () => void,
75
+ ): void {
76
+ withEdits(
77
+ paths.map((segments) => ['variables', ...segments]),
78
+ run,
79
+ );
69
80
  }
70
81
 
71
82
  /** Whether mutation code runs inside a {for} iteration. */
@@ -1292,6 +1292,44 @@ export interface ParsedCode {
1292
1292
  strings: string[];
1293
1293
  }
1294
1294
 
1295
+ /** A binding write (empty path), or a member write, with the entire target span. */
1296
+ export interface CodeMutation {
1297
+ start: number;
1298
+ end: number;
1299
+ /** Null for an indirect target; null path segments are computed keys. */
1300
+ target: { sigil: Sigil; name: string; path: (string | null)[] } | null;
1301
+ /** Compound assignments and updates read the target as well as writing it. */
1302
+ read: boolean;
1303
+ }
1304
+
1305
+ /** A reason declaration-time shapes alone cannot justify a missing-member advisory. */
1306
+ export interface CodeShapeUncertainty {
1307
+ start: number;
1308
+ end: number;
1309
+ reason:
1310
+ | 'computed-write'
1311
+ | 'indirect-write'
1312
+ | 'prototype-write'
1313
+ | 'call'
1314
+ | 'escape'
1315
+ | 'dynamic-scope';
1316
+ }
1317
+
1318
+ export interface CodeEffects {
1319
+ mutations: CodeMutation[];
1320
+ uncertain: CodeShapeUncertainty[];
1321
+ }
1322
+
1323
+ /** Conservative shape effects using parseCode's grammar and target roles.
1324
+ * Includes nested functions and unreachable branches. Offsets refer to src;
1325
+ * map through pieceOffset when analyzing decoded passagePieces code.
1326
+ * Throws for invalid code. No alias, call or control-flow analysis is attempted.
1327
+ */
1328
+ export declare function analyzeCodeEffects(
1329
+ src: string,
1330
+ goal?: JsGoal,
1331
+ ): CodeEffects;
1332
+
1295
1333
  /** Parse executable code using the runtime grammar. Throws for malformed code
1296
1334
  * (including sigil declarations); lexJs remains available for tolerant scanning.
1297
1335
  * Member assignments read their root binding; only direct targets write it.