plainscript-lang 0.1.7-latest

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +815 -0
  3. package/compiler/bundler.js +86 -0
  4. package/compiler/cli.js +843 -0
  5. package/compiler/dependency-detector.js +173 -0
  6. package/compiler/formatter.js +170 -0
  7. package/compiler/generator.js +2032 -0
  8. package/compiler/lexer.js +413 -0
  9. package/compiler/parser.js +2077 -0
  10. package/compiler/version.js +6 -0
  11. package/docs/PLINJS_SPEC.md +1051 -0
  12. package/docs/index.html +2287 -0
  13. package/docs/logo.jpg +0 -0
  14. package/docs/website/index.html +1500 -0
  15. package/docs/website/script.js +197 -0
  16. package/docs/website/style.css +1117 -0
  17. package/examples/arrays.pln +13 -0
  18. package/examples/cache-and-jobs.pln +29 -0
  19. package/examples/database.pln +41 -0
  20. package/examples/day2.pln +7 -0
  21. package/examples/day3.pln +11 -0
  22. package/examples/deployment.pln +12 -0
  23. package/examples/email-send.pln +22 -0
  24. package/examples/expressions.pln +40 -0
  25. package/examples/football-backend/app.pln +90 -0
  26. package/examples/hello.pln +3 -0
  27. package/examples/id-verification/app.pln +29 -0
  28. package/examples/id-verification/make-sample-id.js +123 -0
  29. package/examples/loops.pln +17 -0
  30. package/examples/objects.pln +12 -0
  31. package/examples/rest-api-fetch.pln +94 -0
  32. package/examples/rest-api.pln +68 -0
  33. package/examples/scheduled-tasks.pln +23 -0
  34. package/examples/server.pln +25 -0
  35. package/examples/start.pln +2 -0
  36. package/examples/stdlib.pln +41 -0
  37. package/examples/telegram-bot.pln +42 -0
  38. package/examples/web-app.pln +20 -0
  39. package/examples/websocket-server.pln +27 -0
  40. package/examples/whatsapp-bot/pairing.pln +17 -0
  41. package/examples/whatsapp-bot/qr.pln +8 -0
  42. package/package.json +47 -0
