squiffy-runtime 7.0.0-beta.3 → 7.0.0-beta.4

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.
@@ -7,5 +7,9 @@ export declare class TextProcessor {
7
7
  getCurrentSection: () => Section;
8
8
  handlebars: typeof Handlebars;
9
9
  constructor(story: () => Story, state: State, currentSection: () => Section);
10
+ evaluate(expression: string): unknown;
11
+ private expressionCache;
12
+ private evaluated;
10
13
  process(text: string, inline: boolean): string;
11
14
  }
15
+ export declare function errorHtml(label: string, message: string): string;
package/dist/types.d.ts CHANGED
@@ -51,6 +51,7 @@ export interface Story {
51
51
  start: string;
52
52
  id?: string | null;
53
53
  uiJsIndex?: number;
54
+ expressions?: boolean;
54
55
  sections: Record<string, Section>;
55
56
  }
56
57
  export interface Section {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-runtime",
3
- "version": "7.0.0-beta.3",
3
+ "version": "7.0.0-beta.4",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/textadventures/squiffy.git",
@@ -49,7 +49,7 @@
49
49
  "esbuild": "^0.28.2",
50
50
  "global-jsdom": "^31.0.0",
51
51
  "jsdom": "^31.0.1",
52
- "squiffy-compiler": "^7.0.0-beta.3",
52
+ "squiffy-compiler": "^7.0.0-beta.4",
53
53
  "typescript": "^6.0.3",
54
54
  "vite": "^8.3.8",
55
55
  "vite-plugin-dts": "^5.1.2"
@@ -59,5 +59,5 @@
59
59
  "handlebars": "^4.7.10",
60
60
  "marked": "^18.2.0"
61
61
  },
62
- "gitHead": "016f53cc52dc2cf504787ef8329740ca2cf8d481"
62
+ "gitHead": "751f5f19aebb41942dd45f0de61f60a3ed5f9b8e"
63
63
  }
@@ -1,5 +1,5 @@
1
1
  import { expect, test, describe } from "vitest";
