@rohal12/spindle 0.59.26 → 0.59.27

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.
@@ -40,6 +40,7 @@ export {
40
40
  parseWidgetDef,
41
41
  widgetDefinitions,
42
42
  variableReferences,
43
+ discoverMacros,
43
44
  validateVariableReferences,
44
45
  } from './story-variables.js';
45
46
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.26",
3
+ "version": "0.59.27",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -0,0 +1,299 @@
1
+ /**
2
+ * What `defineMacro({ … })` calls in JavaScript declare, read from the text
3
+ * without running it (see discoverMacros): the literal parts of the config
4
+ * object, and nothing else.
5
+ */
6
+ import { lexJs } from './js-lexer';
7
+ import {
8
+ checkParameterTypes,
9
+ type ParameterDef,
10
+ type ParameterType,
11
+ type StringHolds,
12
+ } from './registry';
13
+ import { Reader } from './static-literal';
14
+ import type { ToolingMacro } from './tooling';
15
+
16
+ /** A macro that a `defineMacro` call declares, and where its name is written. */
17
+ export interface DiscoveredMacro extends ToolingMacro {
18
+ /** Whether it renders what is in `<name>` with `merged` locals. */
19
+ merged?: boolean;
20
+ description?: string;
21
+ /** The name as written, without quotes: `[nameStart, nameEnd)` UTF-16 offsets. */
22
+ nameStart: number;
23
+ nameEnd: number;
24
+ }
25
+
26
+ /** A literal in the config of a macro. */
27
+ type Datum =
28
+ | { type: 'string'; value: string; start: number; end: number }
29
+ | { type: 'boolean'; value: boolean }
30
+ | { type: 'array'; items: (Datum | undefined)[] }
31
+ | { type: 'object'; props: Map<string, Datum | undefined> };
32
+
33
+ /** The text of an object config, or the name of the variable that holds it. */
34
+ const CALL_RE = /(?<![\w$])defineMacro\s*\(\s*/g;
35
+ const IDENTIFIER_ARGUMENT_RE = /^([A-Za-z_$][\w$]*)\s*[,)]/;
36
+ const WORD_RE = /[A-Za-z_]+/y;
37
+
38
+ /** The literals of a config object, read to the end of what is static. */
39
+ class ConfigReader extends Reader {
40
+ /** Whether the text could not be skipped through (it ends the reading). */
41
+ failed = false;
42
+
43
+ /** The static value of a member or element, whatever follows is skipped. */
44
+ private member(): Datum | undefined {
45
+ const at = this.i;
46
+ const datum = this.datum();
47
+ this.space();
48
+ if (datum && this.atElementEnd()) return datum;
49
+ // Part of a larger expression, or not a literal: skip all of it
50
+ this.i = at;
51
+ while (this.i < this.src.length && !this.atElementEnd()) {
52
+ if (!this.skipOne()) {
53
+ this.fail();
54
+ break;
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ private atElementEnd(): boolean {
61
+ return this.i >= this.src.length || ',]}'.includes(this.src.charAt(this.i));
62
+ }
63
+
64
+ /** The literal at the cursor, if it is a string, boolean, array or object. */
65
+ datum(): Datum | undefined {
66
+ const { src } = this;
67
+ this.space();
68
+ const c = src.charAt(this.i);
69
+ if (c === '"' || c === "'") {
70
+ const start = this.i;
71
+ const value = this.stringValue();
72
+ return value === undefined
73
+ ? undefined
74
+ : { type: 'string', value, start: start + 1, end: this.i - 1 };
75
+ }
76
+ if (c === '`') return this.plainTemplate();
77
+ if (c === '[') return this.array();
78
+ if (c === '{') return this.record();
79
+ WORD_RE.lastIndex = this.i;
80
+ const word = WORD_RE.exec(src)?.[0];
81
+ if (word === 'true' || word === 'false') {
82
+ this.i = WORD_RE.lastIndex;
83
+ return { type: 'boolean', value: word === 'true' };
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ /** A template literal that has no `${}` and no escapes, as a string. */
89
+ private plainTemplate(): Datum | undefined {
90
+ const { src } = this;
91
+ const start = this.i;
92
+ for (let i = start + 1; i < src.length; i++) {
93
+ const c = src.charAt(i);
94
+ if (c === '`') {
95
+ this.i = i + 1;
96
+ return {
97
+ type: 'string',
98
+ value: src.slice(start + 1, i),
99
+ start: start + 1,
100
+ end: i,
101
+ };
102
+ }
103
+ if (c === '\\' || (c === '$' && src.charAt(i + 1) === '{')) break;
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ /**
109
+ * Read the elements up to `close`, each by `read`, which leaves the cursor
110
+ * after what it read. False if the text ends first, or cannot be read.
111
+ */
112
+ private elements(close: string, read: () => void): boolean {
113
+ this.i++;
114
+ for (;;) {
115
+ this.space();
116
+ const c = this.src.charAt(this.i);
117
+ if (c === close) {
118
+ this.i++;
119
+ return true;
120
+ }
121
+ if (c === ',') {
122
+ this.i++;
123
+ continue;
124
+ }
125
+ if (this.failed || this.i >= this.src.length) return false;
126
+ const before = this.i;
127
+ read();
128
+ if (this.i === before) this.fail();
129
+ }
130
+ }
131
+
132
+ private array(): Datum | undefined {
133
+ const items: (Datum | undefined)[] = [];
134
+ return this.elements(']', () => items.push(this.member()))
135
+ ? { type: 'array', items }
136
+ : undefined;
137
+ }
138
+
139
+ private record(): Datum | undefined {
140
+ const props = new Map<string, Datum | undefined>();
141
+ const ok = this.elements('}', () => {
142
+ const key = this.key();
143
+ this.space();
144
+ if (key !== undefined && this.src.charAt(this.i) === ':') {
145
+ this.i++;
146
+ props.set(key, this.member());
147
+ } else if (!this.skipMember()) {
148
+ // A method, a shorthand member, a spread: not a literal
149
+ this.fail();
150
+ }
151
+ });
152
+ return ok ? { type: 'object', props } : undefined;
153
+ }
154
+
155
+ /** Stop reading: the text cannot be skipped through. */
156
+ private fail(): void {
157
+ this.failed = true;
158
+ }
159
+ }
160
+
161
+ /** The text with everything but code (strings, comments, regexes) blanked. */
162
+ function codeOnly(source: string): string {
163
+ const chars = Array.from({ length: source.length }, () => ' ');
164
+ lexJs(
165
+ source,
166
+ {
167
+ code(ch, index) {
168
+ for (let k = 0; k < ch.length; k++) chars[index + k] = ch[k]!;
169
+ },
170
+ },
171
+ 'statements',
172
+ );
173
+ return chars.join('');
174
+ }
175
+
176
+ const stringOf = (d: Datum | undefined) =>
177
+ d?.type === 'string' ? d : undefined;
178
+ const booleanOf = (d: Datum | undefined) =>
179
+ d?.type === 'boolean' ? d.value : undefined;
180
+ const textOf = (d: Datum | undefined) => stringOf(d)?.value;
181
+ const stringsOf = (d: Datum | undefined): string[] =>
182
+ d?.type === 'array'
183
+ ? d.items.flatMap((item) => stringOf(item)?.value ?? [])
184
+ : [];
185
+
186
+ /** `{ [key]: value }` if `read` finds the property `key` written out, else `{}`. */
187
+ function written<K extends string, T>(
188
+ props: ReadonlyMap<string, Datum | undefined>,
189
+ key: K,
190
+ read: (datum: Datum | undefined) => T | undefined,
191
+ ): { [P in K]?: T } {
192
+ const value = read(props.get(key));
193
+ return (value === undefined ? {} : { [key]: value }) as { [P in K]?: T };
194
+ }
195
+
196
+ /** A declared parameter, if its name and type are written out. */
197
+ function parameterOf(datum: Datum | undefined): ParameterDef | undefined {
198
+ if (datum?.type !== 'object') return undefined;
199
+ const { props } = datum;
200
+ const name = stringOf(props.get('name'));
201
+ const type = stringOf(props.get('type'));
202
+ if (!name || !type) return undefined;
203
+ const param: ParameterDef = {
204
+ name: name.value,
205
+ type: type.value as ParameterType,
206
+ ...written(props, 'required', booleanOf),
207
+ ...written(props, 'description', textOf),
208
+ ...written(props, 'holds', (d) => textOf(d) as StringHolds | undefined),
209
+ };
210
+ if (props.has('parameters')) {
211
+ const options = parametersOf(props.get('parameters'));
212
+ if (!options) return undefined;
213
+ param.parameters = options;
214
+ }
215
+ return param;
216
+ }
217
+
218
+ /** The parameters of an array literal of them, if every one is written out. */
219
+ function parametersOf(datum: Datum | undefined): ParameterDef[] | undefined {
220
+ if (datum?.type !== 'array') return undefined;
221
+ const params: ParameterDef[] = [];
222
+ for (const item of datum.items) {
223
+ const param = parameterOf(item);
224
+ if (!param) return undefined;
225
+ params.push(param);
226
+ }
227
+ return params;
228
+ }
229
+
230
+ /** The macro a config object declares, if its name is written out. */
231
+ function macroOf(config: Datum): DiscoveredMacro | undefined {
232
+ if (config.type !== 'object') return undefined;
233
+ const { props } = config;
234
+ const name = stringOf(props.get('name'));
235
+ if (!name?.value) return undefined;
236
+ const subMacros = stringsOf(props.get('subMacros'));
237
+ const block = booleanOf(props.get('block'));
238
+ const macro: DiscoveredMacro = {
239
+ name: name.value,
240
+ block: block === true || (block !== false && subMacros.length > 0),
241
+ subMacros,
242
+ nameStart: name.start,
243
+ nameEnd: name.end,
244
+ ...written(props, 'interpolate', booleanOf),
245
+ ...written(props, 'storeVar', booleanOf),
246
+ ...written(props, 'merged', booleanOf),
247
+ ...written(props, 'description', textOf),
248
+ };
249
+ // Arguments are read by their parameters: a list that is not entirely
250
+ // written out, or that defineMacro would refuse, declares none
251
+ const parameters = parametersOf(props.get('parameters'));
252
+ if (parameters) {
253
+ try {
254
+ checkParameterTypes(macro.name, parameters);
255
+ macro.parameters = parameters;
256
+ } catch {
257
+ // defineMacro throws for it: the macro is not registered with them
258
+ }
259
+ }
260
+ return macro;
261
+ }
262
+
263
+ /**
264
+ * The macros the `defineMacro({ … })` and `Story.defineMacro({ … })` calls in
265
+ * `source` (JavaScript: a script passage, the body of a `{do}`, a project
266
+ * file) declare, in source order, read from the text without running it. A
267
+ * call whose config is an object literal (or a variable declared as one with
268
+ * `const`, `let` or `var`) and whose `name` is a string is found, wherever it
269
+ * is, even inside a function. Only what is written out is read: a `block`,
270
+ * `interpolate`, `storeVar` or `merged` that is a boolean literal, the
271
+ * strings of `subMacros`, and `parameters` when every one is an object
272
+ * literal with a string `name` and `type` (and `holds`, `required`,
273
+ * `description` and nested `parameters` of options when written out as such);
274
+ * a list with a parameter that is not, or that `defineMacro` would refuse,
275
+ * declares none. It is tolerant: text it cannot read is skipped, and it
276
+ * throws for none.
277
+ */
278
+ export function discoverMacros(source: string): DiscoveredMacro[] {
279
+ const code = codeOnly(source);
280
+ const found: DiscoveredMacro[] = [];
281
+ for (const call of code.matchAll(CALL_RE)) {
282
+ let at = call.index + call[0].length;
283
+ if (code.charAt(at) !== '{') {
284
+ const variable = IDENTIFIER_ARGUMENT_RE.exec(code.slice(at))?.[1];
285
+ if (!variable) continue;
286
+ const declaration = new RegExp(
287
+ `(?<![\\w$.])(?:const|let|var)\\s+${variable.replace(/\$/g, '\\$')}\\s*=\\s*(?=\\{)`,
288
+ ).exec(code);
289
+ if (!declaration) continue;
290
+ at = declaration.index + declaration[0].length;
291
+ }
292
+ const reader = new ConfigReader(source);
293
+ reader.i = at;
294
+ const config = reader.datum();
295
+ const macro = config && macroOf(config);
296
+ if (macro) found.push(macro);
297
+ }
298
+ return found;
299
+ }
@@ -6,6 +6,7 @@
6
6
  * Tooling runs it too (see src/tooling.ts).
7
7
  */
8
8
  import {
9
+ analyzeMarkup,
9
10
  lineColumn,
10
11
  MarkupError,
11
12
  parseMarkup,
@@ -102,6 +103,14 @@ export interface MarkupValidationOptions {
102
103
  * and attributes is checked.
103
104
  */
104
105
  parametersOf?: ParametersOf;
106
+ /**
107
+ * Report every problem of a passage (default: false). By default a
108
+ * passage is read only up to its first malformed tag or unpaired tag, which
109
+ * is enough to refuse to start the story. With this, malformed tags and
110
+ * unpaired tags are all reported, and the macros, code, arguments and
111
+ * passage names are checked in the markup that could be read.
112
+ */
113
+ tolerant?: boolean;
105
114
  }
106
115
 
107
116
  /**
@@ -241,20 +250,32 @@ export function validateMarkup(
241
250
  const parsed: [MarkupPassage, Token[]][] = [];
242
251
  const widgets = new Set<string>();
243
252
  const passageNames = new Set<string>();
253
+ const addWidgets = (tokens: readonly Token[]) => {
254
+ for (const token of tokens) {
255
+ if (token.type !== 'macro' || token.isClose) continue;
256
+ if (token.name.toLowerCase() !== 'widget') continue;
257
+ const name = widgetName(token.rawArgs);
258
+ if (name) widgets.add(name);
259
+ }
260
+ };
244
261
  for (const passage of passages) {
245
262
  passageNames.add(passage.name);
246
263
  if (NOT_MARKUP.has(passage.name)) continue;
247
264
  if (passage.tags?.some((tag) => NOT_MARKUP_TAGS.includes(tag))) continue;
248
265
  const reported = !options.only || options.only(passage);
266
+ if (options.tolerant) {
267
+ // Every problem, and the tokens that could be read around them
268
+ const { tokens, errors } = analyzeMarkup(passage.content, { hooks });
269
+ addWidgets(tokens);
270
+ if (!reported) continue;
271
+ for (const err of errors) reportError(passage, err, '');
272
+ parsed.push([passage, tokens]);
273
+ continue;
274
+ }
249
275
  try {
250
276
  // The tokens first: they don't depend on which macros take a body
251
277
  const tokens = tokenizeMarkup(passage.content);
252
- for (const token of tokens) {
253
- if (token.type !== 'macro' || token.isClose) continue;
254
- if (token.name.toLowerCase() !== 'widget') continue;
255
- const name = widgetName(token.rawArgs);
256
- if (name) widgets.add(name);
257
- }
278
+ addWidgets(tokens);
258
279
  if (!reported) continue;
259
280
  parseMarkup(passage.content, { hooks });
260
281
  parsed.push([passage, tokens]);