@@ -0,0 +1,2077 @@
1
+ // Parser: converts a token stream into an AST (Abstract Syntax Tree).
2
+
3
+ const { TOKEN } = require('./lexer');
4
+
5
+ // Statement-starting PlainScript keywords, used for "did you mean?" suggestions.
6
+ const STATEMENT_KEYWORDS = [
7
+ 'remember', 'show', 'if', 'make', 'give',
8
+ 'for', 'while', 'use', 'import', 'when', 'listen', 'reply', 'serve',
9
+ 'web', 'route', 'start', 'database', 'query', 'insert', 'update', 'delete', 'execute',
10
+ 'ask', 'javascript', 'bot', 'ocr', 'try', 'recover', 'retry',
11
+ ];
12
+
13
+ // Number words used by the numbered item expression (v1.1):
14
+ // player one from players → players[0]
15
+ // player two from players → players[1]
16
+ // Zero-based indexing is never exposed to the programmer.
17
+ const NUMBER_WORDS = {
18
+ one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7,
19
+ eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13,
20
+ fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18,
21
+ nineteen: 19, twenty: 20,
22
+ };
23
+
24
+ // HTTP methods accepted by the route statement (v2.1.0). Lowercase only —
25
+ // PlainScript keywords are lowercase by convention.
26
+ const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
27
+
28
+ // Time units accepted by the "every <n> <unit>" statement, in milliseconds
29
+ // (used by the generator to build the interval directly).
30
+ const TIME_UNITS = {
31
+ second: 1000, seconds: 1000,
32
+ minute: 60 * 1000, minutes: 60 * 1000,
33
+ hour: 60 * 60 * 1000, hours: 60 * 60 * 1000,
34
+ day: 24 * 60 * 60 * 1000, days: 24 * 60 * 60 * 1000,
35
+ };
36
+
37
+ // v2.1.0 — split raw SQL into placeholder-free text and ordered parameter
38
+ // names. "{name}" marks a bound parameter; the generator renders "?" for
39
+ // SQLite or "$1…" for PostgreSQL.
40
+ function extractSqlParams(rawSql) {
41
+ const params = [];
42
+ const sql = String(rawSql).replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => {
43
+ params.push(name);
44
+ return '?';
45
+ });
46
+ return { sql, params };
47
+ }
48
+
49
+ // v2.1.1 — parse an upload size limit such as "5 MB", "512 KB", "1GB" or
50
+ // "100B" into a byte count. Returns null when the text is not a valid size.
51
+ const UPLOAD_SIZE_UNITS = { b: 1, kb: 1024, mb: 1024 * 1024, gb: 1024 * 1024 * 1024 };
52
+ function parseUploadSize(text) {
53
+ const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i.exec(String(text).trim());
54
+ if (!match) return null;
55
+ return Math.round(parseFloat(match[1]) * UPLOAD_SIZE_UNITS[match[2].toLowerCase()]);
56
+ }
57
+
58
+ // Returns the Levenshtein edit distance between two strings.
59
+ function levenshtein(a, b) {
60
+ const m = a.length, n = b.length;
61
+ const dp = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]);
62
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
63
+ for (let i = 1; i <= m; i++) {
64
+ for (let j = 1; j <= n; j++) {
65
+ dp[i][j] = a[i - 1] === b[j - 1]
66
+ ? dp[i - 1][j - 1]
67
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
68
+ }
69
+ }
70
+ return dp[m][n];
71
+ }
72
+
73
+ // Returns the closest keyword within edit distance 2, or null.
74
+ function closestKeyword(word) {
75
+ let best = null, bestDist = Infinity;
76
+ for (const kw of STATEMENT_KEYWORDS) {
77
+ const d = levenshtein(word.toLowerCase(), kw);
78
+ if (d < bestDist) { bestDist = d; best = kw; }
79
+ }
80
+ return bestDist <= 2 ? best : null;
81
+ }
82
+
83
+ // Format an error message with position info from a token when available.
84
+ function makeError(message, token) {
85
+ if (token && token.line) {
86
+ return `Line ${token.line}, Column ${token.col}: ${message}`;
87
+ }
88
+ return message;
89
+ }
90
+
91
+ function parse(tokens) {
92
+ let pos = 0;
93
+
94
+ function peek() { return tokens[pos]; }
95
+ function peekAt(offset) { return tokens[pos + offset] || { type: TOKEN.EOF }; }
96
+ function advance() { return tokens[pos++]; }
97
+
98
+ function consume(expectedType, hint) {
99
+ const token = tokens[pos];
100
+ if (token.type !== expectedType) {
101
+ throw new Error(makeError(
102
+ hint || `Expected ${expectedType} but got "${token.value || token.type}".`,
103
+ token
104
+ ));
105
+ }
106
+ return advance();
107
+ }
108
+
109
+ // ── Condition parsing ───────────────────────────────────────────────────────
110
+ //
111
+ // v2.1.1 grammar (outermost first):
112
+ // condition := andCondition ("or" andCondition)*
113
+ // andCondition:= notCondition ("and" notCondition)*
114
+ // notCondition:= "not" notCondition | comparison
115
+ // comparison := the single-comparison forms below
116
+ //
117
+ // Node shapes produced by the comparison level:
118
+ // BinaryCondition { type, left, op, right } — left op right
119
+ // UnaryCondition { type, left, op } — left is empty / is not empty
120
+ // BetweenCondition { type, left, low, high } — left between low and high
121
+ // StringCondition { type, left, method, right } — left contains/startsWith/endsWith right
122
+ // plus LogicalCondition { type, op: "and"|"or", left, right } and
123
+ // { type, op: "not", operand } from the combinator levels.
124
+
125
+ // Entry point used by if/while.
126
+ function parseCondition() {
127
+ let left = parseAndCondition();
128
+ while (peek().type === TOKEN.OR) {
129
+ advance();
130
+ const right = parseAndCondition();
131
+ left = { type: 'LogicalCondition', op: 'or', left, right };
132
+ }
133
+ return left;
134
+ }
135
+
136
+ function parseAndCondition() {
137
+ let left = parseNotCondition();
138
+ while (peek().type === TOKEN.AND) {
139
+ advance();
140
+ const right = parseNotCondition();
141
+ left = { type: 'LogicalCondition', op: 'and', left, right };
142
+ }
143
+ return left;
144
+ }
145
+
146
+ function parseNotCondition() {
147
+ if (peek().type === TOKEN.NOT) {
148
+ advance();
149
+ return { type: 'LogicalCondition', op: 'not', operand: parseNotCondition() };
150
+ }
151
+ return parseComparisonCondition();
152
+ }
153
+
154
+ function parseComparisonCondition() {
155
+ const left = parseExpression();
156
+
157
+ // ── Non-"is" operators ──────────────────────────────────────────────────
158
+ if (peek().type === TOKEN.CONTAINS) {
159
+ advance();
160
+ const right = parseExpression();
161
+ return { type: 'StringCondition', left, method: 'includes', right };
162
+ }
163
+
164
+ if (peek().type === TOKEN.STARTS) {
165
+ advance();
166
+ consume(TOKEN.WITH, makeError('Expected "with" after "starts". Use: starts with', peek()));
167
+ const right = parseExpression();
168
+ return { type: 'StringCondition', left, method: 'startsWith', right };
169
+ }
170
+
171
+ if (peek().type === TOKEN.ENDS) {
172
+ advance();
173
+ consume(TOKEN.WITH, makeError('Expected "with" after "ends". Use: ends with', peek()));
174
+ const right = parseExpression();
175
+ return { type: 'StringCondition', left, method: 'endsWith', right };
176
+ }
177
+
178
+ if (peek().type === TOKEN.BETWEEN) {
179
+ advance();
180
+ const low = parseExpression();
181
+ consume(TOKEN.AND, makeError('Expected "and" after the lower bound in "between" expression.\n\nExample:\n if x between 1 and 10', peek()));
182
+ const high = parseExpression();
183
+ return { type: 'BetweenCondition', left, low, high };
184
+ }
185
+
186
+ // ── "is ..." comparisons ────────────────────────────────────────────────
187
+ const isToken = peek();
188
+ consume(TOKEN.IS, makeError(
189
+ 'Expected a comparison after the value. Use "is", "is above", "is below", "contains", "starts with", etc.',
190
+ isToken
191
+ ));
192
+
193
+ // is not empty / is not <expr>
194
+ if (peek().type === TOKEN.NOT) {
195
+ advance();
196
+ if (peek().type === TOKEN.EMPTY) {
197
+ advance();
198
+ return { type: 'UnaryCondition', left, op: 'isNotEmpty' };
199
+ }
200
+ const right = parseExpression();
201
+ return { type: 'BinaryCondition', left, op: '!==', right };
202
+ }
203
+
204
+ // is empty
205
+ if (peek().type === TOKEN.EMPTY) {
206
+ advance();
207
+ return { type: 'UnaryCondition', left, op: 'isEmpty' };
208
+ }
209
+
210
+ // is above (alias: >)
211
+ if (peek().type === TOKEN.ABOVE) {
212
+ advance();
213
+ const right = parseExpression();
214
+ return { type: 'BinaryCondition', left, op: '>', right };
215
+ }
216
+
217
+ // is below (alias: <)
218
+ if (peek().type === TOKEN.BELOW) {
219
+ advance();
220
+ const right = parseExpression();
221
+ return { type: 'BinaryCondition', left, op: '<', right };
222
+ }
223
+
224
+ // is at least (>=) / is at most (<=)
225
+ if (peek().type === TOKEN.AT) {
226
+ advance();
227
+ if (peek().type === TOKEN.LEAST) {
228
+ advance();
229
+ const right = parseExpression();
230
+ return { type: 'BinaryCondition', left, op: '>=', right };
231
+ }
232
+ if (peek().type === TOKEN.MOST) {
233
+ advance();
234
+ const right = parseExpression();
235
+ return { type: 'BinaryCondition', left, op: '<=', right };
236
+ }
237
+ throw new Error(makeError('Expected "least" or "most" after "at". Use: is at least / is at most', peek()));
238
+ }
239
+
240
+ // is greater than
241
+ if (peek().type === TOKEN.GREATER) {
242
+ advance();
243
+ consume(TOKEN.THAN, 'Expected "than" after "greater". Use: is greater than');
244
+ const right = parseExpression();
245
+ return { type: 'BinaryCondition', left, op: '>', right };
246
+ }
247
+
248
+ // is less than
249
+ if (peek().type === TOKEN.LESS) {
250
+ advance();
251
+ consume(TOKEN.THAN, 'Expected "than" after "less". Use: is less than');
252
+ const right = parseExpression();
253
+ return { type: 'BinaryCondition', left, op: '<', right };
254
+ }
255
+
256
+ // is <expr> (equality)
257
+ const right = parseExpression();
258
+ return { type: 'BinaryCondition', left, op: '===', right };
259
+ }
260
+
261
+ // ── Statements ─────────────────────────────────────────────────────────────
262
+
263
+ function parseStatement() {
264
+ const token = peek();
265
+
266
+ if (token.type === TOKEN.REMEMBER) return parseRemember();
267
+ if (token.type === TOKEN.SHOW) return parseShow();
268
+ if (token.type === TOKEN.IF) return parseIf();
269
+ if (token.type === TOKEN.MAKE) return parseMake();
270
+ if (token.type === TOKEN.GIVE) return parseGive();
271
+ if (token.type === TOKEN.FOR) return parseForEach();
272
+ // v2.1.0 — every <n> <unit>s … done: interval scheduling. "every" also
273
+ // lexes as TOKEN.EACH (the "for every" alias), so only the number+unit
274
+ // form is intercepted; "for every item in list" keeps its meaning.
275
+ if (token.type === TOKEN.EACH && peekAt(1).type === TOKEN.NUMBER &&
276
+ peekAt(2).type === TOKEN.IDENTIFIER && TIME_UNITS[peekAt(2).value]) {
277
+ return parseEvery();
278
+ }
279
+ if (token.type === TOKEN.WHILE) return parseWhile();
280
+ if (token.type === TOKEN.USE) return parseUse();
281
+ if (token.type === TOKEN.IMPORT) return parseImport();
282
+ if (token.type === TOKEN.WHEN) return parseWhen();
283
+ if (token.type === TOKEN.LISTEN) return parseListen();
284
+ if (token.type === TOKEN.REPLY) return parseReply();
285
+ if (token.type === TOKEN.SERVE) return parseServeFolder();
286
+ // v1.1.1 — JavaScript Gateway
287
+ if (token.type === TOKEN.ASK) return parseAsk();
288
+ if (token.type === TOKEN.JAVASCRIPT_KW) return parseJavaScriptBlock();
289
+ // v2.0.1 — OCR capability
290
+ if (token.type === TOKEN.OCR_KW) return parseOcr();
291
+ // v0.6
292
+ if (token.type === TOKEN.WEB) return parseWebApp();
293
+ if (token.type === TOKEN.ROUTE_KW) return parseSimpleRoute();
294
+ if (token.type === TOKEN.START_KW) return parseStart();
295
+ if (token.type === TOKEN.DATABASE_KW) return parseDatabase();
296
+ // v2.1.0 — query("field"): the HTTP query-string accessor. The SQLite
297
+ // block form keeps priority when "query" stands alone on a line; a
298
+ // call form is always the accessor.
299
+ if (token.type === TOKEN.QUERY_KW && peekAt(1).type === TOKEN.LPAREN) {
300
+ return { type: 'ExpressionStatement', expression: parseCallExpression() };
301
+ }
302
+ if (token.type === TOKEN.QUERY_KW) return parseSqlBlock('query', 'QueryStatement');
303
+ if (token.type === TOKEN.INSERT_KW) return parseSqlBlock('insert', 'InsertStatement');
304
+ if (token.type === TOKEN.UPDATE_KW) return parseSqlBlock('update', 'UpdateStatement');
305
+ // v2.1.1 — delete "<url>" is an HTTP DELETE request; a bare "delete"
306
+ // starting a raw block keeps its SQL meaning.
307
+ if (token.type === TOKEN.DELETE_KW && tokenStartsValue(peekAt(1))) {
308
+ return { type: 'ExpressionStatement', expression: parseHttpCall('delete') };
309
+ }
310
+ if (token.type === TOKEN.DELETE_KW) return parseSqlBlock('delete', 'DeleteStatement');
311
+ if (token.type === TOKEN.EXECUTE_KW) return parseSqlBlock('execute', 'ExecuteStatement');
312
+
313
+ if (token.type === TOKEN.EOF) return null;
314
+
315
+ // Statements starting with an identifier: call, becomes, index/member becomes
316
+ if (token.type === TOKEN.IDENTIFIER) {
317
+ // v1.2 — bot "<token>" / bot <expr>: creates the polling Telegram bot.
318
+ // Bound to BOT by the generator's `bot` stdlib. Only intercepts when a
319
+ // value follows; bot(...) calls and ordinary identifiers (e.g. a
320
+ // variable named bot) keep their normal meaning.
321
+ const nextIsValue =
322
+ peekAt(1).type === TOKEN.STRING || peekAt(1).type === TOKEN.NUMBER ||
323
+ peekAt(1).type === TOKEN.IDENTIFIER ||
324
+ peekAt(1).type === TOKEN.LBRACKET || peekAt(1).type === TOKEN.LBRACE;
325
+ if (token.value === 'bot' && nextIsValue) return parseBot();
326
+
327
+ // v2.1.0 — allow cors: enables CORS middleware on the current app.
328
+ // Contextual (not a reserved keyword): a variable named "allow" keeps
329
+ // its ordinary meaning.
330
+ if (token.value === 'allow' &&
331
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'cors') {
332
+ advance(); // allow
333
+ advance(); // cors
334
+ return { type: 'AllowCorsStatement' };
335
+ }
336
+
337
+ // v2.1.0 — group "<prefix>" ... done: composes routes under a shared
338
+ // path prefix. Contextual like "bot": only intercepted when a quoted
339
+ // prefix follows.
340
+ if (token.value === 'group' && peekAt(1).type === TOKEN.STRING) {
341
+ advance(); // group
342
+ const prefix = advance().value; // consume STRING
343
+ const body = parseBody('"group" block');
344
+ return { type: 'GroupStatement', prefix, body };
345
+ }
346
+
347
+ // v2.1.0 — postgres "<connection>": binds the PostgreSQL driver.
348
+ // Contextual: a variable named "postgres" keeps its meaning unless a
349
+ // connection value follows on the same line.
350
+ if (token.value === 'postgres' && (
351
+ peekAt(1).type === TOKEN.STRING || peekAt(1).type === TOKEN.IDENTIFIER ||
352
+ peekAt(1).type === TOKEN.LPAREN || peekAt(1).type === TOKEN.TEMPLATE_STRING)) {
353
+ return parsePostgres();
354
+ }
355
+
356
+ // v2.1.0 — cache "<redis-url>" / cache env("REDIS_URL"): connects the
357
+ // shared Redis client used by cacheGet / cacheSet / cacheDelete.
358
+ // Contextual like "postgres": a variable named "cache" keeps its
359
+ // meaning unless a connection value follows on the same line.
360
+ if (token.value === 'cache' && (
361
+ peekAt(1).type === TOKEN.STRING || peekAt(1).type === TOKEN.TEMPLATE_STRING ||
362
+ peekAt(1).type === TOKEN.IDENTIFIER || peekAt(1).type === TOKEN.LPAREN)) {
363
+ advance(); // cache
364
+ const url = parseExpression();
365
+ return { type: 'CacheStatement', url };
366
+ }
367
+
368
+ // v2.1.0 — transaction … done: groups database writes atomically.
369
+ // Contextual: "transaction becomes x" and "transaction(...)" keep
370
+ // their ordinary variable/function meanings.
371
+ if (token.value === 'transaction' &&
372
+ peekAt(1).type !== TOKEN.BECOMES && peekAt(1).type !== TOKEN.LPAREN) {
373
+ advance(); // transaction
374
+ const body = parseBody('"transaction" block');
375
+ return { type: 'TransactionStatement', body };
376
+ }
377
+
378
+ // v2.1.0 — mail transport … done: configures the outgoing mailer.
379
+ if (token.value === 'mail' &&
380
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'transport') {
381
+ advance(); // mail
382
+ advance(); // transport
383
+ return { type: 'MailTransportStatement', options: parsePropertyList('"mail transport" block') };
384
+ }
385
+
386
+ // v2.1.0 — send mail … done: sends one email through the transport.
387
+ if (token.value === 'send' &&
388
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'mail') {
389
+ advance(); // send
390
+ advance(); // mail
391
+ return { type: 'SendMailStatement', fields: parsePropertyList('"send mail" block') };
392
+ }
393
+
394
+ // v2.1.0 — every <n> <unit>s … done: repeat work on an interval.
395
+ // ("every" lexes as TOKEN.EACH — see the EACH dispatch above — so this
396
+ // identifier-form branch only guards against future lexer changes.)
397
+ if (token.value === 'every' && peekAt(1).type === TOKEN.NUMBER &&
398
+ peekAt(2).type === TOKEN.IDENTIFIER && TIME_UNITS[peekAt(2).value]) {
399
+ return parseEvery();
400
+ }
401
+
402
+ // v2.1.0 — schedule "<cron>" … done: run work on a cron schedule.
403
+ if (token.value === 'schedule' && peekAt(1).type === TOKEN.STRING) {
404
+ advance(); // schedule
405
+ const expression = advance().value; // cron string
406
+ const body = parseBody('"schedule" block');
407
+ return { type: 'ScheduleStatement', expression, body };
408
+ }
409
+
410
+ // v2.1.0 — run background <call>: fire-and-forget execution.
411
+ if (token.value === 'run' &&
412
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'background') {
413
+ advance(); // run
414
+ advance(); // background
415
+ const call = parsePrimary();
416
+ if (call.type !== 'CallExpression') {
417
+ throw new Error(makeError(
418
+ 'Expected a function call after "run background".\n\nExample:\n run background resizeImage("photo.png")',
419
+ peek()
420
+ ));
421
+ }
422
+ return { type: 'RunBackgroundStatement', call };
423
+ }
424
+
425
+ // v2.1.0 — websocket server on <port> … done: realtime endpoint.
426
+ if (token.value === 'websocket' &&
427
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'server') {
428
+ return parseWebSocketServer();
429
+ }
430
+
431
+ // v2.1.1 — whatsapp bot … done: WhatsApp bot runtime (Baileys under
432
+ // the hood). Contextual: a variable named "whatsapp" keeps its meaning;
433
+ // only "whatsapp bot" opens the block.
434
+ if (token.value === 'whatsapp' &&
435
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'bot') {
436
+ return parseWhatsAppBot();
437
+ }
438
+
439
+ // v2.1.1 — log message: prints the normalized message record inside an
440
+ // "on message" handler. Generation rejects it everywhere else with a
441
+ // teaching error.
442
+ if (token.value === 'log' &&
443
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'message') {
444
+ advance(); // log
445
+ advance(); // message
446
+ return { type: 'WhatsAppLogStatement' };
447
+ }
448
+
449
+ // v2.1.0 — broadcast <expr>: sends to every connected socket.
450
+ if (token.value === 'broadcast') {
451
+ advance(); // broadcast
452
+ const value = parseExpression();
453
+ return { type: 'BroadcastStatement', value };
454
+ }
455
+
456
+ // v2.1.0 — send socket <expr>: replies to one connected socket.
457
+ if (token.value === 'send' &&
458
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'socket') {
459
+ advance(); // send
460
+ advance(); // socket
461
+ const value = parseExpression();
462
+ return { type: 'SendSocketStatement', value };
463
+ }
464
+
465
+ // v2.1.0 — status 404 / status <expr>: sets the HTTP response status.
466
+ // Contextual: "status becomes 404" is still a normal reassignment of a
467
+ // variable named "status", and "status(...)" remains a function call.
468
+ if (token.value === 'status' && peekAt(1).type !== TOKEN.BECOMES &&
469
+ (peekAt(1).type === TOKEN.NUMBER || peekAt(1).type === TOKEN.STRING ||
470
+ peekAt(1).type === TOKEN.TEMPLATE_STRING ||
471
+ peekAt(1).type === TOKEN.IDENTIFIER)) {
472
+ advance(); // status
473
+ const value = parseExpression();
474
+ return { type: 'StatusStatement', value };
475
+ }
476
+
477
+ // ── v2.1.1 statements (all contextual, following the v2.1.0 pattern) ──
478
+
479
+ // try … [recover [as <name>]] … done: deterministic error handling.
480
+ // "try(...)" calls and "try becomes x" keep their ordinary meaning.
481
+ if (token.value === 'try' &&
482
+ peekAt(1).type !== TOKEN.LPAREN && peekAt(1).type !== TOKEN.BECOMES) {
483
+ return parseTryStatement();
484
+ }
485
+
486
+ // wait for <value>: await an async operation as a statement.
487
+ if (token.value === 'wait' && peekAt(1).type === TOKEN.FOR) {
488
+ advance(); // wait
489
+ advance(); // for
490
+ return { type: 'ExpressionStatement', expression: { type: 'AwaitExpression', value: parseUnary() } };
491
+ }
492
+
493
+ // retry <n> times [every <n> seconds] … done
494
+ if (token.value === 'retry' && peekAt(1).type === TOKEN.NUMBER) {
495
+ return parseRetry();
496
+ }
497
+
498
+ // accept uploads [limit "<size>"] [allow ["mime", ...]] [folder "<dir>"]
499
+ if (token.value === 'accept' &&
500
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'uploads') {
501
+ return parseAcceptUploads();
502
+ }
503
+
504
+ // require api key from <expr>: rejects requests without a valid key.
505
+ if (token.value === 'require' &&
506
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'api') {
507
+ return parseRequireApiKey();
508
+ }
509
+
510
+ // enable sessions <secret>: signed-cookie sessions on the current app.
511
+ if (token.value === 'enable' &&
512
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'sessions') {
513
+ advance(); // enable
514
+ advance(); // sessions
515
+ return { type: 'EnableSessionsStatement', secret: parseExpression() };
516
+ }
517
+
518
+ // destroy session: clears the current session (inside a route).
519
+ if (token.value === 'destroy' &&
520
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'session') {
521
+ advance(); // destroy
522
+ advance(); // session
523
+ return { type: 'DestroySessionStatement' };
524
+ }
525
+
526
+ // set cookie "<name>" to <expr> [expires in <n> <unit>] / clear cookie "<name>"
527
+ if (token.value === 'set' &&
528
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'cookie') {
529
+ return parseSetCookie();
530
+ }
531
+ if (token.value === 'clear' &&
532
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'cookie') {
533
+ advance(); // clear
534
+ advance(); // cookie
535
+ const name = consume(TOKEN.STRING,
536
+ 'Expected a cookie name string after "clear cookie".\n\nExample:\n clear cookie "theme"').value;
537
+ return { type: 'ClearCookieStatement', name };
538
+ }
539
+
540
+ // limit requests to <n> per <unit>: rate limiting middleware.
541
+ if (token.value === 'limit' &&
542
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'requests') {
543
+ return parseRateLimit();
544
+ }
545
+
546
+ // google oauth … done: explicit Google OAuth 2.0 semantics.
547
+ if (token.value === 'google' &&
548
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'oauth') {
549
+ advance(); // google
550
+ advance(); // oauth
551
+ return { type: 'GoogleOAuthStatement', options: parsePropertyList('"google oauth" block') };
552
+ }
553
+
554
+ const expr = parsePrimary();
555
+
556
+ if (peek().type === TOKEN.BECOMES) {
557
+ advance();
558
+ const value = parseExpression();
559
+ return { type: 'BecomeStatement', target: expr, value };
560
+ }
561
+
562
+ if (expr.type === 'CallExpression' ||
563
+ expr.type === 'AddCall' ||
564
+ expr.type === 'RemoveCall' ||
565
+ expr.type === 'WriteCall' ||
566
+ expr.type === 'HttpCall' ||
567
+ expr.type === 'AwaitExpression') {
568
+ return { type: 'ExpressionStatement', expression: expr };
569
+ }
570
+
571
+ const word = expr.type === 'Identifier' ? expr.name : token.value;
572
+ const suggestion = closestKeyword(word);
573
+ if (suggestion) {
574
+ throw new Error(makeError(
575
+ `Unknown keyword "${word}". Did you mean "${suggestion}"?`,
576
+ token
577
+ ));
578
+ }
579
+ throw new Error(makeError(
580
+ `Unexpected word "${word}". This is not a valid statement in PlainScript.`,
581
+ token
582
+ ));
583
+ }
584
+
585
+ throw new Error(makeError(`Unexpected keyword "${token.value}".`, token));
586
+ }
587
+
588
+ // remember <name> as <value>
589
+ // remember <name> as\n <key> is <val>\n...\ndone (object literal)
590
+ // remember <name> as javascript\n <raw JS>\ndone (v1.1.1 JavaScript block)
591
+ function parseRemember() {
592
+ consume(TOKEN.REMEMBER);
593
+ const name = consume(
594
+ TOKEN.IDENTIFIER,
595
+ 'Expected a variable name after "remember".\n\nExample:\n remember age as 16'
596
+ ).value;
597
+ consume(
598
+ TOKEN.AS,
599
+ 'Expected keyword "as" after the variable name.\n\nExample:\n remember age as 16'
600
+ );
601
+
602
+ // JavaScript block: remember <name> as javascript … done
603
+ if (peek().type === TOKEN.JAVASCRIPT_KW) {
604
+ advance(); // consume javascript
605
+ const bodyToken = peek();
606
+ if (bodyToken.type !== TOKEN.JS_BODY) {
607
+ throw new Error(makeError(
608
+ 'Expected a JavaScript block after "javascript".\n\nExample:\n remember result as javascript\n await axios.get(url)\n done',
609
+ bodyToken
610
+ ));
611
+ }
612
+ const body = advance().value; // consume JS_BODY
613
+ consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
614
+ return { type: 'JavaScriptBlock', name, body };
615
+ }
616
+
617
+ // v2.1.0 — remember <name> as query|insert|update|delete … done
618
+ // Captures the SQL result: rows for "query", the run info (changes /
619
+ // lastInsertRowid) for the write forms. The call form query("field")
620
+ // is the HTTP accessor and still parses as an expression below.
621
+ if (
622
+ [TOKEN.QUERY_KW, TOKEN.INSERT_KW, TOKEN.UPDATE_KW, TOKEN.DELETE_KW, TOKEN.EXECUTE_KW]
623
+ .includes(peek().type) && peekAt(1).type === TOKEN.SQL_BODY
624
+ ) {
625
+ const kindToken = advance();
626
+ const kind = kindToken.value;
627
+ const sql = advance().value; // consume SQL_BODY
628
+ consume(TOKEN.DONE, `Expected "done" to close the "${kind}" block.`);
629
+ return { type: 'RememberSqlStatement', name, kind, ...extractSqlParams(sql) };
630
+ }
631
+
632
+ // Object literal: next token is IDENTIFIER followed by IS
633
+ if (peek().type === TOKEN.IDENTIFIER && peekAt(1).type === TOKEN.IS) {
634
+ return { type: 'RememberStatement', name, value: parseObjectLiteral() };
635
+ }
636
+
637
+ const value = parseExpression();
638
+ return { type: 'RememberStatement', name, value };
639
+ }
640
+
641
+ // ask <variable>
642
+ // ask "<prompt>" as <variable>
643
+ function parseAsk() {
644
+ consume(TOKEN.ASK);
645
+ if (peek().type === TOKEN.STRING) {
646
+ const prompt = advance().value;
647
+ consume(TOKEN.AS,
648
+ 'Expected "as" after the prompt.\n\nExample:\n ask "What is your name?" as name');
649
+ const variable = consume(TOKEN.IDENTIFIER,
650
+ 'Expected a variable name after "as".\n\nExample:\n ask "What is your name?" as name').value;
651
+ return { type: 'AskStatement', prompt, variable };
652
+ }
653
+ const variable = consume(TOKEN.IDENTIFIER,
654
+ 'Expected a variable name after "ask".\n\nExample:\n ask name').value;
655
+ return { type: 'AskStatement', variable };
656
+ }
657
+
658
+ // javascript\n <raw JS>\ndone — statement-level JavaScript block.
659
+ // Mirrors the `remember <name> as javascript` form but produces no value.
660
+ function parseJavaScriptBlock() {
661
+ consume(TOKEN.JAVASCRIPT_KW);
662
+ const bodyToken = peek();
663
+ if (bodyToken.type !== TOKEN.JS_BODY) {
664
+ throw new Error(makeError(
665
+ 'Expected a JavaScript block after "javascript".\n\nExample:\n javascript\n console.log("hi")\n done',
666
+ bodyToken
667
+ ));
668
+ }
669
+ const body = advance().value; // consume JS_BODY
670
+ consume(TOKEN.DONE, 'Expected "done" to close the JavaScript block.');
671
+ return { type: 'JavaScriptBlock', name: null, body };
672
+ }
673
+
674
+ // v2.0.1 — OCR capability.
675
+ //
676
+ // ocr "<image>" as <variable>
677
+ // ocr "<image>" as <variable> using "<lang>"
678
+ //
679
+ // Extracts text from an image into a variable (mirrors `ask ... as name`).
680
+ // The optional `using "<lang>"` selects a Tesseract language pack such as
681
+ // "eng", "deu", or "deu+eng"; it defaults to "eng".
682
+ function parseOcr() {
683
+ consume(TOKEN.OCR_KW);
684
+ const image = parseExpression();
685
+ consume(TOKEN.AS,
686
+ 'Expected "as <name>" after the image in an ocr statement.\n\nExamples:\n ocr "scan.png" as text\n ocr "scan.png" as text using "deu"'
687
+ );
688
+ const variable = consume(TOKEN.IDENTIFIER,
689
+ 'Expected a variable name after "as".\n\nExample:\n ocr "scan.png" as text'
690
+ ).value;
691
+ let lang = null;
692
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'using') {
693
+ advance(); // consume using
694
+ lang = consume(TOKEN.STRING,
695
+ 'Expected a language string after "using".\n\nExample:\n ocr "scan.png" as text using "deu"'
696
+ ).value;
697
+ }
698
+ return { type: 'OcrStatement', image, variable, lang };
699
+ }
700
+
701
+ function parseShow() {
702
+ consume(TOKEN.SHOW);
703
+ // Support both keyword form (show "text") and call form (show("text")).
704
+ // A "(" after "show" only means a call when the matching ")" ends the
705
+ // expression; otherwise it is a grouped value like show (2 + 3) * 4.
706
+ if (peek().type === TOKEN.LPAREN && !groupContinuesAfterMatch()) {
707
+ advance(); // consume (
708
+ const value = parseExpression();
709
+ consume(TOKEN.RPAREN, 'Expected ")" to close "show" call.');
710
+ return { type: 'ShowStatement', value };
711
+ }
712
+ const value = parseExpression();
713
+ return { type: 'ShowStatement', value };
714
+ }
715
+
716
+ // From the current "(" token, find its matching ")". Returns true when the
717
+ // expression continues after the match (operator or postfix), meaning the
718
+ // parenthesised group is part of a larger expression.
719
+ function groupContinuesAfterMatch() {
720
+ let depth = 0;
721
+ for (let i = pos; i < tokens.length; i++) {
722
+ const t = tokens[i];
723
+ if (t.type === TOKEN.LPAREN) depth++;
724
+ else if (t.type === TOKEN.RPAREN) {
725
+ depth--;
726
+ if (depth === 0) {
727
+ const after = tokens[i + 1];
728
+ if (!after || after.type === TOKEN.EOF) return false;
729
+ return (
730
+ after.type === TOKEN.STAR || after.type === TOKEN.SLASH ||
731
+ after.type === TOKEN.PERCENT || after.type === TOKEN.PLUS ||
732
+ after.type === TOKEN.MINUS || after.type === TOKEN.LBRACKET ||
733
+ after.type === TOKEN.DOT ||
734
+ (after.type === TOKEN.IDENTIFIER &&
735
+ ['of', 'length', 'above', 'below', 'contains', 'matches', 'becomes'].includes(after.value))
736
+ );
737
+ }
738
+ }
739
+ }
740
+ return false;
741
+ }
742
+
743
+ // make name(params) ... done
744
+ function parseMake() {
745
+ consume(TOKEN.MAKE);
746
+ const name = consume(
747
+ TOKEN.IDENTIFIER,
748
+ 'Expected a function name after "make".\n\nExample:\n make greet()\n show "Hello"\n done'
749
+ ).value;
750
+ consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
751
+ const params = parseParamList();
752
+ consume(TOKEN.RPAREN, 'Expected ")" to close the parameter list.');
753
+ const body = parseBody(`function "${name}"`);
754
+ return { type: 'FunctionDeclaration', name, params, body };
755
+ }
756
+
757
+ function parseParamList() {
758
+ const params = [];
759
+ if (peek().type === TOKEN.RPAREN) return params;
760
+ params.push(consume(TOKEN.IDENTIFIER, 'Expected a parameter name.').value);
761
+ while (peek().type === TOKEN.COMMA) {
762
+ advance();
763
+ params.push(consume(TOKEN.IDENTIFIER, 'Expected a parameter name after ",".').value);
764
+ }
765
+ return params;
766
+ }
767
+
768
+ function parseGive() {
769
+ consume(TOKEN.GIVE);
770
+ const value = parseExpression();
771
+ return { type: 'GiveStatement', value };
772
+ }
773
+
774
+ // for each <item> in <collection> ... done
775
+ // for every <item> in <collection> ... done (alias — "every" maps to EACH token)
776
+ function parseForEach() {
777
+ consume(TOKEN.FOR);
778
+ consume(TOKEN.EACH,
779
+ 'Expected "each" or "every" after "for".\n\nExample:\n for each item in players\n show item\n done');
780
+ const item = consume(TOKEN.IDENTIFIER, 'Expected an item name after "each" or "every".').value;
781
+ consume(TOKEN.IN, `Expected "in" after "${item}".\n\nExample:\n for each item in players`);
782
+ const collection = parseExpression();
783
+ const body = parseBody('"for each" loop');
784
+ return { type: 'ForEachStatement', item, collection, body };
785
+ }
786
+
787
+ // while <condition> ... done
788
+ function parseWhile() {
789
+ consume(TOKEN.WHILE);
790
+ const condition = parseCondition();
791
+ const body = parseBody('"while" loop');
792
+ return { type: 'WhileStatement', condition, body };
793
+ }
794
+
795
+ // import "./file.pln"
796
+ function parseImport() {
797
+ consume(TOKEN.IMPORT);
798
+ const filePath = consume(
799
+ TOKEN.STRING,
800
+ 'Expected a file path string after "import".\n\nExample:\n import "./math.pln"'
801
+ ).value;
802
+ return { type: 'ImportStatement', path: filePath };
803
+ }
804
+
805
+ // use <module> — side-effect or canonical binding
806
+ // use <module> as <name> — bind the package to a custom variable name
807
+ // <module> may carry a version range: use left-pad@^1.3.0
808
+ function parseUse() {
809
+ consume(TOKEN.USE);
810
+ const token = peek();
811
+ if (token.type !== TOKEN.PACKAGE && token.type !== TOKEN.IDENTIFIER) {
812
+ throw new Error(makeError(
813
+ 'Expected a module name after "use".\n\nExamples:\n use express\n use node-fetch as fetch\n use left-pad@^1.3.0',
814
+ token
815
+ ));
816
+ }
817
+ advance();
818
+ let alias = null;
819
+ if (peek().type === TOKEN.AS) {
820
+ advance(); // consume "as"
821
+ alias = consume(TOKEN.IDENTIFIER,
822
+ 'Expected a variable name after "as".\n\nExample:\n use node-fetch as fetch'
823
+ ).value;
824
+ }
825
+ return { type: 'UseStatement', module: token.value, alias };
826
+ }
827
+
828
+ // when someone visits "<path>" ... done → Express route
829
+ // when someone sends "<command>" ... done → Telegram command handler
830
+ // when someone sends matching "<pattern>" ... done
831
+ // when someone clicks "<data>" ... done → Telegram callback handler
832
+ // when socket connects|sends message|disconnects → v2.1.0 websocket handlers
833
+ function parseWhen() {
834
+ consume(TOKEN.WHEN);
835
+
836
+ // v2.1.1 — "when nothing matches … done" registers the 404 catch-all.
837
+ // It must appear after every route in the source; the generated handler
838
+ // keeps that position.
839
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'nothing') {
840
+ advance(); // nothing
841
+ const matchesToken = peek();
842
+ if (matchesToken.type !== TOKEN.IDENTIFIER || matchesToken.value !== 'matches') {
843
+ throw new Error(makeError(
844
+ 'Expected "matches" after "when nothing".\n\nExample:\n when nothing matches\n status 404\n reply "Not found"\n done',
845
+ matchesToken
846
+ ));
847
+ }
848
+ advance(); // matches
849
+ const body = parseBody('"when nothing matches" block');
850
+ return { type: 'NotFoundStatement', body };
851
+ }
852
+
853
+ // v2.1.0 — socket handlers inside a "websocket server" block come first:
854
+ // they read "when socket …", not "when someone …".
855
+ const whenToken = peek();
856
+ if (whenToken.type === TOKEN.IDENTIFIER && whenToken.value === 'socket') {
857
+ return parseSocketHandler();
858
+ }
859
+
860
+ consume(TOKEN.SOMEONE,
861
+ 'Expected "someone" after "when".\n\nExample:\n when someone visits "/"\n reply "Hello"\n done');
862
+ const next = peek();
863
+
864
+ if (next.type === TOKEN.VISITS) return parseRouteBody();
865
+
866
+ if (next.type === TOKEN.IDENTIFIER && next.value === 'sends') {
867
+ advance();
868
+ return parseTelegramCommand();
869
+ }
870
+
871
+ if (next.type === TOKEN.IDENTIFIER && next.value === 'clicks') {
872
+ advance();
873
+ return parseTelegramCallback();
874
+ }
875
+
876
+ throw new Error(makeError(
877
+ 'Expected "visits", "sends", or "clicks" after "when someone".\n\nExamples:\n when someone visits "/"\n when someone sends "/start"\n when someone clicks "about"',
878
+ next
879
+ ));
880
+ }
881
+
882
+ // v2.1.0 — socket handlers inside a "websocket server" block:
883
+ // when socket connects … done
884
+ // when socket sends message … done
885
+ // when socket disconnects … done
886
+ function parseSocketHandler() {
887
+ advance(); // socket
888
+ const event = peek();
889
+ if (event.type !== TOKEN.IDENTIFIER ||
890
+ !['connects', 'sends', 'disconnects'].includes(event.value)) {
891
+ throw new Error(makeError(
892
+ 'Expected "connects", "sends message", or "disconnects" after "when socket".',
893
+ event
894
+ ));
895
+ }
896
+ const kind = event.value;
897
+ advance(); // event word
898
+
899
+ if (kind === 'sends') {
900
+ const payload = peek();
901
+ if (payload.type === TOKEN.IDENTIFIER && payload.value === 'message') {
902
+ advance(); // optional word "message" naming the payload
903
+ } else if (payload.type !== TOKEN.DONE) {
904
+ throw new Error(makeError(
905
+ 'Expected the word "message" after "when socket sends".\n\nExample:\n when socket sends message\n send socket message\n done',
906
+ payload
907
+ ));
908
+ }
909
+ const body = parseBody('"when socket sends message" block');
910
+ return { type: 'SocketMessageStatement', body };
911
+ }
912
+
913
+ const body = parseBody(`"when socket ${kind}" block`);
914
+ return kind === 'connects'
915
+ ? { type: 'SocketConnectStatement', body }
916
+ : { type: 'SocketDisconnectStatement', body };
917
+ }
918
+
919
+ // Parses the route body after `when someone visits "<path>"`.
920
+ function parseRouteBody() {
921
+ consume(TOKEN.VISITS,
922
+ 'Expected "visits" after "someone".\n\nExample:\n when someone visits "/"');
923
+ const routePath = consume(TOKEN.STRING,
924
+ 'Expected a route path string after "visits".\n\nExample:\n when someone visits "/"').value;
925
+ const body = parseBody('route');
926
+ return { type: 'RouteStatement', path: routePath, body };
927
+ }
928
+
929
+ // when someone sends "<command>" ... done
930
+ // when someone sends matching "<pattern>" ... done
931
+ function parseTelegramCommand() {
932
+ let isPattern = false;
933
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'matching') {
934
+ isPattern = true;
935
+ advance();
936
+ }
937
+ const command = consume(TOKEN.STRING,
938
+ isPattern
939
+ ? 'Expected a pattern string after "matching".\n\nExample:\n when someone sends matching "/echo (.+)"'
940
+ : 'Expected a command string after "sends".\n\nExample:\n when someone sends "/start"\n reply "Hello"\n done').value;
941
+ const body = parseBody('"when someone sends" block');
942
+ return { type: 'TelegramCommandStatement', command, isPattern, body };
943
+ }
944
+
945
+ // when someone clicks "<data>" ... done
946
+ function parseTelegramCallback() {
947
+ const data = consume(TOKEN.STRING,
948
+ 'Expected a button name string after "clicks".\n\nExample:\n when someone clicks "about"\n reply "About PlainScript"\n done').value;
949
+ const body = parseBody('"when someone clicks" block');
950
+ return { type: 'TelegramCallbackStatement', data, body };
951
+ }
952
+
953
+ // listen on <port> ... done
954
+ function parseListen() {
955
+ consume(TOKEN.LISTEN);
956
+ consume(TOKEN.ON,
957
+ 'Expected "on" after "listen".\n\nExample:\n listen on 3000\n show "Running"\n done');
958
+ const port = parseExpression();
959
+ const body = parseBody('"listen" block');
960
+ return { type: 'ListenStatement', port, body };
961
+ }
962
+
963
+ // reply <expr>
964
+ // reply json\n <key> is <val>\n...\ndone
965
+ function parseReply() {
966
+ consume(TOKEN.REPLY);
967
+ if (peek().type === TOKEN.JSON_KW) {
968
+ advance(); // consume json
969
+ const properties = [];
970
+ while (peek().type !== TOKEN.DONE) {
971
+ if (peek().type === TOKEN.EOF) {
972
+ throw new Error(makeError(
973
+ 'Expected keyword "done" to close "reply json" block before end of file.',
974
+ peek()
975
+ ));
976
+ }
977
+ const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
978
+ consume(TOKEN.IS, `Expected "is" after property name "${key}".`);
979
+ const value = parseExpression();
980
+ properties.push({ key, value });
981
+ }
982
+ advance(); // consume DONE
983
+ return { type: 'ReplyJsonStatement', properties };
984
+ }
985
+ const value = parseExpression();
986
+
987
+ // reply <value> with buttons ... done → Telegram inline keyboard block.
988
+ if (peek().type === TOKEN.WITH &&
989
+ peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'buttons') {
990
+ advance(); // with
991
+ advance(); // buttons
992
+ const buttons = parseButtonBlock();
993
+ return { type: 'ReplyWithButtonsStatement', value, buttons };
994
+ }
995
+
996
+ return { type: 'ReplyStatement', value };
997
+ }
998
+
999
+ // Inline keyboard rows inside a "reply ... with buttons ... done" block.
1000
+ // Each line is one button; a comma joins buttons on the same line into one
1001
+ // row; a blank line between button lines starts a new row.
1002
+ function parseButtonBlock() {
1003
+ const rows = [];
1004
+ let currentRow = [];
1005
+ let prevLine = null;
1006
+ while (peek().type !== TOKEN.DONE) {
1007
+ if (peek().type === TOKEN.EOF) {
1008
+ throw new Error(makeError(
1009
+ 'Expected "done" to close the buttons block before end of file.',
1010
+ peek()
1011
+ ));
1012
+ }
1013
+ if (currentRow.length > 0 && prevLine !== null && peek().line > prevLine + 1) {
1014
+ rows.push(currentRow);
1015
+ currentRow = [];
1016
+ }
1017
+ const text = consume(TOKEN.STRING,
1018
+ 'Expected a button label string inside the buttons block.\n\nExample:\n reply "Choose" with buttons\n "About" -> "about"\n done');
1019
+ consume(TOKEN.ARROW,
1020
+ 'Expected "->" after the button label.\n\nExample:\n "About" -> "about"');
1021
+ const data = consume(TOKEN.STRING,
1022
+ 'Expected a callback string after "->".\n\nExample:\n "About" -> "about"');
1023
+ currentRow.push({ text: text.value, data: data.value });
1024
+ prevLine = data.line;
1025
+ if (peek().type === TOKEN.COMMA) advance();
1026
+ }
1027
+ if (currentRow.length > 0) rows.push(currentRow);
1028
+ advance(); // consume DONE
1029
+ return rows;
1030
+ }
1031
+
1032
+ // serve folder "<path>"
1033
+ function parseServeFolder() {
1034
+ consume(TOKEN.SERVE);
1035
+ consume(TOKEN.FOLDER,
1036
+ 'Expected "folder" after "serve".\n\nExample:\n serve folder "public"');
1037
+ const folder = consume(TOKEN.STRING,
1038
+ 'Expected a folder path string after "serve folder".\n\nExample:\n serve folder "public"').value;
1039
+ return { type: 'ServeFolderStatement', folder };
1040
+ }
1041
+
1042
+ // ── v0.6 — Express DX ──────────────────────────────────────────────────────
1043
+
1044
+ // web app
1045
+ function parseWebApp() {
1046
+ consume(TOKEN.WEB);
1047
+ const appToken = peek();
1048
+ if (appToken.type !== TOKEN.IDENTIFIER || appToken.value !== 'app') {
1049
+ throw new Error(makeError(
1050
+ 'Expected "app" after "web".\n\nExample:\n web app', appToken
1051
+ ));
1052
+ }
1053
+ advance(); // consume "app"
1054
+ return { type: 'WebAppStatement' };
1055
+ }
1056
+
1057
+ // route "<path>" ... done → GET route (v0.6 form)
1058
+ // route get|post|put|patch|delete "<path>" ... done → v2.1.0 method routes
1059
+ function parseSimpleRoute() {
1060
+ consume(TOKEN.ROUTE_KW);
1061
+ // Optional HTTP method word before the path string. The plain form keeps
1062
+ // its v0.6 meaning (GET), so existing programs compile unchanged.
1063
+ // "delete" lexes as the SQL keyword token (DELETE_KW), so both spellings
1064
+ // of that one method are accepted.
1065
+ let method = 'get';
1066
+ const methodToken = peek();
1067
+ const methodWord = methodToken.type === TOKEN.IDENTIFIER ? methodToken.value
1068
+ : methodToken.type === TOKEN.DELETE_KW ? 'delete'
1069
+ : null;
1070
+ if (
1071
+ methodWord &&
1072
+ HTTP_METHODS.includes(methodWord) &&
1073
+ peekAt(1).type === TOKEN.STRING
1074
+ ) {
1075
+ method = methodWord;
1076
+ advance(); // method word
1077
+ }
1078
+ const routePath = consume(TOKEN.STRING,
1079
+ 'Expected a route path after "route".\n\nExample:\n route "/"\n reply "Hello"\n done').value;
1080
+ const body = parseBody('route');
1081
+ return { type: 'SimpleRouteStatement', method, path: routePath, body };
1082
+ }
1083
+
1084
+ // bot "<token>" / bot env("BOT_TOKEN")
1085
+ // Creates the polling Telegram bot and binds it to BOT (v1.2). The token
1086
+ // argument may be any expression — the token literal is never required to
1087
+ // appear in source, and the runtime falls back to TELEGRAM_BOT_TOKEN.
1088
+ function parseBot() {
1089
+ advance(); // consume "bot"
1090
+ const token = parseExpression();
1091
+ return { type: 'ExpressionStatement', expression: { type: 'CallExpression', name: 'bot', args: [token] } };
1092
+ }
1093
+
1094
+ // start <port>
1095
+ // start telegram bot — explicit Telegram startup marker. Polling keeps
1096
+ // the bot alive, so this form is only for documentation/intent.
1097
+ function parseStart() {
1098
+ consume(TOKEN.START_KW);
1099
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'telegram') {
1100
+ advance();
1101
+ const botToken = peek();
1102
+ if (botToken.type !== TOKEN.IDENTIFIER || botToken.value !== 'bot') {
1103
+ throw new Error(makeError(
1104
+ 'Expected "bot" after "telegram".\n\nExample:\n start telegram bot',
1105
+ botToken
1106
+ ));
1107
+ }
1108
+ advance();
1109
+ return { type: 'TelegramStartStatement' };
1110
+ }
1111
+ const port = parseExpression();
1112
+ return { type: 'StartStatement', port };
1113
+ }
1114
+
1115
+ // ── v0.6 — SQLite DX ───────────────────────────────────────────────────────
1116
+
1117
+ // database "<file>" [using "<driver>"]
1118
+ //
1119
+ // v2.1.1 — the optional driver selects the SQLite engine without changing
1120
+ // any other PlainScript database semantics:
1121
+ // "native" — better-sqlite3 (requires a working native binding)
1122
+ // "wasm" — sql.js WebAssembly build (runs anywhere Node runs)
1123
+ // The default ("auto") tries native first and falls back to the wasm
1124
+ // engine when the native binding is unavailable on this platform.
1125
+ function parseDatabase() {
1126
+ consume(TOKEN.DATABASE_KW);
1127
+ const file = consume(TOKEN.STRING,
1128
+ 'Expected a database file path after "database".\n\nExample:\n database "app.db"').value;
1129
+ let driver = null;
1130
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'using') {
1131
+ advance(); // using
1132
+ driver = consume(TOKEN.STRING,
1133
+ 'Expected a driver name after "using".\n\nDrivers: "native", "wasm"\n\nExample:\n database "app.db" using "wasm"').value;
1134
+ if (!['native', 'wasm'].includes(driver)) {
1135
+ throw new Error(makeError(
1136
+ `Unknown SQLite driver "${driver}". Available drivers: "native", "wasm".`,
1137
+ peek()
1138
+ ));
1139
+ }
1140
+ }
1141
+ return { type: 'DatabaseStatement', file, driver };
1142
+ }
1143
+
1144
+ // v2.1.0 — postgres "<connection-string>": binds the PostgreSQL pool to
1145
+ // "db". SQL statements afterwards compile to async pool queries.
1146
+ function parsePostgres() {
1147
+ // "postgres" is contextual: only a declaration when followed by a value.
1148
+ advance(); // postgres
1149
+ const connection = parseExpression();
1150
+ return { type: 'PostgresStatement', connection };
1151
+ }
1152
+
1153
+ // query/insert/update/delete/execute SQL_BODY DONE
1154
+ //
1155
+ // v2.1.0 — the raw SQL may reference PlainScript variables with {name}
1156
+ // placeholders. They are extracted at parse time and replaced: SQLite gets
1157
+ // anonymous "?" markers, PostgreSQL numbered "$1…" markers (the generator
1158
+ // decides). Values are always passed as bound parameters — never spliced
1159
+ // into the SQL text.
1160
+ function parseSqlBlock(keyword, nodeType) {
1161
+ advance(); // consume the keyword token (QUERY_KW, INSERT_KW, etc.)
1162
+ const sqlToken = peek();
1163
+ if (sqlToken.type !== TOKEN.SQL_BODY) {
1164
+ throw new Error(makeError(
1165
+ `Expected a SQL block after "${keyword}".\n\nExample:\n ${keyword}\n SELECT * FROM users\n done`,
1166
+ sqlToken
1167
+ ));
1168
+ }
1169
+ const rawSql = advance().value; // consume SQL_BODY
1170
+ consume(TOKEN.DONE, `Expected "done" to close the "${keyword}" block.`);
1171
+ return { type: nodeType, ...extractSqlParams(rawSql) };
1172
+ }
1173
+
1174
+ // ── v2.1.1 — error handling, retries and backend middleware ───────────────
1175
+
1176
+ // try … [recover [as <name>]] … done
1177
+ function parseTryStatement() {
1178
+ advance(); // try
1179
+ const tryBody = [];
1180
+ while (!(peek().type === TOKEN.DONE ||
1181
+ (peek().type === TOKEN.IDENTIFIER && peek().value === 'recover'))) {
1182
+ if (peek().type === TOKEN.EOF) {
1183
+ throw new Error(makeError(
1184
+ 'Expected keyword "done" to close the "try" block before end of file.',
1185
+ peek()
1186
+ ));
1187
+ }
1188
+ const stmt = parseStatement();
1189
+ if (stmt) tryBody.push(stmt);
1190
+ }
1191
+ let catchName = null;
1192
+ let recoverBody = null;
1193
+ if (peek().type !== TOKEN.DONE) {
1194
+ advance(); // recover
1195
+ if (peek().type === TOKEN.AS) {
1196
+ advance();
1197
+ catchName = consume(TOKEN.IDENTIFIER,
1198
+ 'Expected a variable name after "recover as".\n\nExample:\n recover as error').value;
1199
+ }
1200
+ recoverBody = [];
1201
+ while (peek().type !== TOKEN.DONE) {
1202
+ if (peek().type === TOKEN.EOF) {
1203
+ throw new Error(makeError(
1204
+ 'Expected keyword "done" to close the "recover" block before end of file.',
1205
+ peek()
1206
+ ));
1207
+ }
1208
+ const stmt = parseStatement();
1209
+ if (stmt) recoverBody.push(stmt);
1210
+ }
1211
+ }
1212
+ advance(); // done
1213
+ return { type: 'TryStatement', tryBody, catchName, recoverBody };
1214
+ }
1215
+
1216
+ // retry <n> times [every <n> seconds] … done
1217
+ function parseRetry() {
1218
+ advance(); // retry
1219
+ const attemptsToken = advance(); // NUMBER
1220
+ if (attemptsToken.type !== TOKEN.NUMBER || attemptsToken.value < 1) {
1221
+ throw new Error(makeError(
1222
+ 'The number of retries must be a number of at least 1.\n\nExample:\n retry 3 times',
1223
+ attemptsToken
1224
+ ));
1225
+ }
1226
+ const timesToken = peek();
1227
+ if (timesToken.type !== TOKEN.IDENTIFIER || timesToken.value !== 'times') {
1228
+ throw new Error(makeError(
1229
+ 'Expected "times" after the number of retries.\n\nExample:\n retry 3 times',
1230
+ timesToken
1231
+ ));
1232
+ }
1233
+ advance(); // times
1234
+ let delaySeconds = 1;
1235
+ // ("every" lexes as the EACH keyword.)
1236
+ if ((peek().type === TOKEN.IDENTIFIER && peek().value === 'every') ||
1237
+ (peek().type === TOKEN.EACH && peek().value === 'every')) {
1238
+ advance(); // every
1239
+ const count = advance();
1240
+ // 0 seconds is allowed: it means "retry immediately".
1241
+ if (count.type !== TOKEN.NUMBER || count.value < 0) {
1242
+ throw new Error(makeError(
1243
+ 'Expected a number of seconds (0 or more) after "every".\n\nExample:\n retry 3 times every 5 seconds',
1244
+ count
1245
+ ));
1246
+ }
1247
+ const unit = peek();
1248
+ if (unit.type !== TOKEN.IDENTIFIER || !/^seconds?$/.test(unit.value)) {
1249
+ throw new Error(makeError(
1250
+ 'Expected "seconds" or "second" after the delay in "retry".\n\nExample:\n retry 3 times every 5 seconds',
1251
+ unit
1252
+ ));
1253
+ }
1254
+ advance(); // unit
1255
+ delaySeconds = count.value;
1256
+ }
1257
+ const body = parseBody('"retry" block');
1258
+ return { type: 'RetryStatement', attempts: attemptsToken.value, delaySeconds, body };
1259
+ }
1260
+
1261
+ // accept uploads [limit "<size>"] [allow ["mime", ...]] [folder "<dir>"]
1262
+ function parseAcceptUploads() {
1263
+ advance(); // accept
1264
+ advance(); // uploads
1265
+ let limitBytes = null;
1266
+ let mimes = null;
1267
+ let folder = null;
1268
+ while (true) {
1269
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'limit' && limitBytes === null) {
1270
+ advance(); // limit
1271
+ const sizeToken = consume(TOKEN.STRING,
1272
+ 'Expected a size limit string after "limit".\n\nExamples:\n accept uploads limit "5 MB"\n accept uploads limit "512 KB"');
1273
+ limitBytes = parseUploadSize(sizeToken.value);
1274
+ if (limitBytes === null) {
1275
+ throw new Error(makeError(
1276
+ `Invalid upload size ${JSON.stringify(sizeToken.value)}. Use a number with a unit: B, KB, MB or GB.\n\nExample:\n accept uploads limit "5 MB"`,
1277
+ sizeToken
1278
+ ));
1279
+ }
1280
+ continue;
1281
+ }
1282
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'allow' && mimes === null) {
1283
+ advance(); // allow
1284
+ const list = parseArrayLiteral();
1285
+ for (const element of list.elements) {
1286
+ if (element.type !== 'StringLiteral') {
1287
+ throw new Error(makeError(
1288
+ 'MIME types in "accept uploads allow [...]" must be strings.\n\nExample:\n accept uploads allow ["image/png", "image/jpeg"]',
1289
+ peek()
1290
+ ));
1291
+ }
1292
+ }
1293
+ mimes = list.elements.map(element => element.value);
1294
+ continue;
1295
+ }
1296
+ // ("folder" lexes as the FOLDER keyword, so both token shapes count.)
1297
+ if ((peek().type === TOKEN.FOLDER ||
1298
+ (peek().type === TOKEN.IDENTIFIER && peek().value === 'folder')) && folder === null) {
1299
+ advance(); // folder
1300
+ folder = consume(TOKEN.STRING,
1301
+ 'Expected a folder path string after "folder".\n\nExample:\n accept uploads folder "uploads"').value;
1302
+ continue;
1303
+ }
1304
+ break;
1305
+ }
1306
+ return { type: 'AcceptUploadsStatement', limitBytes, mimes, folder };
1307
+ }
1308
+
1309
+ // require api key from <expr>
1310
+ function parseRequireApiKey() {
1311
+ const startToken = advance(); // require
1312
+ const apiToken = advance();
1313
+ if (apiToken.type !== TOKEN.IDENTIFIER || apiToken.value !== 'api') {
1314
+ throw new Error(makeError('Expected "api key from <key>" after "require".', apiToken));
1315
+ }
1316
+ const keyToken = peek();
1317
+ if (keyToken.type !== TOKEN.IDENTIFIER || keyToken.value !== 'key') {
1318
+ throw new Error(makeError(
1319
+ 'Expected "key" after "require api".\n\nExample:\n require api key from env("API_KEY")',
1320
+ keyToken
1321
+ ));
1322
+ }
1323
+ advance(); // key
1324
+ const fromToken = peek();
1325
+ if (fromToken.type !== TOKEN.IDENTIFIER || fromToken.value !== 'from') {
1326
+ throw new Error(makeError(
1327
+ 'Expected "from" before the key value.\n\nExample:\n require api key from env("API_KEY")',
1328
+ fromToken
1329
+ ));
1330
+ }
1331
+ advance(); // from
1332
+ const key = parseExpression();
1333
+ return { type: 'RequireApiKeyStatement', key };
1334
+ }
1335
+
1336
+ // set cookie "<name>" to <expr> [expires in <n> seconds|minutes|hours|days]
1337
+ function parseSetCookie() {
1338
+ advance(); // set
1339
+ advance(); // cookie
1340
+ const name = consume(TOKEN.STRING,
1341
+ 'Expected a cookie name string after "set cookie".\n\nExample:\n set cookie "theme" to "dark"').value;
1342
+ const toToken = peek();
1343
+ if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
1344
+ throw new Error(makeError(
1345
+ 'Expected "to" after the cookie name.\n\nExample:\n set cookie "theme" to "dark"',
1346
+ toToken
1347
+ ));
1348
+ }
1349
+ advance(); // to
1350
+ const value = parseExpression();
1351
+ let maxAgeSeconds = null;
1352
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'expires') {
1353
+ advance(); // expires
1354
+ // ("in" lexes as the IN keyword.)
1355
+ const inToken = peek();
1356
+ if (inToken.type !== TOKEN.IN) {
1357
+ throw new Error(makeError(
1358
+ 'Expected "in" after "expires".\n\nExample:\n set cookie "theme" to "dark" expires in 7 days',
1359
+ inToken
1360
+ ));
1361
+ }
1362
+ advance(); // in
1363
+ const count = advance();
1364
+ if (count.type !== TOKEN.NUMBER || count.value <= 0) {
1365
+ throw new Error(makeError(
1366
+ 'Expected a positive number after "expires in".\n\nExample:\n set cookie "theme" to "dark" expires in 7 days',
1367
+ count
1368
+ ));
1369
+ }
1370
+ const unit = peek();
1371
+ if (unit.type !== TOKEN.IDENTIFIER || !TIME_UNITS[unit.value]) {
1372
+ throw new Error(makeError(
1373
+ 'Expected a time unit after the number in "expires in".\n\nUnits: seconds, minutes, hours, days\n\nExample:\n set cookie "theme" to "dark" expires in 7 days',
1374
+ unit
1375
+ ));
1376
+ }
1377
+ advance(); // unit
1378
+ maxAgeSeconds = Math.round(count.value * TIME_UNITS[unit.value] / 1000);
1379
+ }
1380
+ return { type: 'SetCookieStatement', name, value, maxAgeSeconds };
1381
+ }
1382
+
1383
+ // limit requests to <n> per seconds|minutes|hours
1384
+ function parseRateLimit() {
1385
+ advance(); // limit
1386
+ advance(); // requests
1387
+ const toToken = peek();
1388
+ if (toToken.type !== TOKEN.IDENTIFIER || toToken.value !== 'to') {
1389
+ throw new Error(makeError(
1390
+ 'Expected "to" after "limit requests".\n\nExample:\n limit requests to 100 per minute',
1391
+ toToken
1392
+ ));
1393
+ }
1394
+ advance(); // to
1395
+ const maxToken = advance();
1396
+ if (maxToken.type !== TOKEN.NUMBER || maxToken.value < 1) {
1397
+ throw new Error(makeError(
1398
+ 'Expected a positive number of requests.\n\nExample:\n limit requests to 100 per minute',
1399
+ maxToken
1400
+ ));
1401
+ }
1402
+ const perToken = peek();
1403
+ if (perToken.type !== TOKEN.IDENTIFIER || perToken.value !== 'per') {
1404
+ throw new Error(makeError(
1405
+ 'Expected "per" before the time window.\n\nExample:\n limit requests to 100 per minute',
1406
+ perToken
1407
+ ));
1408
+ }
1409
+ advance(); // per
1410
+ const unit = advance();
1411
+ if (unit.type !== TOKEN.IDENTIFIER ||
1412
+ !['second', 'seconds', 'minute', 'minutes', 'hour', 'hours'].includes(unit.value)) {
1413
+ throw new Error(makeError(
1414
+ 'Expected a time unit after "per".\n\nUnits: second(s), minute(s), hour(s)\n\nExample:\n limit requests to 100 per minute',
1415
+ unit
1416
+ ));
1417
+ }
1418
+ return { type: 'RateLimitStatement', max: maxToken.value, windowMs: TIME_UNITS[unit.value] };
1419
+ }
1420
+
1421
+ // ── Conditions ─────────────────────────────────────────────────────────────
1422
+
1423
+ function parseIf() {
1424
+ consume(TOKEN.IF);
1425
+ const condition = parseCondition();
1426
+
1427
+ const consequent = [];
1428
+ while (peek().type !== TOKEN.OTHERWISE && peek().type !== TOKEN.DONE) {
1429
+ if (peek().type === TOKEN.EOF) {
1430
+ throw new Error(makeError(
1431
+ 'Expected keyword "done" before end of file to close the "if" block.',
1432
+ peek()
1433
+ ));
1434
+ }
1435
+ const stmt = parseStatement();
1436
+ if (stmt) consequent.push(stmt);
1437
+ }
1438
+
1439
+ let alternate = null;
1440
+ if (peek().type === TOKEN.OTHERWISE) {
1441
+ advance();
1442
+ alternate = [];
1443
+ while (peek().type !== TOKEN.DONE) {
1444
+ if (peek().type === TOKEN.EOF) {
1445
+ throw new Error(makeError(
1446
+ 'Expected keyword "done" before end of file to close the "otherwise" block.',
1447
+ peek()
1448
+ ));
1449
+ }
1450
+ const stmt = parseStatement();
1451
+ if (stmt) alternate.push(stmt);
1452
+ }
1453
+ }
1454
+
1455
+ advance(); // consume DONE
1456
+ return { type: 'IfStatement', condition, consequent, alternate };
1457
+ }
1458
+
1459
+ // ── Shared helpers ──────────────────────────────────────────────────────────
1460
+
1461
+ function parseBody(context) {
1462
+ const body = [];
1463
+ while (peek().type !== TOKEN.DONE) {
1464
+ if (peek().type === TOKEN.EOF) {
1465
+ throw new Error(makeError(
1466
+ `Expected keyword "done" to close the ${context} before end of file.`,
1467
+ peek()
1468
+ ));
1469
+ }
1470
+ const stmt = parseStatement();
1471
+ if (stmt) body.push(stmt);
1472
+ }
1473
+ advance(); // consume DONE
1474
+ return body;
1475
+ }
1476
+
1477
+ // ── Expressions ────────────────────────────────────────────────────────────
1478
+
1479
+ // v2.1.1 — full arithmetic precedence:
1480
+ // additive := term (("+" | "-") term)*
1481
+ // multiplicative ("term") := unary (("*" | "/" | "%") unary)*
1482
+ // unary := "-" unary | "wait for" unary | primary
1483
+ // primary := atom with postfix chains (indexing, members, of, length)
1484
+ function parseExpression() {
1485
+ let left = parseTerm();
1486
+ while (peek().type === TOKEN.PLUS || peek().type === TOKEN.MINUS) {
1487
+ const operator = advance().value;
1488
+ const right = parseTerm();
1489
+ left = { type: 'BinaryExpression', operator, left, right };
1490
+ }
1491
+ return left;
1492
+ }
1493
+
1494
+ function parseTerm() {
1495
+ let left = parseUnary();
1496
+ while (
1497
+ peek().type === TOKEN.STAR ||
1498
+ peek().type === TOKEN.SLASH ||
1499
+ peek().type === TOKEN.PERCENT
1500
+ ) {
1501
+ const operator = advance().value;
1502
+ const right = parseUnary();
1503
+ left = { type: 'BinaryExpression', operator, left, right };
1504
+ }
1505
+ return left;
1506
+ }
1507
+
1508
+ function parseUnary() {
1509
+ if (peek().type === TOKEN.MINUS) {
1510
+ advance();
1511
+ return { type: 'UnaryExpression', operator: '-', operand: parseUnary() };
1512
+ }
1513
+ // v2.1.1 — await semantics: "wait for <value>" awaits an async operation.
1514
+ // The operand binds tightly (a full postfix chain), so
1515
+ // "wait for loadUser(id) + 1" means "(await loadUser(id)) + 1".
1516
+ // ("for" lexes as the FOR keyword, not an identifier.)
1517
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'wait' &&
1518
+ peekAt(1).type === TOKEN.FOR) {
1519
+ advance(); // wait
1520
+ advance(); // for
1521
+ return { type: 'AwaitExpression', value: parseUnary() };
1522
+ }
1523
+ return parsePrimary();
1524
+ }
1525
+
1526
+ // primary → itemExpr | atom (postfix)*
1527
+ function parsePrimary() {
1528
+ const item = tryParseItemExpression();
1529
+ if (item) return item;
1530
+ let node = parseAtom();
1531
+ while (true) {
1532
+ if (peek().type === TOKEN.LBRACKET) {
1533
+ advance();
1534
+ const index = parseExpression();
1535
+ consume(TOKEN.RBRACKET, 'Expected "]" to close the index.');
1536
+ node = { type: 'IndexExpression', object: node, index };
1537
+ } else if (peek().type === TOKEN.DOT) {
1538
+ advance();
1539
+ const property = consume(TOKEN.IDENTIFIER, 'Expected a property name after ".".').value;
1540
+ node = { type: 'MemberExpression', object: node, property };
1541
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'of') {
1542
+ if (node.type !== 'Identifier') {
1543
+ throw new Error(makeError(
1544
+ 'Expected a property name before "of".\n\nExample:\n name of user',
1545
+ peek()
1546
+ ));
1547
+ }
1548
+ advance();
1549
+ const object = parsePrimary();
1550
+ node = { type: 'OfExpression', property: node, object };
1551
+ } else if (peek().type === TOKEN.IDENTIFIER && peek().value === 'length') {
1552
+ advance();
1553
+ node = { type: 'LengthExpression', object: node };
1554
+ } else {
1555
+ break;
1556
+ }
1557
+ }
1558
+ return node;
1559
+ }
1560
+
1561
+ // v1.1 — Item expressions, detected before parseAtom:
1562
+ // first player from players → players[0]
1563
+ // last player from players → players[players.length - 1]
1564
+ // player one from players → players[0]
1565
+ // Shape: three identifiers, the third being "from".
1566
+ function tryParseItemExpression() {
1567
+ const first = peek();
1568
+ const second = peekAt(1);
1569
+ const third = peekAt(2);
1570
+ if (first.type !== TOKEN.IDENTIFIER) return null;
1571
+ if (second.type !== TOKEN.IDENTIFIER) return null;
1572
+ if (third.type !== TOKEN.IDENTIFIER) return null;
1573
+
1574
+ // "first from players" / "last from players" — missing noun
1575
+ if ((first.value === 'first' || first.value === 'last') && second.value === 'from') {
1576
+ throw new Error(makeError(
1577
+ `Expected a noun after "${first.value}".\n\nExample:\n ${first.value} player from players`,
1578
+ second
1579
+ ));
1580
+ }
1581
+
1582
+ if (third.value !== 'from') return null;
1583
+
1584
+ if (first.value === 'first') {
1585
+ advance(); // first
1586
+ advance(); // noun
1587
+ advance(); // from
1588
+ const collection = parsePrimary();
1589
+ return { type: 'FirstItem', collection };
1590
+ }
1591
+
1592
+ if (first.value === 'last') {
1593
+ advance(); // last
1594
+ advance(); // noun
1595
+ advance(); // from
1596
+ const collection = parsePrimary();
1597
+ return { type: 'LastItem', collection };
1598
+ }
1599
+
1600
+ if (second.value in NUMBER_WORDS) {
1601
+ const index = NUMBER_WORDS[second.value] - 1;
1602
+ advance(); // noun
1603
+ advance(); // number word
1604
+ advance(); // from
1605
+ const collection = parsePrimary();
1606
+ return { type: 'NumberedItem', index, collection };
1607
+ }
1608
+
1609
+ throw new Error(makeError(
1610
+ `Expected a number word after "${first.value}" before "from".\n\nUse number words like "one", "two", "three".\n\nExample:\n ${first.value} one from players`,
1611
+ second
1612
+ ));
1613
+ }
1614
+
1615
+ // atom → STRING | NUMBER | true | false | null | '(' expr ')' |
1616
+ // '[' ... ']' | '{' ... '}' | httpCall | IDENTIFIER '(' args ')' | IDENTIFIER
1617
+ function parseAtom() {
1618
+ const token = peek();
1619
+
1620
+ if (token.type === TOKEN.STRING) { advance(); return { type: 'StringLiteral', value: token.value }; }
1621
+ if (token.type === TOKEN.TEMPLATE_STRING) { advance(); return { type: 'TemplateLiteral', value: token.value }; }
1622
+ if (token.type === TOKEN.NUMBER) { advance(); return { type: 'NumberLiteral', value: token.value }; }
1623
+ // v2.1.1 — boolean and null literals
1624
+ if (token.type === TOKEN.TRUE_KW) { advance(); return { type: 'BooleanLiteral', value: true }; }
1625
+ if (token.type === TOKEN.FALSE_KW) { advance(); return { type: 'BooleanLiteral', value: false }; }
1626
+ if (token.type === TOKEN.NULL_KW) { advance(); return { type: 'NullLiteral' }; }
1627
+ // v2.1.1 — parenthesised grouping: (a + b) * c
1628
+ if (token.type === TOKEN.LPAREN) {
1629
+ advance();
1630
+ const inner = parseExpression();
1631
+ consume(TOKEN.RPAREN, 'Expected ")" to close the grouped expression.');
1632
+ return inner;
1633
+ }
1634
+ if (token.type === TOKEN.LBRACKET) { return parseArrayLiteral(); }
1635
+ if (token.type === TOKEN.LBRACE) { return parseInlineObjectLiteral(); }
1636
+
1637
+ // v2.1.1 — HTTP client prefix form:
1638
+ // get "<url>" post urlExpr with <body>
1639
+ // put/patch/delete … optional "headers { … }" and "timeout <ms>" clauses
1640
+ // The call form get(...) stays an ordinary user/builtin call.
1641
+ const httpMethod = httpMethodWord(token);
1642
+ if (httpMethod && peekAt(1).type !== TOKEN.LPAREN && tokenStartsValue(peekAt(1))) {
1643
+ return parseHttpCall(httpMethod);
1644
+ }
1645
+
1646
+ if (token.type === TOKEN.IDENTIFIER) {
1647
+ if (peekAt(1).type === TOKEN.LPAREN) return parseCallExpression();
1648
+ advance();
1649
+ return { type: 'Identifier', name: token.value };
1650
+ }
1651
+
1652
+ // v2.1.0 — query("field") as a value: the HTTP query-string accessor.
1653
+ // The SQLite block form only applies when "query" stands alone.
1654
+ if (token.type === TOKEN.QUERY_KW && peekAt(1).type === TOKEN.LPAREN) {
1655
+ return parseCallExpression();
1656
+ }
1657
+
1658
+ throw new Error(makeError(
1659
+ `Expected a value (a word, number, string, or array) but got "${token.value || token.type}".`,
1660
+ token
1661
+ ));
1662
+ }
1663
+
1664
+ // v2.1.1 — "get", "post", "put", "patch" lex as identifiers; "delete" lexes
1665
+ // as the SQL keyword token. All five introduce an HTTP request when followed
1666
+ // by a URL value instead of "(".
1667
+ function httpMethodWord(token) {
1668
+ if (token.type === TOKEN.IDENTIFIER &&
1669
+ ['get', 'post', 'put', 'patch'].includes(token.value)) return token.value;
1670
+ if (token.type === TOKEN.DELETE_KW) return 'delete';
1671
+ return null;
1672
+ }
1673
+
1674
+ // True when a token can begin a value expression.
1675
+ function tokenStartsValue(token) {
1676
+ return [
1677
+ TOKEN.STRING, TOKEN.TEMPLATE_STRING, TOKEN.NUMBER,
1678
+ TOKEN.IDENTIFIER, TOKEN.LBRACKET, TOKEN.LBRACE,
1679
+ TOKEN.TRUE_KW, TOKEN.FALSE_KW, TOKEN.NULL_KW,
1680
+ ].includes(token.type);
1681
+ }
1682
+
1683
+ // v2.1.1 — parse one HTTP request expression after its method word.
1684
+ //
1685
+ // get <url> [headers <object>] [timeout <ms>]
1686
+ // post|put|patch|delete <url> [with <body>] [headers <object>] [timeout <ms>]
1687
+ //
1688
+ // The response is a record: ok, status, headers, data (JSON-parsed when the
1689
+ // server sends JSON, otherwise the response text).
1690
+ function parseHttpCall(method) {
1691
+ advance(); // consume the method word (get/post/put/patch/delete)
1692
+ const urlToken = peek();
1693
+ if (!tokenStartsValue(urlToken)) {
1694
+ throw new Error(makeError(
1695
+ `Expected a URL after "${method}".\n\nExample:\n ${method} "https://api.example.com/items"`,
1696
+ urlToken
1697
+ ));
1698
+ }
1699
+ const url = parsePrimary();
1700
+ let body = null;
1701
+ let headers = null;
1702
+ let timeout = null;
1703
+ while (true) {
1704
+ if (peek().type === TOKEN.WITH && body === null) {
1705
+ advance();
1706
+ body = parseExpression();
1707
+ continue;
1708
+ }
1709
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'headers' && headers === null) {
1710
+ advance();
1711
+ headers = parseExpression();
1712
+ continue;
1713
+ }
1714
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'timeout' && timeout === null) {
1715
+ advance();
1716
+ timeout = parseExpression();
1717
+ continue;
1718
+ }
1719
+ break;
1720
+ }
1721
+ return { type: 'HttpCall', method, url, body, headers, timeout };
1722
+ }
1723
+
1724
+ // [ expr, expr, ... ]
1725
+ function parseArrayLiteral() {
1726
+ consume(TOKEN.LBRACKET);
1727
+ const elements = [];
1728
+ while (peek().type !== TOKEN.RBRACKET) {
1729
+ if (peek().type === TOKEN.EOF) {
1730
+ throw new Error(makeError('Expected "]" to close the array before end of file.', peek()));
1731
+ }
1732
+ elements.push(parseExpression());
1733
+ if (peek().type === TOKEN.COMMA) advance();
1734
+ }
1735
+ consume(TOKEN.RBRACKET, 'Expected "]" to close the array.');
1736
+ return { type: 'ArrayLiteral', elements };
1737
+ }
1738
+
1739
+ // v1.2 — Inline object literal: { key: value, ... }
1740
+ function parseInlineObjectLiteral() {
1741
+ consume(TOKEN.LBRACE);
1742
+ const properties = [];
1743
+ while (peek().type !== TOKEN.RBRACE) {
1744
+ if (peek().type === TOKEN.EOF) {
1745
+ throw new Error(makeError(
1746
+ 'Expected "}" to close the inline object before end of file.',
1747
+ peek()
1748
+ ));
1749
+ }
1750
+ const keyToken = peek();
1751
+ if (keyToken.type !== TOKEN.IDENTIFIER && keyToken.type !== TOKEN.STRING) {
1752
+ throw new Error(makeError(
1753
+ 'Expected a property name inside the inline object.\n\nExample:\n { text: "hi" }',
1754
+ keyToken
1755
+ ));
1756
+ }
1757
+ advance();
1758
+ const key = keyToken.value;
1759
+ consume(TOKEN.COLON, `Expected ":" after property name "${key}".\n\nExample:\n { ${key}: "hi" }`);
1760
+ const value = parseExpression();
1761
+ properties.push({ key, value });
1762
+ if (peek().type === TOKEN.COMMA) advance();
1763
+ }
1764
+ consume(TOKEN.RBRACE, 'Expected "}" to close the inline object.');
1765
+ return { type: 'InlineObjectLiteral', properties };
1766
+ }
1767
+
1768
+ // Object literal body: key is value ... done
1769
+ function parseObjectLiteral() {
1770
+ const properties = [];
1771
+ while (peek().type !== TOKEN.DONE) {
1772
+ if (peek().type === TOKEN.EOF) {
1773
+ throw new Error(makeError(
1774
+ 'Expected keyword "done" to close the object literal before end of file.',
1775
+ peek()
1776
+ ));
1777
+ }
1778
+ const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
1779
+ consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n name is "Ayokunle"`);
1780
+ const value = parseExpression();
1781
+ properties.push({ key, value });
1782
+ }
1783
+ advance(); // consume DONE
1784
+ return { type: 'ObjectLiteral', properties };
1785
+ }
1786
+
1787
+ // v2.1.0 — "key is value" pairs until "done", shared by the mail
1788
+ // statements. Returns [{ key, value }] and consumes the closing DONE.
1789
+ function parsePropertyList(contextName) {
1790
+ const properties = [];
1791
+ while (peek().type !== TOKEN.DONE) {
1792
+ if (peek().type === TOKEN.EOF) {
1793
+ throw new Error(makeError(
1794
+ `Expected keyword "done" to close the ${contextName} before end of file.`,
1795
+ peek()
1796
+ ));
1797
+ }
1798
+ const key = consume(TOKEN.IDENTIFIER, 'Expected a property name.').value;
1799
+ consume(TOKEN.IS, `Expected "is" after property name "${key}".\n\nExample:\n ${key} is "value"`);
1800
+ const value = parseExpression();
1801
+ properties.push({ key, value });
1802
+ }
1803
+ advance(); // consume DONE
1804
+ return properties;
1805
+ }
1806
+
1807
+ // v2.1.0 — every <n> <unit>s … done: repeat work on an interval.
1808
+ // The unit is resolved to milliseconds at parse time; the generator emits
1809
+ // a plain setInterval with count * unit.
1810
+ function parseEvery() {
1811
+ advance(); // every (TOKEN.EACH)
1812
+ const count = advance().value; // NUMBER
1813
+ const unitToken = peek();
1814
+ if (count <= 0) {
1815
+ throw new Error(makeError('The count in "every" must be at least 1.\n\nExample:\n every 5 minutes\n show "tick"\n done', unitToken));
1816
+ }
1817
+ if (unitToken.type !== TOKEN.IDENTIFIER || !TIME_UNITS[unitToken.value]) {
1818
+ throw new Error(makeError(
1819
+ 'Expected a time unit after the number in "every".\n\nUnits: seconds, minutes, hours, days\n\nExample:\n every 5 minutes',
1820
+ unitToken
1821
+ ));
1822
+ }
1823
+ const unit = TIME_UNITS[advance().value];
1824
+ const body = parseBody('"every" block');
1825
+ return { type: 'EveryStatement', count, unit, body };
1826
+ }
1827
+
1828
+ // v2.1.0 — websocket server on <port> … done
1829
+ //
1830
+ // websocket server on 8081
1831
+ // when socket connects … done
1832
+ // when socket sends message … done
1833
+ // when socket disconnects … done
1834
+ // done
1835
+ //
1836
+ // Handlers are optional and may appear in any order.
1837
+ function parseWebSocketServer() {
1838
+ advance(); // websocket
1839
+ advance(); // server
1840
+ const onToken = peek();
1841
+ const isOn = (onToken.type === TOKEN.IDENTIFIER && onToken.value === 'on') || onToken.type === TOKEN.ON;
1842
+ if (!isOn) {
1843
+ throw new Error(makeError(
1844
+ 'Expected "on <port>" after "websocket server".\n\nExample:\n websocket server on 8081',
1845
+ onToken
1846
+ ));
1847
+ }
1848
+ advance(); // on
1849
+ const port = parseExpression();
1850
+
1851
+ let connectBody = null;
1852
+ let messageBody = null;
1853
+ let disconnectBody = null;
1854
+
1855
+ while (peek().type !== TOKEN.DONE) {
1856
+ if (peek().type === TOKEN.EOF) {
1857
+ throw new Error(makeError(
1858
+ 'Expected keyword "done" to close the websocket block before end of file.',
1859
+ peek()
1860
+ ));
1861
+ }
1862
+ const stmt = parseStatement();
1863
+ if (!stmt) continue;
1864
+ if (stmt.type === 'SocketConnectStatement') connectBody = stmt.body;
1865
+ else if (stmt.type === 'SocketMessageStatement') messageBody = stmt.body;
1866
+ else if (stmt.type === 'SocketDisconnectStatement') disconnectBody = stmt.body;
1867
+ else {
1868
+ throw new Error(makeError(
1869
+ 'A websocket block may only contain "when socket connects", "when socket sends message", and "when socket disconnects" handlers.',
1870
+ peek()
1871
+ ));
1872
+ }
1873
+ }
1874
+ advance(); // consume DONE
1875
+
1876
+ return { type: 'WebSocketServerStatement', port, connectBody, messageBody, disconnectBody };
1877
+ }
1878
+
1879
+ // v2.1.1 — whatsapp bot … done
1880
+ //
1881
+ // whatsapp bot
1882
+ // auth "session" (optional; session folder name)
1883
+ // login qr — or —
1884
+ // login pairing "2348012345678" (literal) — or —
1885
+ // login pairing phone (any value, e.g. from ask)
1886
+ //
1887
+ // on message
1888
+ // log message
1889
+ // if message.text is "/start"
1890
+ // reply "Welcome!"
1891
+ // done
1892
+ // done
1893
+ // done
1894
+ //
1895
+ // The Baileys runtime, its socket, events and auth APIs stay hidden: this
1896
+ // block is the whole surface. Defaults: auth folder "plainscript-whatsapp-auth",
1897
+ // QR login when no `login` line is present.
1898
+ function parseWhatsAppBot() {
1899
+ advance(); // whatsapp
1900
+ advance(); // bot
1901
+
1902
+ let authFolder = null;
1903
+ let login = null;
1904
+ const handlers = [];
1905
+
1906
+ while (peek().type !== TOKEN.DONE) {
1907
+ if (peek().type === TOKEN.EOF) {
1908
+ throw new Error(makeError(
1909
+ 'Expected keyword "done" to close the "whatsapp bot" block before end of file.',
1910
+ peek()
1911
+ ));
1912
+ }
1913
+
1914
+ // auth "<folder>" — where WhatsApp session credentials persist.
1915
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'auth' &&
1916
+ peekAt(1).type === TOKEN.STRING) {
1917
+ advance(); // auth
1918
+ authFolder = advance().value; // folder name
1919
+ continue;
1920
+ }
1921
+
1922
+ // login qr | login pairing "<phone>"
1923
+ if (peek().type === TOKEN.IDENTIFIER && peek().value === 'login') {
1924
+ advance(); // login
1925
+ const modeToken = peek();
1926
+ if (modeToken.type === TOKEN.IDENTIFIER && modeToken.value === 'qr') {
1927
+ advance();
1928
+ login = { mode: 'qr' };
1929
+ continue;
1930
+ }
1931
+ if (modeToken.type === TOKEN.IDENTIFIER && modeToken.value === 'pairing') {
1932
+ advance(); // pairing
1933
+ // v2.1.2 — the phone may be a string literal (validated here at
1934
+ // compile time) or any PlainScript value, typically a variable filled by
1935
+ // `ask`:
1936
+ //
1937
+ // ask "WhatsApp number: " as phone
1938
+ // whatsapp bot
1939
+ // auth "session"
1940
+ // login pairing phone
1941
+ // done
1942
+ //
1943
+ // Expression phones are validated at runtime before connecting.
1944
+ if (peek().type === TOKEN.STRING) {
1945
+ const phoneToken = advance();
1946
+ login = { mode: 'pairing', phone: validatePairingPhone(phoneToken.value, phoneToken) };
1947
+ } else {
1948
+ login = { mode: 'pairing', phoneExpr: parseExpression() };
1949
+ }
1950
+ continue;
1951
+ }
1952
+ throw new Error(makeError(
1953
+ 'Expected "qr" or "pairing \\"<number>\\"" after "login".\n\nExamples:\n login qr\n login pairing "2348012345678"',
1954
+ modeToken
1955
+ ));
1956
+ }
1957
+
1958
+ // on message … done — the message handler.
1959
+ if (peek().type === TOKEN.ON && peekAt(1).type === TOKEN.IDENTIFIER && peekAt(1).value === 'message') {
1960
+ advance(); // on
1961
+ advance(); // message
1962
+ const body = parseBody('"on message" block');
1963
+ handlers.push({ type: 'WhatsAppOnMessageStatement', body });
1964
+ continue;
1965
+ }
1966
+
1967
+ throw new Error(makeError(
1968
+ 'A "whatsapp bot" block may only contain an "auth", a "login", and "on message" statements.\n\nExample:\n whatsapp bot\n auth "session"\n login qr\n\n on message\n log message\n done\n done',
1969
+ peek()
1970
+ ));
1971
+ }
1972
+ advance(); // consume DONE
1973
+
1974
+ return {
1975
+ type: 'WhatsAppBotStatement',
1976
+ authFolder: authFolder || 'plainscript-whatsapp-auth',
1977
+ login: login || { mode: 'qr' },
1978
+ handlers,
1979
+ };
1980
+ }
1981
+
1982
+ // Baileys requires the pairing phone number in international format:
1983
+ // digits only (country code included), no leading "+", at most 15 digits
1984
+ // (E.164). Common separators are accepted in source and stripped here so
1985
+ // both "2348012345678" and "+234 801-234-5678" compile to the same value.
1986
+ function validatePairingPhone(raw, token) {
1987
+ const cleaned = String(raw).replace(/[\s()+\-\.]/g, '');
1988
+ if (!/^[0-9]+$/.test(cleaned)) {
1989
+ throw new Error(makeError(
1990
+ `"${raw}" is not a valid phone number for "login pairing".\n\nUse the full international number, digits only — country code first, no "+" and no spaces:\n\nExample:\n login pairing "2348012345678"`,
1991
+ token
1992
+ ));
1993
+ }
1994
+ if (cleaned.length < 8 || cleaned.length > 15) {
1995
+ throw new Error(makeError(
1996
+ `"${raw}" is not a valid phone number for "login pairing".\n\nThe international number must be 8 to 15 digits long (country code included):\n\nExample:\n login pairing "2348012345678"`,
1997
+ token
1998
+ ));
1999
+ }
2000
+ return cleaned;
2001
+ }
2002
+
2003
+ // name(arg, arg, ...)
2004
+ // name(value to collection) → v1.1 collection/io forms (add, remove, write)
2005
+ function parseCallExpression() {
2006
+ const nameToken = peek();
2007
+ const name = advance().value;
2008
+ consume(TOKEN.LPAREN, `Expected "(" after function name "${name}".`);
2009
+ const { separator, args } = parseArgList();
2010
+ consume(TOKEN.RPAREN, 'Expected ")" to close the argument list.');
2011
+ if (separator) return buildSpecialCall(name, separator, args, nameToken);
2012
+ // remove(last player from players): the item expression already consumed
2013
+ // "from <collection>", so reinterpret the single item argument as the
2014
+ // remove(value from collection) operation.
2015
+ if (name === 'remove' && args.length === 1 &&
2016
+ (args[0].type === 'FirstItem' || args[0].type === 'LastItem' || args[0].type === 'NumberedItem')) {
2017
+ return { type: 'RemoveCall', value: args[0], collection: args[0].collection };
2018
+ }
2019
+ return { type: 'CallExpression', name, args };
2020
+ }
2021
+
2022
+ function parseArgList() {
2023
+ const args = [];
2024
+ let separator = null;
2025
+ if (peek().type === TOKEN.RPAREN) return { separator, args };
2026
+ if (peek().type === TOKEN.EOF) {
2027
+ throw new Error(makeError('Expected ")" to close the argument list before end of file.', peek()));
2028
+ }
2029
+ args.push(parseExpression());
2030
+ while (peek().type === TOKEN.COMMA) {
2031
+ advance();
2032
+ if (peek().type === TOKEN.EOF) {
2033
+ throw new Error(makeError('Expected ")" to close the argument list before end of file.', peek()));
2034
+ }
2035
+ args.push(parseExpression());
2036
+ }
2037
+ // v1.1 — collection expressions: add(item to list) / remove(item from list) / write(data to "file")
2038
+ if (args.length === 1 && peek().type === TOKEN.IDENTIFIER &&
2039
+ (peek().value === 'to' || peek().value === 'from')) {
2040
+ separator = peek().value;
2041
+ advance();
2042
+ if (peek().type === TOKEN.EOF) {
2043
+ throw new Error(makeError(`Expected a value after "${separator}".`, peek()));
2044
+ }
2045
+ args.push(parseExpression());
2046
+ }
2047
+ return { separator, args };
2048
+ }
2049
+
2050
+ // v1.1 — Build a collection or I/O expression from a "to"/"from" special form.
2051
+ function buildSpecialCall(name, separator, args, nameToken) {
2052
+ if (separator === 'to' && name === 'add') {
2053
+ return { type: 'AddCall', value: args[0], collection: args[1] };
2054
+ }
2055
+ if (separator === 'from' && name === 'remove') {
2056
+ return { type: 'RemoveCall', value: args[0], collection: args[1] };
2057
+ }
2058
+ if (separator === 'to' && name === 'write') {
2059
+ return { type: 'WriteCall', data: args[0], file: args[1] };
2060
+ }
2061
+ throw new Error(makeError(
2062
+ `"${name}" is not a valid PlainScript collection expression.\n\nPlain supports:\n add(item to collection)\n remove(item from collection)\n write(data to "file")`,
2063
+ nameToken
2064
+ ));
2065
+ }
2066
+
2067
+ // ── Program ────────────────────────────────────────────────────────────────
2068
+
2069
+ const body = [];
2070
+ while (peek().type !== TOKEN.EOF) {
2071
+ const stmt = parseStatement();
2072
+ if (stmt) body.push(stmt);
2073
+ }
2074
+ return { type: 'Program', body };
2075
+ }
2076
+
2077
+ module.exports = { parse };