2
- import { rewriteInfixCondition, rewriteInfixExpressions } from "./infixExpressions.js";
2
+ import { rewriteDisplayExpression, rewriteInfixArguments, rewriteInfixCondition, rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "./infixExpressions.js";
3
3
 
4
4
  describe("rewriteInfixCondition", () => {
5
5
  test.each([
@@ -123,6 +123,83 @@ describe("rewriteInfixCondition", () => {
123
123
  expect(() => rewriteInfixCondition(input)).toThrow(message);
124
124
  });
125
125
 
126
+ test.each([
127
+ ["a + b > 1", "(gt (add a b) 1)"],
128
+ ["a - b > 1", "(gt (sub a b) 1)"],
129
+ ["a * b > 1", "(gt (mul a b) 1)"],
130
+ ["a / b > 1", "(gt (div a b) 1)"],
131
+ ["a % b = 1", "(eq (mod a b) 1)"],
132
+ ["-a < 0", "(lt (sub 0 a) 0)"],
133
+ ["- a < 0", "(lt (sub 0 a) 0)"],
134
+ ["gold >= price * 2", "(gte gold (mul price 2))"],
135
+ ])("arithmetic operator: %s", (input, expected) => {
136
+ expect(rewriteInfixCondition(input)).toBe(expected);
137
+ });
138
+
139
+ test.each([
140
+ ["a + b * c = 1", "(eq (add a (mul b c)) 1)"],
141
+ ["a * b + c = 1", "(eq (add (mul a b) c) 1)"],
142
+ ["a - b - c = 1", "(eq (sub (sub a b) c) 1)"],
143
+ ["a / b / c = 1", "(eq (div (div a b) c) 1)"],
144
+ ["a % b * c = 1", "(eq (mul (mod a b) c) 1)"],
145
+ ["(a + b) * c = 1", "(eq (mul (add a b) c) 1)"],
146
+ ["a * (b + c) = 1", "(eq (mul a (add b c)) 1)"],
147
+ ["-a * b = 1", "(eq (mul (sub 0 a) b) 1)"],
148
+ ["-(a + b) = 1", "(eq (sub 0 (add a b)) 1)"],
149
+ ["a - -b = 1", "(eq (sub a (sub 0 b)) 1)"],
150
+ ["a + b > c and not d - 1 = 0", "(and (gt (add a b) c) (not (eq (sub d 1) 0)))"],
151
+ ["a > b + 1 or c", "(or (gt a (add b 1)) c)"],
152
+ ["(length \"items\") * 2 > 3", "(gt (mul (length \"items\") 2) 3)"],
153
+ ])("arithmetic precedence: %s", (input, expected) => {
154
+ expect(rewriteInfixCondition(input)).toBe(expected);
155
+ });
156
+
157
+ test.each([
158
+ ["a+b>1", "(gt (add a b) 1)"],
159
+ ["a*b>1", "(gt (mul a b) 1)"],
160
+ ["a%b>1", "(gt (mod a b) 1)"],
161
+ ["a -1 > 0", "(gt (sub a 1) 0)"],
162
+ ["a - 1 > 0", "(gt (sub a 1) 0)"],
163
+ ["a -b > 0", "(gt (sub a b) 0)"],
164
+ ["a /b > 0", "(gt (div a b) 0)"],
165
+ ["a * -1 > 0", "(gt (mul a -1) 0)"],
166
+ ["a > -1", "(gt a -1)"],
167
+ ["1.5 * a > 0", "(gt (mul 1.5 a) 0)"],
168
+ ])("arithmetic spacing: %s", (input, expected) => {
169
+ expect(rewriteInfixCondition(input)).toBe(expected);
170
+ });
171
+
172
+ test.each([
173
+ ["my-score > 1", "(gt my-score 1)"],
174
+ ["a-b > 1", "(gt a-b 1)"],
175
+ ["../score > 1", "(gt ../score 1)"],
176
+ ["player/score > 1", "(gt player/score 1)"],
177
+ ["[gold + silver] > 1", "(gt [gold + silver] 1)"],
178
+ ["name = \"a + b\"", "(eq name \"a + b\")"],
179
+ ])("- and / inside names and paths: %s", (input, expected) => {
180
+ expect(rewriteInfixCondition(input)).toBe(expected);
181
+ });
182
+
183
+ test.each([
184
+ "my-score",
185
+ "(gt x -1)",
186
+ "(foo a -1)",
187
+ "(x -1)",
188
+ ])("passes through prefix syntax with -: %s", (input) => {
189
+ expect(rewriteInfixCondition(input)).toBeNull();
190
+ });
191
+
192
+ test.each([
193
+ ["a +", "expected a value after '+'"],
194
+ ["a * > 1", "expected a value before '>'"],
195
+ ["* a", "expected a value before '*'"],
196
+ ["a + + b", "expected a value before '+'"],
197
+ ["-", "expected a value after '-'"],
198
+ ["(a + b", "expected ')' but found end of expression"],
199
+ ])("arithmetic error: %s", (input, message) => {
200
+ expect(() => rewriteInfixCondition(input)).toThrow(message);
201
+ });
202
+
126
203
  test("error message includes the condition", () => {
127
204
  expect(() => rewriteInfixCondition(" score > ")).toThrow("Invalid condition \"score >\": expected a value after '>'");
128
205
  });
@@ -134,6 +211,65 @@ describe("rewriteInfixCondition", () => {
134
211
  });
135
212
  });
136
213
 
214
+ describe("rewriteInfixArguments", () => {
215
+ test.each([
216
+ ["\"gold\" gold + price * 2", "\"gold\" (add gold (mul price 2))"],
217
+ ["\"gold\" (gold + price) * 2", "\"gold\" (mul (add gold price) 2)"],
218
+ ["\"name\" name + \" the Brave\"", "\"name\" (add name \" the Brave\")"],
219
+ ["\"x\" -y", "\"x\" (sub 0 y)"],
220
+ ["\"x\" a > b", "\"x\" (gt a b)"],
221
+ ["\"x\" a and b", "\"x\" (and a b)"],
222
+ ["\"x\" (length \"items\") - 1", "\"x\" (sub (length \"items\") 1)"],
223
+ ])("%s", (input, expected) => {
224
+ expect(rewriteInfixArguments(input)).toBe(expected);
225
+ });
226
+
227
+ test.each([
228
+ "\"score\" 100",
229
+ "\"score\" -1",
230
+ "\"name\" \"Alice\"",
231
+ "\"items\" (array \"a\" \"b\")",
232
+ "\"x\" (add a b)",
233
+ "\"counter\"",
234
+ "\"x\" my-score",
235
+ ])("passes through prefix syntax: %s", (input) => {
236
+ expect(rewriteInfixArguments(input)).toBeNull();
237
+ });
238
+
239
+ test.each([
240
+ ["\"gold\" gold +", "Invalid expression \"\"gold\" gold +\": expected a value after '+'"],
241
+ ["\"gold\" gold + 1 x", "unexpected 'x'"],
242
+ ["\"gold\" + 1", "expected a value before '+'"],
243
+ ])("error: %s", (input, message) => {
244
+ expect(() => rewriteInfixArguments(input)).toThrow(message);
245
+ });
246
+ });
247
+
248
+ describe("rewriteDisplayExpression", () => {
249
+ test.each([
250
+ ["price * 2", "mul price 2"],
251
+ ["gold + price * 2", "add gold (mul price 2)"],
252
+ ["a > b", "gt a b"],
253
+ ["gold", "gold"],
254
+ [" (gold) ", "gold"],
255
+ ["(length \"items\")", "length \"items\""],
256
+ ["-gold", "sub 0 gold"],
257
+ ])("%s", (input, expected) => {
258
+ expect(rewriteDisplayExpression(input)).toBe(expected);
259
+ });
260
+
261
+ test.each([
262
+ ["", "expected a value"],
263
+ ["a +", "expected a value after '+'"],
264
+ ["a b", "unexpected 'b'"],
265
+ ["5", "expected an attribute or a calculation"],
266
+ ["\"text\"", "expected an attribute or a calculation"],
267
+ ["\"unterminated", "unterminated string"],
268
+ ])("error: %s", (input, message) => {
269
+ expect(() => rewriteDisplayExpression(input)).toThrow(message);
270
+ });
271
+ });
272
+
137
273
  describe("rewriteInfixExpressions", () => {
138
274
  test("#if", () => {
139
275
  expect(rewriteInfixExpressions("{{#if score > 100 and has_key}}yes{{/if}}"))
@@ -184,4 +320,60 @@ describe("rewriteInfixExpressions", () => {
184
320
  test("throws for malformed infix", () => {
185
321
  expect(() => rewriteInfixExpressions("{{#if score >}}x{{/if}}")).toThrow("Invalid condition \"score >\"");
186
322
  });
323
+
324
+ test("{{set}}, {{inc}} and {{dec}}", () => {
325
+ expect(rewriteInfixExpressions("{{set \"gold\" gold + price * 2}}{{inc \"gold\" price * 2}}{{dec \"hp\" dmg - armour}}"))
326
+ .toBe("{{set \"gold\" (add gold (mul price 2))}}{{inc \"gold\" (mul price 2)}}{{dec \"hp\" (sub dmg armour)}}");
327
+ });
328
+
329
+ test("{{set}} with prefix syntax is untouched", () => {
330
+ const text = "{{set \"score\" 100}}{{inc \"x\"}}{{set \"items\" (array \"a\")}}{{settings}}{{inc}}";
331
+ expect(rewriteInfixExpressions(text)).toBe(text);
332
+ });
333
+
334
+ test("{{= expression}}", () => {
335
+ expect(rewriteInfixExpressions("Cost: {{= price * 2}}, {{~= a + b ~}} and {{= gold}}."))
336
+ .toBe("Cost: {{mul price 2}}, {{~add a b~}} and {{gold}}.");
337
+ });
338
+
339
+ test("escaped {{= }} is untouched", () => {
340
+ expect(rewriteInfixExpressions("\\{{= a + b}}")).toBe("\\{{= a + b}}");
341
+ });
342
+
343
+ test("throws for malformed {{set}} and {{= }}", () => {
344
+ expect(() => rewriteInfixExpressions("{{set \"x\" a +}}")).toThrow("Invalid expression \"\"x\" a +\"");
345
+ expect(() => rewriteInfixExpressions("{{= a +}}")).toThrow("Invalid expression \"a +\"");
346
+ });
347
+ });
348
+
349
+ describe("rewriteValueExpression", () => {
350
+ test.each([
351
+ ["gold", "gold"],
352
+ ["10", "10"],
353
+ ['"sword"', '"sword"'],
354
+ ["true", "true"],
355
+ ["gold + price * 2", "(add gold (mul price 2))"],
356
+ ["gold > 100", "(gt gold 100)"],
357
+ ["not has_key", "(not has_key)"],
358
+ ['(seen "intro")', '(seen "intro")'],
359
+ ])("%s -> %s", (input, expected) => {
360
+ expect(rewriteValueExpression(input)).toBe(expected);
361
+ });
362
+
363
+ test.each(["", "gold +", "gold price", "(gold"])("rejects %j", input => {
364
+ expect(() => rewriteValueExpression(input)).toThrow(/Invalid expression/);
365
+ });
366
+ });
367
+
368
+ describe("splitSetters", () => {
369
+ test.each([
370
+ ["a = 1, b += 2", ["a = 1", "b += 2"]],
371
+ [' message = "Hi, there", done', ['message = "Hi, there"', "done"]],
372
+ ["name = 'Bob, the Brave', x", ["name = 'Bob, the Brave'", "x"]],
373
+ ['a = "say \\"hi, there\\"", b', ['a = "say \\"hi, there\\""', "b"]],
374
+ ["a = (add b 1), c", ["a = (add b 1)", "c"]],
375
+ ["a = 1,, b = 2,", ["a = 1", "b = 2"]],
376
+ ])("%j", (input, expected) => {
377
+ expect(splitSetters(input)).toEqual(expected);
378
+ });
187
379
  });
@@ -1,10 +1,19 @@
1
- // Rewrites infix conditions in {{#if}}, {{#unless}}, {{else if}} and {{else unless}}
2
- // into the equivalent prefix helper calls, before the text reaches Handlebars. e.g.
3
- // {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
1
+ // Rewrites infix expressions into the equivalent prefix helper calls, before the text reaches
2
+ // Handlebars. They're accepted in:
3
+ // conditions: {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
4
+ // (also {{#unless}}, {{else if}} and {{else unless}})
5
+ // values: {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
6
+ // (also {{inc}} and {{dec}})
7
+ // display: {{= price * 2}} -> {{mul price 2}}
4
8
  //
5
- // Precedence, from tightest to loosest: comparisons, not/!, and/&&, or/||. So "not" applies to
6
- // a whole comparison, as it reads in English: not gender = "male" means not (gender = "male").
7
- // Conditions that don't use any infix operator are passed through unchanged.
9
+ // Precedence, from tightest to loosest: unary minus, * / %, + -, comparisons, not/!, and/&&,
10
+ // or/||. So "not" applies to a whole comparison, as it reads in English: not gender = "male"
11
+ // means not (gender = "male").
12
+ // Expressions that don't use any infix operator are passed through unchanged (except {{= }},
13
+ // which isn't valid Handlebars, so it's always rewritten).
14
+ //
15
+ // "-" and "/" can appear inside Handlebars names and paths (my-score, ../score), so they're only
16
+ // operators at the start of a token: a - b and a -b subtract, but a-b is the attribute "a-b".
8
17
 
9
18
  type TokenType = "op" | "(" | ")" | "value" | "ident";
10
19
 
@@ -27,13 +36,24 @@ const comparisonHelpers: Record<string, string> = {
27
36
  "<=": "lte",
28
37
  };
29
38
 
30
- const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!"];
39
+ const arithmeticHelpers: Record<string, string> = {
40
+ "+": "add",
41
+ "-": "sub",
42
+ "*": "mul",
43
+ "/": "div",
44
+ "%": "mod",
45
+ };
46
+
47
+ const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!", "+", "*", "%", "-", "/"];
31
48
  const keywordOps = ["and", "or", "not"];
32
49
  const literals = ["true", "false", "null", "undefined"];
33
50
 
34
51
  // Characters that end an identifier/path. "[" starts a Handlebars literal segment,
35
52
  // e.g. [my attribute], which may contain any of these.
36
- const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~"]);
53
+ // "-" and "/" aren't here: see above.
54
+ const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~+*%"]);
55
+
56
+ const numberPattern = /^-?\d+(\.\d+)?$/;
37
57
 
38
58
  class ExpressionError extends Error {}
39
59
 
@@ -64,7 +84,9 @@ function tokenize(expr: string): Token[] {
64
84
  i = j + 1;
65
85
  continue;
66
86
  }
67
- const op = symbolicOps.find(o => expr.startsWith(o, i));
87
+ // A "-" before a digit starts a negative number, as before (the parser treats
88
+ // a -1 as a - 1 where it needs an operator)
89
+ const op = symbolicOps.find(o => expr.startsWith(o, i) && !(o === "-" && /\d/.test(expr[i + 1] ?? "")));
68
90
  if (op) {
69
91
  tokens.push({ type: "op", text: op });
70
92
  i += op.length;
@@ -87,7 +109,7 @@ function tokenize(expr: string): Token[] {
87
109
  const word = expr.slice(i, j);
88
110
  if (keywordOps.includes(word)) {
89
111
  tokens.push({ type: "op", text: word });
90
- } else if (literals.includes(word) || /^-?\d+(\.\d+)?$/.test(word)) {
112
+ } else if (literals.includes(word) || numberPattern.test(word)) {
91
113
  tokens.push({ type: "value", text: word });
92
114
  } else {
93
115
  tokens.push({ type: "ident", text: word });
@@ -123,6 +145,28 @@ class Parser {
123
145
  return token ? `'${token.text}'` : "end of expression";
124
146
  }
125
147
 
148
+ // A value: an expression with nothing after it
149
+ parseExpression(): Node {
150
+ const result = this.parseOr();
151
+ if (this.peek()) {
152
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
153
+ }
154
+ return result;
155
+ }
156
+
157
+ // Arguments to a helper: `count` plain values (e.g. the attribute name), then an expression
158
+ parseArguments(count: number): Node[] {
159
+ const result: Node[] = [];
160
+ for (let i = 0; i < count; i++) {
161
+ result.push(this.parsePrimary());
162
+ }
163
+ if (!this.peek()) {
164
+ throw new ExpressionError("expected a value");
165
+ }
166
+ result.push(this.parseExpression());
167
+ return result;
168
+ }
169
+
126
170
  // Top level: an expression, optionally followed by hash arguments (e.g. includeZero=true)
127
171
  parseCondition(): Node[] {
128
172
  const result = [this.parseOr()];
@@ -176,7 +220,7 @@ class Parser {
176
220
  }
177
221
 
178
222
  private parseComparison(): Node {
179
- const left = this.parsePrimary();
223
+ const left = this.parseAdditive();
180
224
  const opToken = this.peek();
181
225
  if (opToken?.type !== "op" || !(opToken.text in comparisonHelpers)) {
182
226
  return left;
@@ -185,7 +229,7 @@ class Parser {
185
229
  if (!this.peek()) {
186
230
  throw new ExpressionError(`expected a value after '${opToken.text}'`);
187
231
  }
188
- const right = this.parsePrimary();
232
+ const right = this.parseAdditive();
189
233
  const following = this.peek();
190
234
  if (following?.type === "op" && following.text in comparisonHelpers) {
191
235
  throw new ExpressionError(`comparisons can't be chained (at '${following.text}'), use "and" to combine them`);
@@ -194,6 +238,49 @@ class Parser {
194
238
  return { kind: "call", name: comparisonHelpers[opToken.text], args: [left, right] };
195
239
  }
196
240
 
241
+ private parseAdditive(): Node {
242
+ return this.parseArithmetic(["+", "-"], () => this.parseMultiplicative());
243
+ }
244
+
245
+ private parseMultiplicative(): Node {
246
+ return this.parseArithmetic(["*", "/", "%"], () => this.parseUnary());
247
+ }
248
+
249
+ // Left-associative, so a - b - c is (a - b) - c
250
+ private parseArithmetic(ops: string[], parseOperand: () => Node): Node {
251
+ let left = parseOperand();
252
+ for (;;) {
253
+ let op: string;
254
+ const token = this.peek();
255
+ if (this.isOp(token, ...ops)) {
256
+ op = this.next().text;
257
+ if (!this.peek()) {
258
+ throw new ExpressionError(`expected a value after '${op}'`);
259
+ }
260
+ } else if (ops.includes("-") && token?.type === "value" && token.text.startsWith("-") && numberPattern.test(token.text)) {
261
+ // a -1 means a - 1. Split the negative number into the operator and the number.
262
+ op = "-";
263
+ this.tokens[this.pos] = { type: "value", text: token.text.slice(1) };
264
+ } else {
265
+ return left;
266
+ }
267
+ this.usedInfix = true;
268
+ left = { kind: "call", name: arithmeticHelpers[op], args: [left, parseOperand()] };
269
+ }
270
+ }
271
+
272
+ private parseUnary(): Node {
273
+ if (this.isOp(this.peek(), "-")) {
274
+ this.next();
275
+ if (!this.peek()) {
276
+ throw new ExpressionError("expected a value after '-'");
277
+ }
278
+ this.usedInfix = true;
279
+ return { kind: "call", name: "sub", args: [{ kind: "raw", text: "0" }, this.parseUnary()] };
280
+ }
281
+ return this.parsePrimary();
282
+ }
283
+
197
284
  private parsePrimary(): Node {
198
285
  const token = this.peek();
199
286
  if (token?.type === "ident" || token?.type === "value") {
@@ -247,34 +334,105 @@ function emit(node: Node): string {
247
334
  return `(${node.name} ${node.args.map(emit).join(" ")})`;
248
335
  }
249
336
 
250
- // Rewrites a single condition. Returns null if it doesn't use infix syntax.
251
- export function rewriteInfixCondition(condition: string): string | null {
252
- let tokens: Token[];
253
- try {
254
- tokens = tokenize(condition);
255
- } catch {
256
- // Leave anything we can't tokenize for Handlebars to report
257
- return null;
258
- }
259
- const hasOperators = tokens.some(t => t.type === "op");
260
- const parser = new Parser(tokens);
261
- let nodes: Node[];
337
+ // "value" is a whole expression whose value is used, e.g. the right-hand side of @set
338
+ type Mode = "condition" | "arguments" | "display" | "value";
339
+
340
+ // Parses `text` and returns the rewritten nodes, or null if it should be left alone: it
341
+ // doesn't use infix syntax, or it can't be parsed and has no operators (which leaves malformed
342
+ // prefix syntax for Handlebars to report).
343
+ function rewrite(text: string, mode: Mode, label: string): Node[] | null {
344
+ // Whether errors are always reported, and the result always returned, rather than leaving
345
+ // anything that isn't infix syntax for Handlebars
346
+ const strict = mode === "display" || mode === "value";
347
+ // Errors are thrown after the try/catch blocks, as new errors with the expression in the message
262
348
  let error: ExpressionError | null = null;
349
+ let tokens: Token[] = [];
263
350
  try {
264
- nodes = parser.parseCondition();
351
+ tokens = tokenize(text);
265
352
  } catch (e) {
266
- if (!hasOperators || !(e instanceof ExpressionError)) return null;
353
+ // Leave anything we can't tokenize for Handlebars to report, except {{= }}
354
+ if (!strict || !(e instanceof ExpressionError)) return null;
267
355
  error = e;
268
- nodes = [];
356
+ }
357
+ const hasOperators = tokens.some(t => t.type === "op");
358
+ const parser = new Parser(tokens);
359
+ let nodes: Node[] = [];
360
+ if (!error) {
361
+ try {
362
+ nodes = mode === "condition" ? parser.parseCondition()
363
+ : mode === "arguments" ? parser.parseArguments(1)
364
+ : [parser.parseExpression()];
365
+ } catch (e) {
366
+ if (!(e instanceof ExpressionError) || (!hasOperators && !strict)) return null;
367
+ error = e;
368
+ }
269
369
  }
270
370
  if (error) {
271
- throw new Error(`Invalid condition "${condition.trim()}": ${error.message}`);
371
+ throw new Error(`Invalid ${label} "${text.trim()}": ${error.message}`);
272
372
  }
273
- if (!parser.usedInfix) return null;
274
- return nodes.map(emit).join(" ");
373
+ if (!parser.usedInfix && !strict) return null;
374
+ return nodes;
375
+ }
376
+
377
+ // Rewrites a single condition. Returns null if it doesn't use infix syntax.
378
+ export function rewriteInfixCondition(condition: string): string | null {
379
+ const nodes = rewrite(condition, "condition", "condition");
380
+ return nodes && nodes.map(emit).join(" ");
275
381
  }
276
382
 
277
- const blockStart = /(\\*)\{\{(~?\s*)(#if|#unless|else\s+if|else\s+unless)(?=[\s(!])/g;
383
+ // Rewrites the arguments to {{set}}, {{inc}} or {{dec}}: an attribute name, then an expression.
384
+ // Returns null if the expression doesn't use infix syntax.
385
+ export function rewriteInfixArguments(args: string): string | null {
386
+ const nodes = rewrite(args, "arguments", "expression");
387
+ return nodes && nodes.map(emit).join(" ");
388
+ }
389
+
390
+ // Rewrites the expression in {{= expression}} into the contents of a mustache tag, i.e. a
391
+ // helper call without the outer parentheses, or an attribute name.
392
+ export function rewriteDisplayExpression(expression: string): string {
393
+ const node = rewrite(expression, "display", "expression")![0];
394
+ if (node.kind === "call") {
395
+ return `${node.name} ${node.args.map(emit).join(" ")}`;
396
+ }
397
+ if (literals.includes(node.text) || numberPattern.test(node.text) || /^["']/.test(node.text)) {
398
+ throw new Error(`Invalid expression "${expression.trim()}": expected an attribute or a calculation`);
399
+ }
400
+ return node.text;
401
+ }
402
+
403
+ // Rewrites an expression whose value is used (the right-hand side of @set and link setters, when a
404
+ // story uses expressions there) into a Handlebars value: a helper call in parentheses, an
405
+ // attribute name or a literal. Throws if it isn't a valid expression.
406
+ export function rewriteValueExpression(expression: string): string {
407
+ return emit(rewrite(expression, "value", "expression")![0]);
408
+ }
409
+
410
+ // Splits a list of link setters on the commas between them, but not on commas inside quotes or
411
+ // parentheses: greeting = "Hi, there", gold -= price is two setters.
412
+ export function splitSetters(setters: string): string[] {
413
+ const result: string[] = [];
414
+ let depth = 0;
415
+ let quote: string | null = null;
416
+ let start = 0;
417
+ for (let i = 0; i < setters.length; i++) {
418
+ const c = setters[i];
419
+ if (quote) {
420
+ if (c === "\\") i++;
421
+ else if (c === quote) quote = null;
422
+ }
423
+ else if (c === "\"" || c === "'") quote = c;
424
+ else if (c === "(") depth++;
425
+ else if (c === ")") depth = Math.max(0, depth - 1);
426
+ else if (c === "," && depth === 0) {
427
+ result.push(setters.slice(start, i));
428
+ start = i + 1;
429
+ }
430
+ }
431
+ result.push(setters.slice(start));
432
+ return result.map(s => s.trim()).filter(s => s !== "");
433
+ }
434
+
435
+ const tagStart = /(\\*)\{\{(~?\s*)(?:(#if|#unless|else\s+if|else\s+unless)(?=[\s(!])|(set|inc|dec)(?=\s)|(=))/g;
278
436
 
279
437
  // Finds the end of a mustache tag starting at `from`, skipping over quoted strings.
280
438
  // Returns the index of the closing "}}" (or "~}}"), or -1.
@@ -301,9 +459,9 @@ export function rewriteInfixExpressions(text: string): string {
301
459
 
302
460
  let result = "";
303
461
  let last = 0;
304
- blockStart.lastIndex = 0;
462
+ tagStart.lastIndex = 0;
305
463
  let match: RegExpExecArray | null;
306
- while ((match = blockStart.exec(text)) !== null) {
464
+ while ((match = tagStart.exec(text)) !== null) {
307
465
  // An odd number of backslashes escapes the mustache
308
466
  if (match[1].length % 2 === 1) continue;
309
467
 
@@ -311,13 +469,20 @@ export function rewriteInfixExpressions(text: string): string {
311
469
  const argEnd = findTagEnd(text, argStart);
312
470
  if (argEnd === -1) break;
313
471
 
314
- const condition = text.slice(argStart, argEnd);
315
- const rewritten = rewriteInfixCondition(condition);
316
- if (rewritten !== null) {
317
- result += text.slice(last, argStart) + " " + rewritten;
472
+ const args = text.slice(argStart, argEnd);
473
+ if (match[5]) {
474
+ // {{= expression}}: replace the "=" too
475
+ const tagOpen = match.index + match[1].length;
476
+ result += text.slice(last, tagOpen) + "{{" + match[2] + rewriteDisplayExpression(args);
318
477
  last = argEnd;
478
+ } else {
479
+ const rewritten = match[3] ? rewriteInfixCondition(args) : rewriteInfixArguments(args);
480
+ if (rewritten !== null) {
481
+ result += text.slice(last, argStart) + " " + rewritten;
482
+ last = argEnd;
483
+ }
319
484
  }
320
- blockStart.lastIndex = argEnd;
485
+ tagStart.lastIndex = argEnd;
321
486
  }
322
487
  return result + text.slice(last);
323
488
  }
package/src/numbers.ts ADDED
@@ -0,0 +1,21 @@
1
+ // The rules for turning attribute values into numbers, shared by everything that does arithmetic:
2
+ // the maths helpers ({{add}}, {{sub}} etc., which infix arithmetic is rewritten to), {{inc}} and
3
+ // {{dec}}, and @set's +=, -=, *= and /= (which @inc and @dec compile to).
4
+ //
5
+ // Attributes often hold numbers as text: values from user input, {{set "x" "5"}}, or JavaScript.
6
+ // So text that's a number counts as that number. A blank value (unset, null, false or "") counts
7
+ // as 0, so a counter can start from nothing. Anything else is an error, rather than giving NaN or
8
+ // joining text together.
9
+
10
+ export const isBlank = (v: unknown) => v === undefined || v === null || v === false || v === "";
11
+
12
+ export const isNumeric = (v: unknown) =>
13
+ typeof v === "number" || isBlank(v) || (typeof v === "string" && v.trim() !== "" && !isNaN(Number(v)));
14
+
15
+ // "what" names the operation in the error, e.g. "inc" gives: "inc" needs numbers, but was given "abc"
16
+ export function toNumber(what: string, v: unknown): number {
17
+ if (!isNumeric(v)) {
18
+ throw new Error(`"${what}" needs numbers, but was given ${JSON.stringify(v)}`);
19
+ }
20
+ return isBlank(v) ? 0 : Number(v);
21
+ }