plainscript-lang 1.0.36 → 1.0.362

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 (84) hide show
  1. package/README.md +252 -20
  2. package/compiler/bundler.js +4 -4
  3. package/compiler/cli.js +18 -18
  4. package/compiler/dependency-detector.js +34 -22
  5. package/compiler/generator.js +326 -196
  6. package/compiler/lexer.js +49 -39
  7. package/compiler/parser.js +552 -181
  8. package/compiler/sourcemap.js +1 -1
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +2 -2
  11. package/docs/FB-PROMPT.md +524 -0
  12. package/docs/GAME-PROMPT.md +56 -55
  13. package/docs/PLAINSCRIPT-SPEC.md +16 -15
  14. package/docs/index.html +13 -6
  15. package/docs/website/script.js +1 -1
  16. package/docs/website/style.css +3 -3
  17. package/examples/ai-providers.pln +1 -1
  18. package/examples/arrays.pln +1 -1
  19. package/examples/async-errors.pln +2 -1
  20. package/examples/auth-api.pln +1 -1
  21. package/examples/auth-sessions.pln +1 -1
  22. package/examples/basics.pln +1 -1
  23. package/examples/bots.pln +1 -1
  24. package/examples/browser-interactive/README.md +3 -3
  25. package/examples/browser-interactive/src/interactive.pln +1 -1
  26. package/examples/cache-and-jobs.pln +1 -1
  27. package/examples/cache-schedule.pln +1 -1
  28. package/examples/canvas-game/README.md +4 -4
  29. package/examples/canvas-game/src/game.pln +1 -1
  30. package/examples/collections.pln +1 -1
  31. package/examples/concurrency.pln +1 -1
  32. package/examples/conditions.pln +1 -1
  33. package/examples/database.pln +1 -1
  34. package/examples/day2.pln +1 -1
  35. package/examples/day3.pln +1 -1
  36. package/examples/deployment.pln +1 -1
  37. package/examples/email-send.pln +1 -1
  38. package/examples/error-handling.pln +3 -2
  39. package/examples/expressions.pln +1 -1
  40. package/examples/file-uploads.pln +1 -1
  41. package/examples/files-and-config.pln +1 -1
  42. package/examples/files.pln +1 -1
  43. package/examples/football-backend/app.pln +1 -1
  44. package/examples/functions.pln +1 -1
  45. package/examples/hello.pln +1 -1
  46. package/examples/http-client.pln +1 -1
  47. package/examples/http.pln +1 -1
  48. package/examples/id-verification/app.pln +1 -1
  49. package/examples/javascript-library/README.md +6 -6
  50. package/examples/javascript-library/public/index.html +1 -1
  51. package/examples/javascript-library/src/interop.pln +1 -1
  52. package/examples/json.pln +1 -1
  53. package/examples/loops.pln +1 -1
  54. package/examples/modules/app.pln +1 -1
  55. package/examples/modules/main.pln +1 -1
  56. package/examples/modules/math.pln +1 -1
  57. package/examples/mongo.pln +1 -1
  58. package/examples/objects.pln +1 -1
  59. package/examples/ocr.pln +1 -1
  60. package/examples/packages.pln +1 -1
  61. package/examples/record-kinds.pln +1 -1
  62. package/examples/records.pln +1 -1
  63. package/examples/rest-api-fetch.pln +1 -1
  64. package/examples/rest-api.pln +1 -1
  65. package/examples/scheduled-tasks.pln +1 -1
  66. package/examples/search-and-filter.pln +1 -1
  67. package/examples/server.pln +1 -1
  68. package/examples/sessions-and-cookies.pln +1 -1
  69. package/examples/sqlite.pln +1 -1
  70. package/examples/start.pln +1 -1
  71. package/examples/stdlib.pln +1 -1
  72. package/examples/string-verbs.pln +1 -1
  73. package/examples/telegram-ai-bot.pln +1 -1
  74. package/examples/telegram-bot.pln +1 -1
  75. package/examples/testing.pln +1 -1
  76. package/examples/three-dimensional/README.md +2 -2
  77. package/examples/three-dimensional/src/scene.pln +1 -1
  78. package/examples/web-api.pln +1 -1
  79. package/examples/web-app.pln +1 -1
  80. package/examples/websocket-server.pln +1 -1
  81. package/examples/websocket.pln +1 -1
  82. package/examples/whatsapp-bot/pairing.pln +2 -2
  83. package/examples/whatsapp-bot/qr.pln +2 -2
  84. package/package.json +11 -12
@@ -6,14 +6,22 @@ const { SourceMapGenerator } = require('./sourcemap');
6
6
  // Known runtime packages and their require() statements.
7
7
  const KNOWN_PACKAGES = {
8
8
  express: `const express = require('express');`,
9
- sqlite: `const Database = require('better-sqlite3');`,
9
+ // v1.0.362 - better-sqlite3 is an OPTIONAL runtime backend. The require
10
+ // must not run at module load: on platforms without a usable native
11
+ // binary (e.g. Android/Termux) `plainscript` must still compile and run
12
+ // programs that never touch SQLite. `Database` is resolved lazily and only
13
+ // errors with a teaching message when a program actually constructs a
14
+ // native database.
15
+ sqlite: `let Database;
16
+ try { Database = require('better-sqlite3'); }
17
+ catch (__e) { Database = function () { throw new Error('PlainScript: the native SQLite engine (better-sqlite3) is not usable on this machine (' + (__e && __e.message ? __e.message : __e) + ').\\nInstall it with: npm install better-sqlite3\\nOr use the portable engine instead: database "' + (arguments[0] || ':memory:') + '" using "wasm"'); }; }`,
10
18
  fs: `const fs = require('fs');`,
11
19
  path: `const path = require('path');`,
12
20
  axios: `const axios = require('axios');`,
13
21
  chalk: `const chalk = require('chalk');`,
14
- // v2.1.0 — PostgreSQL driver behind the friendly "postgres" name.
22
+ // v2.1.0 - PostgreSQL driver behind the friendly "postgres" name.
15
23
  postgres: `const { Pool } = require('pg');`,
16
- // v2.2.0 — MongoDB driver.
24
+ // v2.2.0 - MongoDB driver.
17
25
  mongodb: `const { MongoClient } = require('mongodb');`,
18
26
  };
19
27
 
@@ -22,7 +30,7 @@ const KNOWN_PACKAGES = {
22
30
  const NPM_NAME = {
23
31
  sqlite: 'better-sqlite3',
24
32
  postgres: 'pg',
25
- // v2.1.1 — portable WebAssembly SQLite engine used by the "database"
33
+ // v2.1.1 - portable WebAssembly SQLite engine used by the "database"
26
34
  // statement as an automatic fallback (or explicit choice) when
27
35
  // better-sqlite3's native binding is unavailable.
28
36
  'wasm-sqlite': 'sql.js',
@@ -42,7 +50,7 @@ const BUILTIN_DECLARATIONS = {
42
50
  fs: `const fs = require('fs');`,
43
51
  path: `const path = require('path');`,
44
52
  crypto: `const crypto = require('crypto');`,
45
- // v1.0.1 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
53
+ // v1.0.1 - env-file runtime. Applies KEY=VALUE pairs from a .env file to
46
54
  // process.env. Blank lines and `#` comment lines are skipped.
47
55
  dotenv: [
48
56
  `function __loadEnvFile(path) {`,
@@ -61,7 +69,7 @@ const BUILTIN_DECLARATIONS = {
61
69
  ` }`,
62
70
  `}`,
63
71
  ].join('\n'),
64
- // v1.1.1 — ask runtime (RFC-0011 §14)
72
+ // v1.1.1 - ask runtime (RFC-0011 §14)
65
73
  ask: [
66
74
  `const readline = require('readline');`,
67
75
  `async function __ask(prompt = '') {`,
@@ -73,7 +81,7 @@ const BUILTIN_DECLARATIONS = {
73
81
  ` }`,
74
82
  `}`,
75
83
  ].join('\n'),
76
- // v2.0.1 — OCR runtime (tesseract.js). Extracts text from an image file.
84
+ // v2.0.1 - OCR runtime (tesseract.js). Extracts text from an image file.
77
85
  // The worker is created per call and always terminated, so repeated ocr
78
86
  // statements do not leak workers.
79
87
  ocr: [
@@ -88,7 +96,7 @@ const BUILTIN_DECLARATIONS = {
88
96
  ` }`,
89
97
  `}`,
90
98
  ].join('\n'),
91
- // v1.0.36 — DOM browser runtime (select/selectAll/parseHTML). Browser
99
+ // v1.0.362 - DOM browser runtime (select/selectAll/parseHTML). Browser
92
100
  // globals are guarded so the generated JS explains the problem when it is
93
101
  // run under Node instead of failing with a ReferenceError midpoint.
94
102
  dom: [
@@ -107,7 +115,7 @@ const BUILTIN_DECLARATIONS = {
107
115
  ` return template.content;`,
108
116
  `}`,
109
117
  ].join('\n'),
110
- // v1.0.36 — input runtime: pointer coordinates, gamepads, dropped files.
118
+ // v1.0.362 - input runtime: pointer coordinates, gamepads, dropped files.
111
119
  input: [
112
120
  `function __localPoint(e, canvas) {`,
113
121
  ` if (typeof document === 'undefined') throw new Error('localPoint(...) needs a browser (document is not defined in Node).');`,
@@ -125,7 +133,7 @@ const BUILTIN_DECLARATIONS = {
125
133
  ` return [...(event && event.dataTransfer ? event.dataTransfer.files : [])];`,
126
134
  `}`,
127
135
  ].join('\n'),
128
- // v1.0.36 — asset-loading runtime (images, JSON, bytes, data URLs). All
136
+ // v1.0.362 - asset-loading runtime (images, JSON, bytes, data URLs). All
129
137
  // helpers return promises; the STDLIB entries await them.
130
138
  assets: [
131
139
  `function __loadImage(url) {`,
@@ -162,7 +170,7 @@ const BUILTIN_DECLARATIONS = {
162
170
  ` });`,
163
171
  `}`,
164
172
  ].join('\n'),
165
- // v1.0.36 — Web Audio runtime. The AudioContext is created once and shared
173
+ // v1.0.362 - Web Audio runtime. The AudioContext is created once and shared
166
174
  // (browsers cap the number), and resumed on demand because autoplay policies
167
175
  // start it suspended.
168
176
  audio: [
@@ -205,7 +213,7 @@ const BUILTIN_DECLARATIONS = {
205
213
  ` });`,
206
214
  `}`,
207
215
  ].join('\n'),
208
- // v1.0.36 — WebGL runtime: context selection plus the three compile/link/
216
+ // v1.0.362 - WebGL runtime: context selection plus the three compile/link/
209
217
  // buffer helpers behind the gl* stdlib entries.
210
218
  gl: [
211
219
  `function __glContext(canvas) {`,
@@ -246,7 +254,7 @@ const BUILTIN_DECLARATIONS = {
246
254
  ` return buffer;`,
247
255
  `}`,
248
256
  ].join('\n'),
249
- // v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
257
+ // v1.0.1 - shared runtime helpers for reflection, binary-size, YAML subset
250
258
  // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
251
259
  // when any feature that needs them is used.
252
260
  core: [
@@ -379,7 +387,7 @@ const BUILTIN_DECLARATIONS = {
379
387
  ` });`,
380
388
  `}`,
381
389
  ].join('\n'),
382
- // v1.0.35 — dependency-free SVG images and visualizations.
390
+ // v1.0.35 - dependency-free SVG images and visualizations.
383
391
  // The image value is an SVG string, so it can be saved, embedded, or returned
384
392
  // from a web route without a native graphics dependency.
385
393
  visualization: [
@@ -471,7 +479,7 @@ const BUILTIN_DECLARATIONS = {
471
479
  ` return 'data:image/svg+xml;base64,' + Buffer.from(String(image == null ? '' : image), 'utf8').toString('base64');`,
472
480
  `}`,
473
481
  ].join('\n'),
474
- // v1.0.1 — process execution (child processes).
482
+ // v1.0.1 - process execution (child processes).
475
483
  process: [
476
484
  `const { execFile } = require('child_process');`,
477
485
  `function __runCommand(command, args) {`,
@@ -482,11 +490,11 @@ const BUILTIN_DECLARATIONS = {
482
490
  ` });`,
483
491
  `}`,
484
492
  ].join('\n'),
485
- // v1.0.1 — Map helpers.
493
+ // v1.0.1 - Map helpers.
486
494
  mapset: [
487
495
  `function __mapSet(map, key, value) { map.set(key, value); return map; }`,
488
496
  ].join('\n'),
489
- // v2.2.0 — collection primitives (flatten / pick / omit / groupBy).
497
+ // v2.2.0 - collection primitives (flatten / pick / omit / groupBy).
490
498
  coll: [
491
499
  `function __flatten(list) {`,
492
500
  ` const out = [];`,
@@ -529,7 +537,7 @@ const BUILTIN_DECLARATIONS = {
529
537
  ` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
530
538
  `}`,
531
539
  ].join('\n'),
532
- // v1.0.1 — dynamic module loader.
540
+ // v1.0.1 - dynamic module loader.
533
541
  loadmodule: [
534
542
  `function __loadModule(spec) {`,
535
543
  ` const path = require('path');`,
@@ -538,7 +546,7 @@ const BUILTIN_DECLARATIONS = {
538
546
  ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
539
547
  `}`,
540
548
  ].join('\n'),
541
- // v1.0.1 — recursive directory walker (returns full paths, files first).
549
+ // v1.0.1 - recursive directory walker (returns full paths, files first).
542
550
  walk: [
543
551
  `function __walkFolder(dir) {`,
544
552
  ` const fs = require('fs');`,
@@ -556,7 +564,7 @@ const BUILTIN_DECLARATIONS = {
556
564
  ` return out;`,
557
565
  `}`,
558
566
  ].join('\n'),
559
- // v2.1.0 — request validation runtime. Returns the names of required
567
+ // v2.1.0 - request validation runtime. Returns the names of required
560
568
  // fields whose value is missing (undefined/null/empty string) in data.
561
569
  validation: [
562
570
  `function __validate(data, fields) {`,
@@ -566,7 +574,7 @@ const BUILTIN_DECLARATIONS = {
566
574
  ` });`,
567
575
  `}`,
568
576
  ].join('\n'),
569
- // v2.1.0 — email runtime (nodemailer). One transport per program; sending
577
+ // v2.1.0 - email runtime (nodemailer). One transport per program; sending
570
578
  // fails with a teaching error when no transport was configured.
571
579
  mailer: [
572
580
  `const nodemailer = require('nodemailer');`,
@@ -577,12 +585,12 @@ const BUILTIN_DECLARATIONS = {
577
585
  ` return __mailTransport.sendMail(options);`,
578
586
  `}`,
579
587
  ].join('\n'),
580
- // v2.1.0 — cron scheduling runtime (croner). Zero dependencies, validates
588
+ // v2.1.0 - cron scheduling runtime (croner). Zero dependencies, validates
581
589
  // expressions at registration time.
582
590
  scheduler: [
583
591
  `const cron = require('croner');`,
584
592
  ].join('\n'),
585
- // v2.1.0 — WebSocket runtime (ws). Standalone server bound to its own port.
593
+ // v2.1.0 - WebSocket runtime (ws). Standalone server bound to its own port.
586
594
  websocket: [
587
595
  `const { WebSocketServer } = require('ws');`,
588
596
  `function __wsServerCreate(port, handlers) {`,
@@ -606,7 +614,7 @@ const BUILTIN_DECLARATIONS = {
606
614
  ` }`,
607
615
  `}`,
608
616
  ].join('\n'),
609
- // v2.1.0 — cache runtime (Redis via the redis package). The client is
617
+ // v2.1.0 - cache runtime (Redis via the redis package). The client is
610
618
  // created by the "cache" statement; accessors fail with a teaching error
611
619
  // when no cache was configured.
612
620
  cache: [
@@ -633,7 +641,7 @@ const BUILTIN_DECLARATIONS = {
633
641
  ` return __memCache.delete(key) ? 1 : 0;`,
634
642
  `}`,
635
643
  ].join('\n'),
636
- // v2.1.1 — WhatsApp runtime (@whiskeysockets/baileys behind the
644
+ // v2.1.1 - WhatsApp runtime (@whiskeysockets/baileys behind the
637
645
  // "whatsapp bot" block). Everything Baileys-shaped stays in here: socket
638
646
  // creation, auth-state files, QR rendering, pairing codes, connection
639
647
  // lifecycle and messages.upsert normalization. PlainScript programs only ever
@@ -641,7 +649,7 @@ const BUILTIN_DECLARATIONS = {
641
649
  whatsapp: [
642
650
  `const { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload } = (() => {`,
643
651
  ` let sock = null;`,
644
- ` let __waBaileysPkg = '@qwerty-xcv/baileys';`,
652
+ ` let __waBaileysPkg = '@whiskeysockets/baileys';`,
645
653
  ` const handlers = [];`,
646
654
  ` const __waSilentLogger = (() => {`,
647
655
  ` const noop = () => {};`,
@@ -751,7 +759,7 @@ const BUILTIN_DECLARATIONS = {
751
759
  ` }`,
752
760
  ` function __whatsappOnMessage(handler) { handlers.push(handler); }`,
753
761
  ` async function __whatsappStart(options) {`,
754
- ` __waBaileysPkg = options.baileys || '@qwerty-xcv/baileys';`,
762
+ ` __waBaileysPkg = options.baileys || '@whiskeysockets/baileys';`,
755
763
  ` const baileys = require(__waBaileysPkg);`,
756
764
  ` const makeWASocket = baileys.default;`,
757
765
  ` const { useMultiFileAuthState, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
@@ -766,7 +774,7 @@ const BUILTIN_DECLARATIONS = {
766
774
  // Auth/session persistence: useMultiFileAuthState stores credentials in
767
775
  // the folder from `auth "<name>"`; saveCreds writes every update back.
768
776
  ` const { state, saveCreds } = await useMultiFileAuthState(folder);`,
769
- // v2.14 — adopt the proven pairing-safe socket settings used by the
777
+ // v2.14 - adopt the proven pairing-safe socket settings used by the
770
778
  // reference Dual-Crasher build on the qwerty fork: a fixed Baileys protocol
771
779
  // version and the exact browser fingerprint that survives WhatsApp's
772
780
  // handshake without a 428 connection close.
@@ -783,7 +791,7 @@ const BUILTIN_DECLARATIONS = {
783
791
  ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
784
792
  ` });`,
785
793
  ` sock.ev.on('creds.update', saveCreds);`,
786
- // Pairing codes are requested two seconds after socket creation — asking
794
+ // Pairing codes are requested two seconds after socket creation - asking
787
795
  // earlier aborts the link attempt. PlainScript retries a few times (spam)
788
796
  // so a dropped request never blocks linking. The number was validated at
789
797
  // compile time; no custom suffix is applied.
@@ -983,7 +991,7 @@ const BUILTIN_DECLARATIONS = {
983
991
  ` return { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload };`,
984
992
  `})();`,
985
993
  ].join('\n'),
986
- // v2.1.1 — HTTP client runtime on the global fetch API (Node.js 18+).
994
+ // v2.1.1 - HTTP client runtime on the global fetch API (Node.js 18+).
987
995
  // Every response becomes a PlainScript-friendly record: { ok, status, headers,
988
996
  // data }, where data holds parsed JSON when the content type says JSON.
989
997
  http: [
@@ -1020,7 +1028,7 @@ const BUILTIN_DECLARATIONS = {
1020
1028
  ` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
1021
1029
  `}`,
1022
1030
  ].join('\n'),
1023
- // v2.2.0 — provider-neutral AI runtime. `chat` and `embedText` speak
1031
+ // v2.2.0 - provider-neutral AI runtime. `chat` and `embedText` speak
1024
1032
  // OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
1025
1033
  // and DeepSeek. A custom `base` and `key` can be supplied per call.
1026
1034
  ai: [
@@ -1080,7 +1088,7 @@ const BUILTIN_DECLARATIONS = {
1080
1088
  ` return dot / (Math.sqrt(na) * Math.sqrt(nb));`,
1081
1089
  `}`,
1082
1090
  ].join('\n'),
1083
- // v2.1.1 — file upload runtime (multer behind "accept uploads"). Files are
1091
+ // v2.1.1 - file upload runtime (multer behind "accept uploads"). Files are
1084
1092
  // held in memory by default or written to disk when a folder is given.
1085
1093
  // Normalised records expose: name, type, size, data (buffer) and path.
1086
1094
  uploads: [
@@ -1124,7 +1132,7 @@ const BUILTIN_DECLARATIONS = {
1124
1132
  ` return (req.files || []).filter((f) => f.fieldname === field).map(__normalizeUpload);`,
1125
1133
  `}`,
1126
1134
  ].join('\n'),
1127
- // v2.1.1 — cookie helpers shared by the cookie() accessor and the session
1135
+ // v2.1.1 - cookie helpers shared by the cookie() accessor and the session
1128
1136
  // runtime.
1129
1137
  cookies: [
1130
1138
  `function __parseCookies(header) {`,
@@ -1145,7 +1153,7 @@ const BUILTIN_DECLARATIONS = {
1145
1153
  ` return value === undefined ? null : value;`,
1146
1154
  `}`,
1147
1155
  ].join('\n'),
1148
- // v2.1.1 — session runtime. Cookie-signed session ids backed by an
1156
+ // v2.1.1 - session runtime. Cookie-signed session ids backed by an
1149
1157
  // in-memory store (sessions reset when the server restarts).
1150
1158
  sessions: [
1151
1159
  `const __sessionStore = new Map();`,
@@ -1188,7 +1196,7 @@ const BUILTIN_DECLARATIONS = {
1188
1196
  ` response.setHeader('Set-Cookie', 'plainscript.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');`,
1189
1197
  `}`,
1190
1198
  ].join('\n'),
1191
- // v2.1.1 — authentication runtime: scrypt password hashing and signed
1199
+ // v2.1.1 - authentication runtime: scrypt password hashing and signed
1192
1200
  // tokens (HS256 format), both zero-dependency.
1193
1201
  auth: [
1194
1202
  `const __authCrypto = require('crypto');`,
@@ -1233,7 +1241,7 @@ const BUILTIN_DECLARATIONS = {
1233
1241
  ` }`,
1234
1242
  `}`,
1235
1243
  ].join('\n'),
1236
- // v2.1.1 — Google sign-in (OAuth 2.0 authorization code flow). Registers
1244
+ // v2.1.1 - Google sign-in (OAuth 2.0 authorization code flow). Registers
1237
1245
  // two endpoints: /auth/google (redirect) and the configured callback URL
1238
1246
  // (token exchange + profile fetch), then redirects to the landing page.
1239
1247
  oauth: [
@@ -1288,7 +1296,7 @@ const BUILTIN_DECLARATIONS = {
1288
1296
  ` });`,
1289
1297
  `}`,
1290
1298
  ].join('\n'),
1291
- // v2.1.1 — per-IP request rate limiting with an in-memory sliding window.
1299
+ // v2.1.1 - per-IP request rate limiting with an in-memory sliding window.
1292
1300
  ratelimit: [
1293
1301
  `function __rateLimit(options) {`,
1294
1302
  ` const hits = new Map();`,
@@ -1313,13 +1321,13 @@ const BUILTIN_DECLARATIONS = {
1313
1321
  ` };`,
1314
1322
  `}`,
1315
1323
  ].join('\n'),
1316
- // v2.1.1 — pause helper for "retry N times every N seconds".
1324
+ // v2.1.1 - pause helper for "retry N times every N seconds".
1317
1325
  retry: [
1318
1326
  `const __retrySleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));`,
1319
1327
  ].join('\n'),
1320
- // IOPL-native — event emitter runtime.
1328
+ // IOPL-native - event emitter runtime.
1321
1329
  __emitter: 'const __emitter = new (require("events").EventEmitter)();',
1322
- // IOPL-native — line-by-line file streaming runtime.
1330
+ // IOPL-native - line-by-line file streaming runtime.
1323
1331
  __streamFile: [
1324
1332
  `async function __streamFile(path, fn) {`,
1325
1333
  ` const fs = require('fs');`,
@@ -1327,7 +1335,7 @@ const BUILTIN_DECLARATIONS = {
1327
1335
  ` for await (const line of rl) await fn(line);`,
1328
1336
  `}`,
1329
1337
  ].join('\n'),
1330
- // v2.1.1 — SQLite runtime with a portable engine chain. Default order:
1338
+ // v2.1.1 - SQLite runtime with a portable engine chain. Default order:
1331
1339
  // better-sqlite3 (native binding) first, sql.js (WebAssembly) as fallback.
1332
1340
  // Both engines are wrapped in the same tiny synchronous surface that PlainScript
1333
1341
  // generates (prepare().all()/.run(), exec(), transaction()), so compiled
@@ -1345,7 +1353,12 @@ const BUILTIN_DECLARATIONS = {
1345
1353
  ` }`,
1346
1354
  ` console.error('PlainScript: native SQLite unavailable (' + __sqliteNativeReason + '); using the WebAssembly engine instead.');`,
1347
1355
  ` }`,
1348
- ` const initSqlJs = require('sql.js');`,
1356
+ ` let initSqlJs;`,
1357
+ ` try {`,
1358
+ ` initSqlJs = require('sql.js');`,
1359
+ ` } catch (__e) {`,
1360
+ ` throw new Error('Database: SQLite is not available on this machine. The native engine (better-sqlite3) could not be loaded and the WebAssembly engine (sql.js) is not installed.\\nInstall them with: npm install better-sqlite3 sql.js');`,
1361
+ ` }`,
1349
1362
  ` const SQL = await initSqlJs();`,
1350
1363
  ` let raw;`,
1351
1364
  ` try {`,
@@ -1379,8 +1392,14 @@ const BUILTIN_DECLARATIONS = {
1379
1392
  ` };`,
1380
1393
  `}`,
1381
1394
  `function __sqliteWrapWasm(db, file) {`,
1395
+ ` // v1.0.362 - sql.js's export() ends an open transaction, so persisting`,
1396
+ ` // mid-transaction would break the explicit COMMIT that follows. While a`,
1397
+ ` // transaction is active, writes are only flushed to disk once, after the`,
1398
+ ` // COMMIT succeeds (the wrapper's own persist at that point covers it).`,
1399
+ ` let __sqliteTxn = 0;`,
1382
1400
  ` const persist = () => {`,
1383
1401
  ` if (file === ':memory:') return;`,
1402
+ ` if (__sqliteTxn > 0) return;`,
1384
1403
  ` try {`,
1385
1404
  ` require('fs').writeFileSync(file, Buffer.from(db.export()));`,
1386
1405
  ` } catch (error) {`,
@@ -1420,15 +1439,19 @@ const BUILTIN_DECLARATIONS = {
1420
1439
  ` transaction(fn) {`,
1421
1440
  ` return () => {`,
1422
1441
  ` db.run('BEGIN');`,
1442
+ ` __sqliteTxn++;`,
1443
+ ` let out;`,
1423
1444
  ` try {`,
1424
- ` const out = fn();`,
1445
+ ` out = fn();`,
1425
1446
  ` db.run('COMMIT');`,
1426
- ` persist();`,
1427
- ` return out;`,
1428
1447
  ` } catch (error) {`,
1429
1448
  ` try { db.run('ROLLBACK'); } catch (_) {}`,
1430
1449
  ` throw error;`,
1450
+ ` } finally {`,
1451
+ ` __sqliteTxn--;`,
1431
1452
  ` }`,
1453
+ ` persist();`,
1454
+ ` return out;`,
1432
1455
  ` };`,
1433
1456
  ` },`,
1434
1457
  ` };`,
@@ -1545,7 +1568,7 @@ const BUILTIN_DECLARATIONS = {
1545
1568
  ` inline_keyboard: [rows.map(([text, data]) => ({ text, callback_data: data }))],`,
1546
1569
  ` },`,
1547
1570
  ` });`,
1548
- // v2.0.1 — createTelegramBot is defined inside this module so its handler
1571
+ // v2.0.1 - createTelegramBot is defined inside this module so its handler
1549
1572
  // registry (`handlers`) and API transport (`call`, `sleep`) are in scope.
1550
1573
  // Defining it outside made every BOT.onCommand/onPattern/onCallback call
1551
1574
  // throw "ReferenceError: handlers is not defined", so no rendered inline
@@ -1664,11 +1687,11 @@ const BUILTIN_DECLARATIONS = {
1664
1687
  symbolSpecies: (_args) => `Symbol.species`,
1665
1688
  // Runtime constructors
1666
1689
  sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1667
- // v0.6 — runtime standard library
1690
+ // v0.6 - runtime standard library
1668
1691
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1669
1692
  readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1670
1693
  writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
1671
- // v2.4.0 — dependency-free SVG image and visualization helpers.
1694
+ // v2.4.0 - dependency-free SVG image and visualization helpers.
1672
1695
  svgImage: (args, context) => {
1673
1696
  ensureBuiltin(context, 'visualization');
1674
1697
  return `__svgImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
@@ -1699,7 +1722,7 @@ const BUILTIN_DECLARATIONS = {
1699
1722
  env: (args, context) => `process.env[${generateExpr(args[0], context)}]`,
1700
1723
  exit: (args, context) => `process.exit(${args.length ? generateExpr(args[0], context) : '0'})`,
1701
1724
  uuid: (_args, context) => `crypto.randomUUID()`,
1702
- // v1.2 — Telegram runtime helpers
1725
+ // v1.2 - Telegram runtime helpers
1703
1726
  bot: (args, context) => {
1704
1727
  ensureBuiltin(context, 'telegram');
1705
1728
  markAsync(context);
@@ -1741,7 +1764,7 @@ const BUILTIN_DECLARATIONS = {
1741
1764
  const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
1742
1765
  return `await Telegram.call(${method}, ${params})`;
1743
1766
  },
1744
- // v2.1.0 — HTTP request accessors. Only meaningful inside a route handler,
1767
+ // v2.1.0 - HTTP request accessors. Only meaningful inside a route handler,
1745
1768
  // where Express provides req/res.
1746
1769
  param: (args, context) => routeAccessor('param', 'params', args, context),
1747
1770
  query: (args, context) => routeAccessor('query', 'query', args, context),
@@ -1758,13 +1781,13 @@ const BUILTIN_DECLARATIONS = {
1758
1781
  if (!args || args.length === 0) return base;
1759
1782
  return `${base}[${generateExpr(args[0], context)}]`;
1760
1783
  },
1761
- // v2.1.0 — request validation. Returns the list of missing required fields.
1784
+ // v2.1.0 - request validation. Returns the list of missing required fields.
1762
1785
  validate: (args, context) => {
1763
1786
  ensureBuiltin(context, 'validation');
1764
1787
  return `__validate(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1765
1788
  },
1766
1789
 
1767
- // ── v2.1.0 — filesystem helpers (sync, matching readFile/writeFile style)
1790
+ // ── v2.1.0 - filesystem helpers (sync, matching readFile/writeFile style)
1768
1791
 
1769
1792
  copyFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.copyFileSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1770
1793
  moveFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.renameSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
@@ -1782,7 +1805,7 @@ const BUILTIN_DECLARATIONS = {
1782
1805
  return `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1783
1806
  },
1784
1807
 
1785
- // ── v2.1.0 — text, number and collection helpers
1808
+ // ── v2.1.0 - text, number and collection helpers
1786
1809
 
1787
1810
  trim: (args, context) => `String(${generateExpr(args[0], context)}).trim()`,
1788
1811
  replace: (args, context) => {
@@ -1813,7 +1836,7 @@ const BUILTIN_DECLARATIONS = {
1813
1836
  hasKey: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1814
1837
  merge: (args, context) => `{ ...${generateExpr(args[0], context)}, ...${generateExpr(args[1], context)} }`,
1815
1838
 
1816
- // ── v2.2.0 — collection & string primitives (IOPL-native, dependency-free).
1839
+ // ── v2.2.0 - collection & string primitives (IOPL-native, dependency-free).
1817
1840
  // A numeric range [start..end], stepping by 1 (or `step` when given).
1818
1841
  range: (args, context) => {
1819
1842
  const start = generateExpr(args[0], context);
@@ -1830,7 +1853,11 @@ const BUILTIN_DECLARATIONS = {
1830
1853
  ensureBuiltin(context, 'coll');
1831
1854
  return `__flatten(${generateExpr(args[0], context)})`;
1832
1855
  },
1833
- includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)})`,
1856
+ includes: (args, context) => {
1857
+ const coll = generateExpr(args[0], context);
1858
+ const val = generateExpr(args[1], context);
1859
+ return `(${coll} instanceof Set ? ${coll}.has(${val}) : (${coll}).includes(${val}))`;
1860
+ },
1834
1861
  paginate: (args, context) => {
1835
1862
  ensureBuiltin(context, 'coll');
1836
1863
  return `__paginate(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${args.length > 2 ? generateExpr(args[2], context) : '10'})`;
@@ -1858,7 +1885,7 @@ const BUILTIN_DECLARATIONS = {
1858
1885
  padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1859
1886
  padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1860
1887
 
1861
- // ── v2.3.0 — Proxy and Reflect (IOPL-native).
1888
+ // ── v2.3.0 - Proxy and Reflect (IOPL-native).
1862
1889
  // Proxy creation: proxy(target, handler)
1863
1890
  proxy: (args, context) => `new Proxy(${args.map(a => generateExpr(a, context)).join(', ')})`,
1864
1891
  // Proxy revocable: proxyRevocable(target, handler) -> { proxy, revoke }
@@ -1878,8 +1905,8 @@ const BUILTIN_DECLARATIONS = {
1878
1905
  reflectSet: (args, context) => `Reflect.set(${args.map(a => generateExpr(a, context)).join(', ')})`,
1879
1906
  reflectSetPrototypeOf: (args, context) => `Reflect.setPrototypeOf(${args.map(a => generateExpr(a, context)).join(', ')})`,
1880
1907
 
1881
- // ── v1.0.1 — nullable / regex / date helpers (IOPL-native).
1882
- // first non-null, non-undefined argument — IOPL null-coalescing.
1908
+ // ── v1.0.1 - nullable / regex / date helpers (IOPL-native).
1909
+ // first non-null, non-undefined argument - IOPL null-coalescing.
1883
1910
  coalesce: (args, context) =>
1884
1911
  `(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
1885
1912
  // regex-aware replace (replace() is literal-only).
@@ -1895,7 +1922,7 @@ const BUILTIN_DECLARATIONS = {
1895
1922
  return `__formatDate(${value}, ${pattern})`;
1896
1923
  },
1897
1924
 
1898
- // ── v1.0.2 — Native Date/DateTime/Regex support (IOPL-native, no JS gateway needed).
1925
+ // ── v1.0.2 - Native Date/DateTime/Regex support (IOPL-native, no JS gateway needed).
1899
1926
  // Create a new Date object. With no args: now. With 1 arg: parse ISO string or timestamp.
1900
1927
  // With multiple args: year, month (1-12), day, hour, min, sec, ms.
1901
1928
  newDate: (args, context) => {
@@ -2033,7 +2060,7 @@ const BUILTIN_DECLARATIONS = {
2033
2060
  return `${text}.split(new RegExp(${pattern}, ${flags}))`;
2034
2061
  },
2035
2062
 
2036
- // ── v2.1.0 — cache (Redis) accessors. All async.
2063
+ // ── v2.1.0 - cache (Redis) accessors. All async.
2037
2064
 
2038
2065
  cacheGet: (args, context) => {
2039
2066
  ensureBuiltin(context, 'cache');
@@ -2056,14 +2083,14 @@ const BUILTIN_DECLARATIONS = {
2056
2083
  return `await __cacheDelete(String(${generateExpr(args[0], context)}))`;
2057
2084
  },
2058
2085
 
2059
- // v2.1.0 — email sending helper (statement form uses this too).
2086
+ // v2.1.0 - email sending helper (statement form uses this too).
2060
2087
  sendMail: (args, context) => {
2061
2088
  ensureBuiltin(context, 'mailer');
2062
2089
  markAsync(context);
2063
2090
  return `__mailSend(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
2064
2091
  },
2065
2092
 
2066
- // ── v2.1.1 — uploads, cookies, passwords and tokens
2093
+ // ── v2.1.1 - uploads, cookies, passwords and tokens
2067
2094
 
2068
2095
  // upload("field") / uploads("field") read files registered by
2069
2096
  // "accept uploads". Single file → record or null; plural → array.
@@ -2106,7 +2133,7 @@ const BUILTIN_DECLARATIONS = {
2106
2133
  return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
2107
2134
  },
2108
2135
 
2109
- // ── v1.0.1 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
2136
+ // ── v1.0.1 - capability-gap stdlib (reflection, binary, concurrency, ...) ──
2110
2137
 
2111
2138
  // Reflection
2112
2139
  typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
@@ -2137,7 +2164,7 @@ const BUILTIN_DECLARATIONS = {
2137
2164
  return `crypto.createHash('md5').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2138
2165
  },
2139
2166
 
2140
- // Serialization — minimal dependency-free YAML subset (see __yamlParse).
2167
+ // Serialization - minimal dependency-free YAML subset (see __yamlParse).
2141
2168
  yamlDecode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlParse(${generateExpr(args[0], context)})`; },
2142
2169
  yamlEncode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlStringify(${generateExpr(args[0], context)})`; },
2143
2170
 
@@ -2167,7 +2194,7 @@ const BUILTIN_DECLARATIONS = {
2167
2194
  // Generators / iterables
2168
2195
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
2169
2196
 
2170
- // v1.0.1 — dynamic module loading (the runtime companion to `import "./x.pt"`).
2197
+ // v1.0.1 - dynamic module loading (the runtime companion to `import "./x.pt"`).
2171
2198
  // Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
2172
2199
  // `require.resolve` from the program root.
2173
2200
  loadModule: (args, context) => {
@@ -2175,7 +2202,7 @@ const BUILTIN_DECLARATIONS = {
2175
2202
  return `__loadModule(${generateExpr(args[0], context)})`;
2176
2203
  },
2177
2204
 
2178
- // ── v2.2.0 — AI/ML. `chat`/`embedText` call an OpenAI-compatible endpoint
2205
+ // ── v2.2.0 - AI/ML. `chat`/`embedText` call an OpenAI-compatible endpoint
2179
2206
  // (key from OPENAI_API_KEY, base from OPENAI_BASE_URL); `similarity` runs
2180
2207
  // offline cosine similarity over any two equal-length numeric vectors.
2181
2208
  chat: (args, context) => {
@@ -2276,7 +2303,7 @@ const BUILTIN_DECLARATIONS = {
2276
2303
  return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
2277
2304
  },
2278
2305
 
2279
- // ── v1.0.2 — Extended Math functions (IOPL-native).
2306
+ // ── v1.0.2 - Extended Math functions (IOPL-native).
2280
2307
  abs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
2281
2308
  min: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
2282
2309
  max: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
@@ -2316,7 +2343,7 @@ const BUILTIN_DECLARATIONS = {
2316
2343
  hypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
2317
2344
  cbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
2318
2345
 
2319
- // ── v1.0.2 — Extended String functions (IOPL-native).
2346
+ // ── v1.0.2 - Extended String functions (IOPL-native).
2320
2347
  trim: (args, context) => `String(${generateExpr(args[0], context)}).trim()`,
2321
2348
  trimStart: (args, context) => `String(${generateExpr(args[0], context)}).trimStart()`,
2322
2349
  trimEnd: (args, context) => `String(${generateExpr(args[0], context)}).trimEnd()`,
@@ -2348,7 +2375,7 @@ const BUILTIN_DECLARATIONS = {
2348
2375
  toString: (args, context) => `String(${generateExpr(args[0], context)}).toString()`,
2349
2376
  stringValueOf: (args, context) => `String(${generateExpr(args[0], context)}).valueOf()`,
2350
2377
 
2351
- // ── v1.0.2 — Extended Array/Collection functions (IOPL-native).
2378
+ // ── v1.0.2 - Extended Array/Collection functions (IOPL-native).
2352
2379
  push: (args, context) => `(${generateExpr(args[0], context)}).push(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
2353
2380
  pop: (args, context) => `(${generateExpr(args[0], context)}).pop()`,
2354
2381
  shift: (args, context) => `(${generateExpr(args[0], context)}).shift()`,
@@ -2364,7 +2391,12 @@ const BUILTIN_DECLARATIONS = {
2364
2391
  findLastIndex: (args, context) => `(${generateExpr(args[0], context)}).findLastIndex(${generateExpr(args[1], context)})`,
2365
2392
  indexOf: (args, context) => `(${generateExpr(args[0], context)}).indexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
2366
2393
  lastIndexOf: (args, context) => `(${generateExpr(args[0], context)}).lastIndexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
2367
- includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
2394
+ includes: (args, context) => {
2395
+ const coll = generateExpr(args[0], context);
2396
+ const val = generateExpr(args[1], context);
2397
+ const fromIndex = args.length > 2 ? ', ' + generateExpr(args[2], context) : '';
2398
+ return `(${coll} instanceof Set ? ${coll}.has(${val}) : (${coll}).includes(${val}${fromIndex}))`;
2399
+ },
2368
2400
  join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
2369
2401
  reverse: (args, context) => `[...${generateExpr(args[0], context)}].reverse()`,
2370
2402
  sort: (args, context) => `[...${generateExpr(args[0], context)}].sort(${args.length > 1 ? generateExpr(args[1], context) : '(a, b) => (a < b ? -1 : a > b ? 1 : 0)'})`,
@@ -2386,7 +2418,7 @@ const BUILTIN_DECLARATIONS = {
2386
2418
  values: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
2387
2419
  entries: (args, context) => `Object.entries(${generateExpr(args[0], context)})`,
2388
2420
 
2389
- // ── v1.0.2 — Extended Object functions (IOPL-native).
2421
+ // ── v1.0.2 - Extended Object functions (IOPL-native).
2390
2422
  assign: (args, context) => `Object.assign(${args.map(a => generateExpr(a, context)).join(', ')})`,
2391
2423
  create: (args, context) => `Object.create(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
2392
2424
  defineProperty: (args, context) => `Object.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
@@ -2406,7 +2438,7 @@ const BUILTIN_DECLARATIONS = {
2406
2438
  seal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
2407
2439
  hasOwn: (args, context) => `Object.hasOwn(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2408
2440
 
2409
- // ── v1.0.2 — Promise/Async utilities (IOPL-native).
2441
+ // ── v1.0.2 - Promise/Async utilities (IOPL-native).
2410
2442
  Promise: {
2411
2443
  resolve: (args, context) => `Promise.resolve(${generateExpr(args[0], context)})`,
2412
2444
  reject: (args, context) => `Promise.reject(${generateExpr(args[0], context)})`,
@@ -2440,11 +2472,11 @@ const BUILTIN_DECLARATIONS = {
2440
2472
  return `Promise.race([${generateExpr(args[0], context)}, new Promise((_, r) => setTimeout(() => r(new Error('Timed out')), ${ms}))])`;
2441
2473
  },
2442
2474
 
2443
- // ── v1.0.2 — JSON utilities (IOPL-native).
2475
+ // ── v1.0.2 - JSON utilities (IOPL-native).
2444
2476
  jsonParse: (args, context) => `JSON.parse(${generateExpr(args[0], context)})`,
2445
2477
  stringify: (args, context) => `JSON.stringify(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
2446
2478
 
2447
- // ── v1.0.2 — Type checking utilities (IOPL-native).
2479
+ // ── v1.0.2 - Type checking utilities (IOPL-native).
2448
2480
  isArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
2449
2481
  isInteger: (args, context) => `Number.isInteger(${generateExpr(args[0], context)})`,
2450
2482
  isNaN: (args, context) => `Number.isNaN(${generateExpr(args[0], context)})`,
@@ -2453,12 +2485,12 @@ const BUILTIN_DECLARATIONS = {
2453
2485
  parseInt: (args, context) => `parseInt(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
2454
2486
  parseFloat: (args, context) => `parseFloat(${generateExpr(args[0], context)})`,
2455
2487
 
2456
- // ── v1.0.2 — Array static methods (IOPL-native).
2488
+ // ── v1.0.2 - Array static methods (IOPL-native).
2457
2489
  arrayFrom: (args, context) => `Array.from(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
2458
2490
  arrayOf: (args, context) => `Array.of(${args.map(a => generateExpr(a, context)).join(', ')})`,
2459
2491
  arrayIsArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
2460
2492
 
2461
- // ── v1.0.2 — Object static methods (IOPL-native).
2493
+ // ── v1.0.2 - Object static methods (IOPL-native).
2462
2494
  objectFromEntries: (args, context) => `Object.fromEntries(${generateExpr(args[0], context)})`,
2463
2495
  objectGetOwnPropertySymbols: (args, context) => `Object.getOwnPropertySymbols(${generateExpr(args[0], context)})`,
2464
2496
  objectGetOwnPropertyDescriptors: (args, context) => `Object.getOwnPropertyDescriptors(${generateExpr(args[0], context)})`,
@@ -2482,7 +2514,7 @@ const BUILTIN_DECLARATIONS = {
2482
2514
  objectFreeze: (args, context) => `Object.freeze(${generateExpr(args[0], context)})`,
2483
2515
  objectSeal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
2484
2516
 
2485
- // ── v1.0.2 — Symbol support (IOPL-native).
2517
+ // ── v1.0.2 - Symbol support (IOPL-native).
2486
2518
  symbol: (args, context) => `Symbol(${args.length > 0 ? generateExpr(args[0], context) : 'undefined'})`,
2487
2519
  symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
2488
2520
  symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
@@ -2499,7 +2531,7 @@ const BUILTIN_DECLARATIONS = {
2499
2531
  symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
2500
2532
  symbolUnscopables: (_args) => `Symbol.unscopables`,
2501
2533
 
2502
- // ── v1.0.2 — Math static methods (IOPL-native).
2534
+ // ── v1.0.2 - Math static methods (IOPL-native).
2503
2535
  mathAbs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
2504
2536
  mathMin: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
2505
2537
  mathMax: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
@@ -2537,7 +2569,7 @@ const BUILTIN_DECLARATIONS = {
2537
2569
  mathHypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
2538
2570
  mathCbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
2539
2571
 
2540
- // ── v1.0.2 — TypedArray support (IOPL-native).
2572
+ // ── v1.0.2 - TypedArray support (IOPL-native).
2541
2573
  int8Array: (args, context) => `new Int8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2542
2574
  uint8Array: (args, context) => `new Uint8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2543
2575
  uint8ClampedArray: (args, context) => `new Uint8ClampedArray(${args.map(a => generateExpr(a, context)).join(', ')})`,
@@ -2552,25 +2584,25 @@ const BUILTIN_DECLARATIONS = {
2552
2584
  dataView: (args, context) => `new DataView(${args.map(a => generateExpr(a, context)).join(', ')})`,
2553
2585
  arrayBuffer: (args, context) => `new ArrayBuffer(${args.map(a => generateExpr(a, context)).join(', ')})`,
2554
2586
 
2555
- // ── v1.0.2 — Global objects access (IOPL-native).
2587
+ // ── v1.0.2 - Global objects access (IOPL-native).
2556
2588
  globalThis: (_args) => `globalThis`,
2557
2589
  console: (_args) => `console`,
2558
2590
  process: (_args) => `process`,
2559
2591
  Buffer: (_args) => `Buffer`,
2560
2592
 
2561
- // ── v2.3.0 — EventSource / Server-Sent Events (IOPL-native).
2593
+ // ── v2.3.0 - EventSource / Server-Sent Events (IOPL-native).
2562
2594
  eventSource: (args, context) => `new EventSource(${args.map(a => generateExpr(a, context)).join(', ')})`,
2563
2595
 
2564
- // ── v2.2.0 — URL and URLSearchParams (IOPL-native).
2596
+ // ── v2.2.0 - URL and URLSearchParams (IOPL-native).
2565
2597
  url: (args, context) => `new URL(${generateExpr(args[0], context)}${args[1] ? `, ${generateExpr(args[1], context)}` : ''})`,
2566
2598
  urlSearchParams: (args, context) => `new URLSearchParams(${args.length ? generateExpr(args[0], context) : ''})`,
2567
2599
 
2568
- // ── v2.2.0 — Intl / Internationalization (IOPL-native).
2600
+ // ── v2.2.0 - Intl / Internationalization (IOPL-native).
2569
2601
  dateTimeFormat: (args, context) => `new Intl.DateTimeFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2570
2602
  numberFormat: (args, context) => `new Intl.NumberFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2571
2603
  collator: (args, context) => `new Intl.Collator(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2572
2604
 
2573
- // ── v2.2.0 — Crypto / Web Crypto API (IOPL-native).
2605
+ // ── v2.2.0 - Crypto / Web Crypto API (IOPL-native).
2574
2606
  cryptoRandomUUID: (_args) => `crypto.randomUUID()`,
2575
2607
  cryptoGetRandomValues: (args, context) => `crypto.getRandomValues(${generateExpr(args[0], context)})`,
2576
2608
  cryptoSubtleDigest: (args, context) => `crypto.subtle.digest(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
@@ -2585,13 +2617,13 @@ const BUILTIN_DECLARATIONS = {
2585
2617
  cryptoSubtleWrapKey: (args, context) => `crypto.subtle.wrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2586
2618
  cryptoSubtleUnwrapKey: (args, context) => `crypto.subtle.unwrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2587
2619
 
2588
- // ── v2.2.0 — WeakMap / WeakSet / WeakRef / FinalizationRegistry (IOPL-native).
2620
+ // ── v2.2.0 - WeakMap / WeakSet / WeakRef / FinalizationRegistry (IOPL-native).
2589
2621
  weakMap: (_args) => `new WeakMap()`,
2590
2622
  weakSet: (_args) => `new WeakSet()`,
2591
2623
  weakRef: (args, context) => `new WeakRef(${generateExpr(args[0], context)})`,
2592
2624
  finalizationRegistry: (args, context) => `new FinalizationRegistry(${generateExpr(args[0], context)})`,
2593
2625
 
2594
- // ── v2.2.0 — Proxy / Reflect (IOPL-native).
2626
+ // ── v2.2.0 - Proxy / Reflect (IOPL-native).
2595
2627
  proxy: (args, context) => `new Proxy(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2596
2628
  reflectGet: (args, context) => `Reflect.get(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2597
2629
  reflectSet: (args, context) => `Reflect.set(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
@@ -2603,7 +2635,7 @@ const BUILTIN_DECLARATIONS = {
2603
2635
  reflectDefineProperty: (args, context) => `Reflect.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
2604
2636
  reflectGetOwnPropertyDescriptor: (args, context) => `Reflect.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2605
2637
 
2606
- // ── v2.2.0 — Symbol (IOPL-native).
2638
+ // ── v2.2.0 - Symbol (IOPL-native).
2607
2639
  symbol: (args, context) => `Symbol(${args.length ? generateExpr(args[0], context) : 'undefined'})`,
2608
2640
  symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
2609
2641
  symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
@@ -2620,12 +2652,12 @@ const BUILTIN_DECLARATIONS = {
2620
2652
  symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
2621
2653
  symbolUnscopables: (_args) => `Symbol.unscopables`,
2622
2654
 
2623
- // ── v2.2.0 — BigInt (IOPL-native).
2655
+ // ── v2.2.0 - BigInt (IOPL-native).
2624
2656
  bigInt: (args, context) => `BigInt(${generateExpr(args[0], context)})`,
2625
2657
  bigIntAsIntN: (args, context) => `BigInt.asIntN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2626
2658
  bigIntAsUintN: (args, context) => `BigInt.asUintN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2627
2659
 
2628
- // ── v2.2.0 — Atomics / SharedArrayBuffer (IOPL-native).
2660
+ // ── v2.2.0 - Atomics / SharedArrayBuffer (IOPL-native).
2629
2661
  atomicsAdd: (args, context) => `Atomics.add(${args.map(a => generateExpr(a, context)).join(', ')})`,
2630
2662
  atomicsSub: (args, context) => `Atomics.sub(${args.map(a => generateExpr(a, context)).join(', ')})`,
2631
2663
  atomicsAnd: (args, context) => `Atomics.and(${args.map(a => generateExpr(a, context)).join(', ')})`,
@@ -2640,7 +2672,7 @@ const BUILTIN_DECLARATIONS = {
2640
2672
  atomicsIsLockFree: (args, context) => `Atomics.isLockFree(${generateExpr(args[0], context)})`,
2641
2673
  sharedArrayBuffer: (args, context) => `new SharedArrayBuffer(${generateExpr(args[0], context)})`,
2642
2674
 
2643
- // ── v2.2.0 — Error subclasses (IOPL-native).
2675
+ // ── v2.2.0 - Error subclasses (IOPL-native).
2644
2676
  error: (args, context) => `new Error(${args.length ? generateExpr(args[0], context) : ''})`,
2645
2677
  typeError: (args, context) => `new TypeError(${args.length ? generateExpr(args[0], context) : ''})`,
2646
2678
  rangeError: (args, context) => `new RangeError(${args.length ? generateExpr(args[0], context) : ''})`,
@@ -2650,12 +2682,12 @@ const BUILTIN_DECLARATIONS = {
2650
2682
  uriError: (args, context) => `new URIError(${args.length ? generateExpr(args[0], context) : ''})`,
2651
2683
  aggregateError: (args, context) => `new AggregateError(${args.map(a => generateExpr(a, context)).join(', ')})`,
2652
2684
 
2653
- // ── v2.2.0 — Blob / File / FormData (IOPL-native, browser-compatible).
2685
+ // ── v2.2.0 - Blob / File / FormData (IOPL-native, browser-compatible).
2654
2686
  blob: (args, context) => `new Blob(${args.map(a => generateExpr(a, context)).join(', ')})`,
2655
2687
  file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2656
2688
  formData: (_args) => `new FormData()`,
2657
2689
 
2658
- // ── v1.0.36 — browser DOM (IOPL-native). All helpers guard their browser
2690
+ // ── v1.0.362 - browser DOM (IOPL-native). All helpers guard their browser
2659
2691
  // global, so the generated output throws a clear teaching error under Node.
2660
2692
  select: (args, context) => {
2661
2693
  ensureBuiltin(context, 'dom');
@@ -2673,7 +2705,7 @@ const BUILTIN_DECLARATIONS = {
2673
2705
  return `__parseHTML(${generateExpr(args[0], context)})`;
2674
2706
  },
2675
2707
 
2676
- // ── v1.0.36 — browser input (IOPL-native).
2708
+ // ── v1.0.362 - browser input (IOPL-native).
2677
2709
  localPoint: (args, context) => {
2678
2710
  ensureBuiltin(context, 'input');
2679
2711
  requireArgs('localPoint', args, 2, 'localPoint(event, canvas)');
@@ -2689,7 +2721,7 @@ const BUILTIN_DECLARATIONS = {
2689
2721
  return `__droppedFiles(${generateExpr(args[0], context)})`;
2690
2722
  },
2691
2723
 
2692
- // ── v1.0.36 — browser assets (IOPL-native). Each awaitable helper is
2724
+ // ── v1.0.362 - browser assets (IOPL-native). Each awaitable helper is
2693
2725
  // awaited here, so the surrounding function/handler is marked async.
2694
2726
  loadImage: (args, context) => {
2695
2727
  ensureBuiltin(context, 'assets');
@@ -2722,7 +2754,7 @@ const BUILTIN_DECLARATIONS = {
2722
2754
  return `(await __readDataUrl(${generateExpr(args[0], context)}))`;
2723
2755
  },
2724
2756
 
2725
- // ── v1.0.36 — Web Audio (IOPL-native).
2757
+ // ── v1.0.362 - Web Audio (IOPL-native).
2726
2758
  audioContext: (_args, context) => {
2727
2759
  ensureBuiltin(context, 'audio');
2728
2760
  return `__audioContext()`;
@@ -2733,7 +2765,7 @@ const BUILTIN_DECLARATIONS = {
2733
2765
  return `__audioTone(${args.map(a => generateExpr(a, context)).join(', ')})`;
2734
2766
  },
2735
2767
 
2736
- // ── v1.0.36 — WebSocket send helper (works with any WebSocket-like object,
2768
+ // ── v1.0.362 - WebSocket send helper (works with any WebSocket-like object,
2737
2769
  // browser or Node): strings go through verbatim, everything else is JSON.
2738
2770
  webSocketSend: (args, context) => {
2739
2771
  requireArgs('webSocketSend', args, 2, 'webSocketSend(socket, { type: "move", x: 10 })');
@@ -2742,7 +2774,7 @@ const BUILTIN_DECLARATIONS = {
2742
2774
  return `${ws}.send(typeof (${value}) === 'string' ? (${value}) : JSON.stringify(${value}))`;
2743
2775
  },
2744
2776
 
2745
- // ── v1.0.36 — WebGL (IOPL-native).
2777
+ // ── v1.0.362 - WebGL (IOPL-native).
2746
2778
  webglContext: (args, context) => {
2747
2779
  ensureBuiltin(context, 'gl');
2748
2780
  requireOneArg('webglContext', args);
@@ -2769,7 +2801,7 @@ const BUILTIN_DECLARATIONS = {
2769
2801
  // record that this scope emitted an `await` so handler and function bodies can
2770
2802
  // decide their own async-ness at generation time (see generateBlock). Routing
2771
2803
  // every await-emitting construct through this single function removes the need
2772
- // for a separate hand-maintained registry of async statement types — so a new
2804
+ // for a separate hand-maintained registry of async statement types - so a new
2773
2805
  // async keyword can never silently break when used inside a route, listener, or
2774
2806
  // function.
2775
2807
  function markAsync(context) {
@@ -2777,7 +2809,7 @@ function markAsync(context) {
2777
2809
  // Only a construct that awaits at the true top level needs the program
2778
2810
  // wrapped in an async IIFE. Awaits emitted inside a user function (inFunction)
2779
2811
  // or inside a route/listener/404 handler (inHandler) are handled by marking
2780
- // that function/handler async instead — they must not drag the whole program
2812
+ // that function/handler async instead - they must not drag the whole program
2781
2813
  // into an async wrapper, or "top-level use wraps the whole program" would be
2782
2814
  // the only safe nesting level for a new async keyword.
2783
2815
  if (!context.inFunction && !context.inHandler) context.needsAsync = true;
@@ -2788,7 +2820,7 @@ function markAsync(context) {
2788
2820
  // This is the single source of truth for whether a route handler, listener,
2789
2821
  // 404 handler, or user function must be declared `async`. Previously this was
2790
2822
  // decided by a separate AST walker (containsAsyncBlock) that had to be kept in
2791
- // sync by hand with every construct that compiles down to `await` — the exact
2823
+ // sync by hand with every construct that compiles down to `await` - the exact
2792
2824
  // fragility that made "top-level use wraps the whole program" the only place
2793
2825
  // certain keywords (like ocr) were guaranteed to work. By observing the output
2794
2826
  // of generation instead, whatever a body contains is handled correctly, even if
@@ -2802,7 +2834,7 @@ function generateBlock(statements, indent, context) {
2802
2834
  return { out, emitted };
2803
2835
  }
2804
2836
 
2805
- // v2.1.0 — generate a request accessor (param/query/header). These compile to
2837
+ // v2.1.0 - generate a request accessor (param/query/header). These compile to
2806
2838
  // direct Express req.<bucket>[key] reads and are rejected outside routes so
2807
2839
  // mistakes surface at compile time with a teaching error.
2808
2840
  function routeAccessor(name, bucket, args, context) {
@@ -2817,7 +2849,7 @@ function routeAccessor(name, bucket, args, context) {
2817
2849
  return `req.${bucket}[${generateExpr(args[0], context)}]`;
2818
2850
  }
2819
2851
 
2820
- // v2.1.1 — compile-time guard shared by request-scoped accessors that do not
2852
+ // v2.1.1 - compile-time guard shared by request-scoped accessors that do not
2821
2853
  // follow the req.<bucket> shape (upload/uploads/cookie).
2822
2854
  function routeOnly(name, example) {
2823
2855
  if (!_inRoute) {
@@ -2847,15 +2879,15 @@ let _inRoute = false;
2847
2879
  // True while generating inside a Telegram handler body. Remaps PlainScript's
2848
2880
  // "reply" statement to send a chat message instead of an HTTP response.
2849
2881
  let _inTelegram = false;
2850
- // v2.1.1 — true while generating inside a WhatsApp "on message" handler.
2882
+ // v2.1.1 - true while generating inside a WhatsApp "on message" handler.
2851
2883
  // Remaps PlainScript's "reply" to a WhatsApp chat message and PlainScript's "message"
2852
2884
  // identifier to the normalized message record of the current delivery.
2853
2885
  let _inWhatsApp = false;
2854
- // v2.1.0 — active "group" prefixes. Route paths are prefixed with the
2886
+ // v2.1.0 - active "group" prefixes. Route paths are prefixed with the
2855
2887
  // concatenation of every enclosing group, innermost last.
2856
2888
  const _routePrefixes = [];
2857
2889
 
2858
- // v2.1.0 — active SQL driver. "sqlite" (default) targets better-sqlite3's
2890
+ // v2.1.0 - active SQL driver. "sqlite" (default) targets better-sqlite3's
2859
2891
  // synchronous prepare/run/exec API; "pg" targets node-postgres pools and
2860
2892
  // makes every SQL statement async. Set by database/postgres declarations.
2861
2893
  let _sqlDriver = 'sqlite';
@@ -2868,7 +2900,7 @@ function routePath(path) {
2868
2900
  return _routePrefixes.join('') + path;
2869
2901
  }
2870
2902
 
2871
- // v2.1.0 — render the JavaScript expression that executes one SQL statement
2903
+ // v2.1.0 - render the JavaScript expression that executes one SQL statement
2872
2904
  // under the active driver. kind: query | write | execute.
2873
2905
  function emitSqlCall(kind, sql, params, indent, context) {
2874
2906
  const args = params.join(', ');
@@ -2935,7 +2967,7 @@ function npmPackageName(moduleName) {
2935
2967
 
2936
2968
  function emitRequire(context, moduleName, alias) {
2937
2969
  // A specifier may carry a version range ("left-pad@^1.3.0"). require() takes
2938
- // the bare name only — the range is the installer's business (plain install).
2970
+ // the bare name only - the range is the installer's business (plain install).
2939
2971
  const { name: bareName } = splitPackageSpec(moduleName);
2940
2972
  const npmName = npmPackageName(bareName);
2941
2973
 
@@ -2947,12 +2979,19 @@ function emitRequire(context, moduleName, alias) {
2947
2979
  }
2948
2980
  const known = KNOWN_PACKAGES[bareName];
2949
2981
  if (known) {
2950
- const boundAs = known.match(/const (\w+)/)[1];
2982
+ const boundAs = known.match(/(?:const|let) (\w+)/)[1];
2951
2983
  if (alias !== boundAs) {
2952
2984
  throw new Error(
2953
2985
  `"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
2954
2986
  );
2955
2987
  }
2988
+ const key = `${npmName}\0${alias}`;
2989
+ if (context.requires.has(key)) return '';
2990
+ context.requires.add(key);
2991
+ // Canonical binding, e.g. express to express, sqlite to Database. Using
2992
+ // the KNOWN entry keeps sqlite's lazy loader (better-sqlite3 is an
2993
+ // optional backend) instead of emitting a fresh eager require.
2994
+ return known;
2956
2995
  }
2957
2996
  const key = `${npmName}\0${alias}`;
2958
2997
  if (context.requires.has(key)) return '';
@@ -2965,7 +3004,7 @@ function emitRequire(context, moduleName, alias) {
2965
3004
 
2966
3005
  if (KNOWN_PACKAGES[bareName]) return KNOWN_PACKAGES[bareName];
2967
3006
 
2968
- // RFC-0011 §5.1 — arbitrary npm packages. A name that is not a valid JS
3007
+ // RFC-0011 §5.1 - arbitrary npm packages. A name that is not a valid JS
2969
3008
  // identifier (e.g. node-fetch) is required for its side effect only.
2970
3009
  if (isValidIdentifier(bareName)) {
2971
3010
  return `const ${bareName} = require('${npmName}');`;
@@ -3022,7 +3061,7 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3022
3061
  context = createGenerationContext(opts);
3023
3062
  }
3024
3063
 
3025
- // v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
3064
+ // v1.0.1 - reset per-program test bookkeeping so repeated generate() calls
3026
3065
  // (build pipeline) start clean.
3027
3066
  __testCount = 0;
3028
3067
  __testCatchers = [];
@@ -3063,7 +3102,7 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3063
3102
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
3064
3103
  }
3065
3104
 
3066
- // v1.0.1 — native test runner. When any "test ... done" block exists, emit
3105
+ // v1.0.1 - native test runner. When any "test ... done" block exists, emit
3067
3106
  // the runner helper, register each test after its function declaration, and
3068
3107
  // execute them. Each failure prints a message and sets process.exitCode = 1.
3069
3108
  if (__testCatchers.length > 0) {
@@ -3071,7 +3110,7 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3071
3110
  `const __tests = [];`,
3072
3111
  `function __check(op, a, b) {`,
3073
3112
  ` const ok = op === 'contains'`,
3074
- ` ? String(a).includes(String(b))`,
3113
+ ` ? (a instanceof Set ? a.has(b) : String(a).includes(String(b)))`,
3075
3114
  ` : op === 'is'`,
3076
3115
  ` ? a === b`,
3077
3116
  ` : op === 'raises'`,
@@ -3107,7 +3146,7 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3107
3146
  return jsCode;
3108
3147
  }
3109
3148
 
3110
- // ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
3149
+ // ── v1.0.1 - test DSL bookkeeping ───────────────────────────────────────────
3111
3150
  let __testCount = 0;
3112
3151
  let __testCatchers = [];
3113
3152
  let __inTest = false;
@@ -3120,8 +3159,14 @@ function generateCondition(cond, context) {
3120
3159
  return `${generateExpr(cond.left, context)} ${cond.op} ${generateExpr(cond.right, context)}`;
3121
3160
 
3122
3161
  case 'UnaryCondition':
3123
- if (cond.op === 'isEmpty') return `(${generateExpr(cond.left, context)}).length === 0`;
3124
- if (cond.op === 'isNotEmpty') return `(${generateExpr(cond.left, context)}).length > 0`;
3162
+ if (cond.op === 'isEmpty') {
3163
+ const expr = generateExpr(cond.left, context);
3164
+ return `(${expr} instanceof Map || ${expr} instanceof Set ? ${expr}.size === 0 : (typeof ${expr} === 'object' && ${expr} !== null ? Object.keys(${expr}).length === 0 : (${expr}).length === 0))`;
3165
+ }
3166
+ if (cond.op === 'isNotEmpty') {
3167
+ const expr = generateExpr(cond.left, context);
3168
+ return `(${expr} instanceof Map || ${expr} instanceof Set ? ${expr}.size > 0 : (typeof ${expr} === 'object' && ${expr} !== null ? Object.keys(${expr}).length > 0 : (${expr}).length > 0))`;
3169
+ }
3125
3170
  throw new Error(`Unknown unary condition op "${cond.op}".`);
3126
3171
 
3127
3172
  case 'BetweenCondition': {
@@ -3129,14 +3174,49 @@ function generateCondition(cond, context) {
3129
3174
  return `${expr} >= ${generateExpr(cond.low, context)} && ${expr} <= ${generateExpr(cond.high, context)}`;
3130
3175
  }
3131
3176
 
3132
- case 'StringCondition':
3133
- return `(${generateExpr(cond.left, context)}).${cond.method}(${generateExpr(cond.right, context)})`;
3177
+ case 'InCondition': {
3178
+ const right = generateExpr(cond.right, context);
3179
+ const left = generateExpr(cond.left, context);
3180
+ return `(${right} instanceof Set ? ${right}.has(${left}) : (${right}).includes(${left}))`;
3181
+ }
3182
+
3183
+ case 'NotInCondition': {
3184
+ const right = generateExpr(cond.right, context);
3185
+ const left = generateExpr(cond.left, context);
3186
+ return `!(${right} instanceof Set ? ${right}.has(${left}) : (${right}).includes(${left}))`;
3187
+ }
3134
3188
 
3135
- // v2.1.1 — and / or / not combinators.
3189
+ case 'StringCondition': {
3190
+ const left = generateExpr(cond.left, context);
3191
+ const right = generateExpr(cond.right, context);
3192
+ if (cond.method === 'includes') {
3193
+ return `(${left} instanceof Set ? ${left}.has(${right}) : (${left}).includes(${right}))`;
3194
+ }
3195
+ return `(${left}).${cond.method}(${right})`;
3196
+ }
3197
+
3198
+ // v2.1.1 - and / or / not combinators. The Boolean combinators operate on
3199
+ // the same LogicalCondition nodes at both the condition level and the
3200
+ // expression level, so an operand may be either a pure condition node
3201
+ // (comparison) or an arbitrary value expression (`f()`, a collection, a
3202
+ // number, a `set with ...` literal). Pure conditions recurse through the
3203
+ // condition generator; everything else is emitted as a general expression.
3136
3204
  case 'LogicalCondition': {
3137
- if (cond.op === 'not') return `!(${generateCondition(cond.operand, context)})`;
3205
+ const CONDITION_TYPES = [
3206
+ 'BinaryCondition',
3207
+ 'UnaryCondition',
3208
+ 'BetweenCondition',
3209
+ 'StringCondition',
3210
+ 'InCondition',
3211
+ 'NotInCondition',
3212
+ 'LogicalCondition',
3213
+ ];
3214
+ const emit = (n) => CONDITION_TYPES.includes(n.type)
3215
+ ? generateCondition(n, context)
3216
+ : generateExpr(n, context);
3217
+ if (cond.op === 'not') return `!(${emit(cond.operand)})`;
3138
3218
  const jsOp = cond.op === 'and' ? '&&' : '||';
3139
- return `${generateCondition(cond.left, context)} ${jsOp} ${generateCondition(cond.right, context)}`;
3219
+ return `${emit(cond.left)} ${jsOp} ${emit(cond.right)}`;
3140
3220
  }
3141
3221
 
3142
3222
  default:
@@ -3163,7 +3243,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3163
3243
  return `${indent}console.log(${generateExpr(node.value, context)});`;
3164
3244
 
3165
3245
  case 'GiveStatement':
3166
- return `${indent}return ${generateExpr(node.value, context)};`;
3246
+ return `${indent}return${node.value ? ' ' + generateExpr(node.value, context) : ''};`;
3167
3247
 
3168
3248
  case 'BecomeStatement': {
3169
3249
  // Handle destructuring: [a, b] = arr / {x, y} = obj
@@ -3190,11 +3270,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3190
3270
  return `${indent}${target} ${op} ${value};`;
3191
3271
  }
3192
3272
 
3193
- // v1.0.1 — record kinds: `define a kind called "Person" with ... done`.
3273
+ // v1.0.1 - record kinds: `define a kind called "Person" with ... done`.
3194
3274
  // Names are emitted as a JS factory that returns a fresh plain object with
3195
3275
  // declared defaults. Constructors prompt for required fields at compile
3196
3276
  // time via `create a Person with ...` (see GenerateExpr CreateKind).
3197
- // v1.0.2 — supports `extends` for inheritance.
3277
+ // v1.0.2 - supports `extends` for inheritance.
3198
3278
  case 'DefineKindStatement': {
3199
3279
  let defaults = '';
3200
3280
  if (node.extends) {
@@ -3223,14 +3303,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3223
3303
  ].join('\n');
3224
3304
  }
3225
3305
 
3226
- // v1.0.1 — load env file "<path>": apply KEY=VALUE pairs to process.env.
3306
+ // v1.0.1 - load env file "<path>": apply KEY=VALUE pairs to process.env.
3227
3307
  // Blank lines and `#` comments are skipped; values keep their text.
3228
3308
  case 'LoadEnvFileStatement': {
3229
3309
  ensureBuiltin(context, 'dotenv');
3230
3310
  return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
3231
3311
  }
3232
3312
 
3233
- // v1.0.1 — native test DSL. `test "<name>" ... done` registers a runnable
3313
+ // v1.0.1 - native test DSL. `test "<name>" ... done` registers a runnable
3234
3314
  // unit; all tests are executed after the program body with a tiny runner.
3235
3315
  case 'TestStatement': {
3236
3316
  __testCount++;
@@ -3243,7 +3323,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3243
3323
  return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
3244
3324
  }
3245
3325
 
3246
- // v1.0.1 — assertion `check <a> (equals|is|contains|raises) <b>`.
3326
+ // v1.0.1 - assertion `check <a> (equals|is|contains|raises) <b>`.
3247
3327
  // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
3248
3328
  // inside the runner's try/catch (its thrown error is the subject).
3249
3329
  case 'CheckStatement': {
@@ -3271,7 +3351,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3271
3351
  return exports.map(e => `${indent}${e}`).join('\n');
3272
3352
  }
3273
3353
 
3274
- // v1.0.1 — generators: `yield <expr>` (or bare `yield`).
3354
+ // v1.0.1 - generators: `yield <expr>` (or bare `yield`).
3275
3355
  case 'YieldStatement': {
3276
3356
  if (!context.inFunction) {
3277
3357
  throw new Error('"yield" can only be used inside a function created with "make".\n\nExample:\n make countUp(n)\n let i = 0\n while i less than n\n i = i + 1\n yield i\n done\n done');
@@ -3342,7 +3422,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3342
3422
  return `${indent}let ${node.variable} = await __ask(${prompt});`;
3343
3423
  }
3344
3424
 
3345
- // v2.0.1 — ocr "<image>" as <variable> [using "<lang>"]
3425
+ // v2.0.1 - ocr "<image>" as <variable> [using "<lang>"]
3346
3426
  case 'OcrStatement': {
3347
3427
  ensureBuiltin(context, 'ocr');
3348
3428
  markAsync(context);
@@ -3394,6 +3474,15 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3394
3474
  return out;
3395
3475
  }
3396
3476
 
3477
+ case 'RepeatTimesStatement': {
3478
+ context.loopDepth++;
3479
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
3480
+ context.loopDepth--;
3481
+ const count = generateExpr(node.count, context);
3482
+ const idxVar = `__repeat_i_${context.loopDepth + 1}`;
3483
+ return `${indent}for (let ${idxVar} = 0; ${idxVar} < ${count}; ${idxVar}++) {\n${body}\n${indent}}`;
3484
+ }
3485
+
3397
3486
  case 'ForEachStatement': {
3398
3487
  context.loopDepth++;
3399
3488
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -3405,7 +3494,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3405
3494
  context.loopDepth++;
3406
3495
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
3407
3496
  context.loopDepth--;
3408
- // for index <name> in <collection> — zero-based index over a list.
3497
+ // for index <name> in <collection> - zero-based index over a list.
3409
3498
  if (node.over != null) {
3410
3499
  const coll = generateExpr(node.over, context);
3411
3500
  return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
@@ -3489,7 +3578,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3489
3578
  return `${indent}class ${node.name}${superClass} {\n${body}\n${indent}}`;
3490
3579
  }
3491
3580
 
3492
- // v0.3 — Express runtime
3581
+ // v0.3 - Express runtime
3493
3582
 
3494
3583
  case 'ListenStatement': {
3495
3584
  const prevInHandler = context.inHandler;
@@ -3546,7 +3635,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3546
3635
  return `${indent}res.json({ ${props} });`;
3547
3636
  }
3548
3637
 
3549
- // v1.2 — reply <value> with buttons … done (Telegram inline keyboard).
3638
+ // v1.2 - reply <value> with buttons … done (Telegram inline keyboard).
3550
3639
  // The AST stores rows of { text, data } objects (parser.js). The Telegram
3551
3640
  // runtime's keyboard() expects a flat list of [text, data] pairs, so each
3552
3641
  // button is rendered as [text, data] and rows are merged into that list.
@@ -3560,13 +3649,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3560
3649
  case 'ServeFolderStatement':
3561
3650
  return `${indent}app.use(express.static(${JSON.stringify(node.folder)}));`;
3562
3651
 
3563
- // v0.6 — Express DX
3652
+ // v0.6 - Express DX
3564
3653
 
3565
3654
  case 'WebAppStatement':
3566
3655
  return [
3567
3656
  emitRequire(context, 'express'),
3568
3657
  `${indent}const app = express();`,
3569
- // v2.1.0 — parse JSON request bodies so POST/PUT handlers can read
3658
+ // v2.1.0 - parse JSON request bodies so POST/PUT handlers can read
3570
3659
  // "body of request". Harmless for GET-only v2.0.1 programs.
3571
3660
  `${indent}app.use(express.json());`,
3572
3661
  ]
@@ -3583,7 +3672,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3583
3672
  return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
3584
3673
  }
3585
3674
 
3586
- // v2.1.0 — group "<prefix>" ... done: composes routes under a shared
3675
+ // v2.1.0 - group "<prefix>" ... done: composes routes under a shared
3587
3676
  // prefix. Groups nest; every enclosed route (either form) gets the
3588
3677
  // concatenated prefix. Non-route statements run in program order.
3589
3678
  case 'GroupStatement': {
@@ -3593,7 +3682,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3593
3682
  return body;
3594
3683
  }
3595
3684
 
3596
- // v2.1.0 — status <expr>: sets the HTTP response status code. Only valid
3685
+ // v2.1.0 - status <expr>: sets the HTTP response status code. Only valid
3597
3686
  // inside a route handler (res is in scope there).
3598
3687
  case 'StatusStatement':
3599
3688
  if (!_inRoute) {
@@ -3601,14 +3690,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3601
3690
  }
3602
3691
  return `${indent}res.status(${generateExpr(node.value, context)});`;
3603
3692
 
3604
- // v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route.
3693
+ // v2.2.0 - redirect to "<url>": sends an HTTP redirect from a route.
3605
3694
  case 'RedirectStatement':
3606
3695
  if (!_inRoute) {
3607
3696
  throw new Error('"redirect to" can only be used inside a route handler.\n\nExample:\n route get "/old"\n redirect to "/new"\n done');
3608
3697
  }
3609
3698
  return `${indent}res.redirect(${generateExpr(node.url, context)});`;
3610
3699
 
3611
- // v2.1.0 — allow cors: enables cross-origin requests on the current app.
3700
+ // v2.1.0 - allow cors: enables cross-origin requests on the current app.
3612
3701
  // Applies to routes registered after this statement.
3613
3702
  case 'AllowCorsStatement':
3614
3703
  return [
@@ -3621,7 +3710,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3621
3710
  `${indent}});`,
3622
3711
  ].join('\n');
3623
3712
 
3624
- // ── v2.1.1 — uploads, auth middleware, rate limiting, OAuth ────────────
3713
+ // ── v2.1.1 - uploads, auth middleware, rate limiting, OAuth ────────────
3625
3714
  // These register Express middleware in program order; routes declared
3626
3715
  // after them are protected / wired accordingly.
3627
3716
 
@@ -3634,7 +3723,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3634
3723
  return `${indent}app.use(__uploads({ ${options.join(', ')} }));`;
3635
3724
  }
3636
3725
 
3637
- // require api key from <expr> — rejects requests whose x-api-key header
3726
+ // require api key from <expr> - rejects requests whose x-api-key header
3638
3727
  // does not match. The expected key may come from env("...") or anywhere.
3639
3728
  case 'RequireApiKeyStatement':
3640
3729
  return [
@@ -3676,7 +3765,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3676
3765
  return `${indent}__googleOAuth(app, { ${parts} });`;
3677
3766
  }
3678
3767
 
3679
- // ── v2.1.1 — route-scoped state: cookies and sessions
3768
+ // ── v2.1.1 - route-scoped state: cookies and sessions
3680
3769
 
3681
3770
  case 'DestroySessionStatement':
3682
3771
  if (!_inRoute) {
@@ -3702,7 +3791,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3702
3791
  }
3703
3792
  return `${indent}res.clearCookie(${JSON.stringify(node.name)}, { path: '/' });`;
3704
3793
 
3705
- // when nothing matches … done — the 404 catch-all. Registered in source
3794
+ // when nothing matches … done - the 404 catch-all. Registered in source
3706
3795
  // position, so it must come after every route (Express matches handlers
3707
3796
  // in registration order).
3708
3797
  case 'NotFoundStatement': {
@@ -3716,7 +3805,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3716
3805
  return `${indent}app.use((${handlerAsync}req, res) => {\n${block.out}\n${indent}});`;
3717
3806
  }
3718
3807
 
3719
- // ── v2.1.1 — error handling and retries
3808
+ // ── v2.1.1 - error handling and retries
3720
3809
 
3721
3810
  case 'TryStatement': {
3722
3811
  const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -3788,11 +3877,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3788
3877
  case 'StartStatement':
3789
3878
  return `${indent}app.listen(${generateExpr(node.port, context)});`;
3790
3879
 
3791
- // v0.6 — SQLite DX. v2.1.0 adds parameterized SQL, captured results and
3880
+ // v0.6 - SQLite DX. v2.1.0 adds parameterized SQL, captured results and
3792
3881
  // transactions; the driver switches to PostgreSQL when a "postgres"
3793
3882
  // declaration is active.
3794
3883
 
3795
- // database "<file>" [using "<driver>"] — v2.1.1 opens through the
3884
+ // database "<file>" [using "<driver>"] - v2.1.1 opens through the
3796
3885
  // portable engine chain: better-sqlite3 when its native binding works on
3797
3886
  // this machine, sql.js otherwise ("using" forces one engine). The opened
3798
3887
  // handle exposes the same prepare/exec/transaction surface either way,
@@ -3806,7 +3895,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3806
3895
  return `${indent}const db = await __dbOpen(${JSON.stringify(node.file)}, ${driverArg});`;
3807
3896
  }
3808
3897
 
3809
- // v2.1.0 — postgres "<connection>": node-postgres pool bound to "db".
3898
+ // v2.1.0 - postgres "<connection>": node-postgres pool bound to "db".
3810
3899
  // Every SQL statement afterwards compiles to async pool queries.
3811
3900
  case 'PostgresStatement': {
3812
3901
  _sqlDriver = 'pg';
@@ -3818,19 +3907,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3818
3907
  ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
3819
3908
  }
3820
3909
 
3821
- // v2.2.0 — mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
3910
+ // v2.2.0 - mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
3822
3911
  // Uses the mongodb driver; subsequent query/insert/update/delete/execute
3823
3912
  // statements compile to MongoDB collection operations.
3913
+ // v1.0.362 - mongodb is an optional backend: the require lives inside
3914
+ // __mongoOpen (it is only evaluated when a database is actually opened),
3915
+ // so programs that never use it start without needing the module.
3824
3916
  case 'MongoStatement': {
3825
3917
  _sqlDriver = 'mongo';
3826
3918
  _sqlClientVar = 'db';
3827
3919
  markAsync(context);
3828
3920
  ensureBuiltin(context, 'mongodb');
3829
3921
  const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
3830
- return [
3831
- emitRequire(context, 'mongodb'),
3832
- `${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
3833
- ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
3922
+ return `${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`;
3834
3923
  }
3835
3924
 
3836
3925
  case 'QueryStatement':
@@ -3846,7 +3935,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3846
3935
  case 'ExecuteStatement':
3847
3936
  return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
3848
3937
 
3849
- // v2.1.0 — remember <name> as query|insert|update|delete … done
3938
+ // v2.1.0 - remember <name> as query|insert|update|delete … done
3850
3939
  case 'RememberSqlStatement': {
3851
3940
  const kind = node.kind === 'query' ? 'query'
3852
3941
  : node.kind === 'execute' ? 'execute'
@@ -3856,7 +3945,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3856
3945
  return `${indent}let ${node.name} = ${emitSqlCall(kind, node.sql, node.params, indent, context)};`;
3857
3946
  }
3858
3947
 
3859
- // v2.1.0 — transaction … done: all enclosed database statements run
3948
+ // v2.1.0 - transaction … done: all enclosed database statements run
3860
3949
  // atomically (all succeed or none are applied).
3861
3950
  case 'TransactionStatement': {
3862
3951
  if (_sqlDriver === 'pg') {
@@ -3891,7 +3980,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3891
3980
  ].join('\n');
3892
3981
  }
3893
3982
 
3894
- // v1.2 — Telegram statements
3983
+ // v1.2 - Telegram statements
3895
3984
 
3896
3985
  case 'TelegramCommandStatement': {
3897
3986
  ensureBuiltin(context, 'telegram');
@@ -3920,18 +4009,18 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3920
4009
  return `${indent}await BOT.start();`;
3921
4010
  }
3922
4011
 
3923
- // ── v2.1.1 — WhatsApp statements ────────────────────────────────────────
4012
+ // ── v2.1.1 - WhatsApp statements ────────────────────────────────────────
3924
4013
 
3925
- // whatsapp bot … done — starts the Baileys runtime with the declared
4014
+ // whatsapp bot … done - starts the Baileys runtime with the declared
3926
4015
  // auth folder and login mode, then registers every "on message" handler.
3927
4016
  // When no login line is present (login is null), only registers handlers
3928
- // without auto-starting — used by hybrid bots that pair on-demand.
4017
+ // without auto-starting - used by hybrid bots that pair on-demand.
3929
4018
  case 'WhatsAppBotStatement': {
3930
4019
  ensureBuiltin(context, 'whatsapp');
3931
4020
  markAsync(context);
3932
4021
  const lines = [];
3933
4022
  if (node.login) {
3934
- // v2.1.2 — the pairing phone may be a compile-time literal or any
4023
+ // v2.1.2 - the pairing phone may be a compile-time literal or any
3935
4024
  // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
3936
4025
  // are normalized/validated by __waNormalizePhone at startup.
3937
4026
  let loginArg;
@@ -3957,7 +4046,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3957
4046
  return lines.join('\n');
3958
4047
  }
3959
4048
 
3960
- // pair whatsapp "<phone>" — on-demand WhatsApp pairing session.
4049
+ // pair whatsapp "<phone>" - on-demand WhatsApp pairing session.
3961
4050
  // When _inTelegram is true, relays the pairing code and connection status
3962
4051
  // to the Telegram chat via ctx.chatId.
3963
4052
  case 'WhatsAppPairStatement': {
@@ -3974,7 +4063,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3974
4063
  return `${indent}await __whatsappPair(${phoneArg}, null, null);`;
3975
4064
  }
3976
4065
 
3977
- // on message … done — registers the handler that receives each incoming
4066
+ // on message … done - registers the handler that receives each incoming
3978
4067
  // WhatsApp message as a normalized PlainScript record on `message`.
3979
4068
  case 'WhatsAppOnMessageStatement': {
3980
4069
  ensureBuiltin(context, 'whatsapp');
@@ -3990,7 +4079,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3990
4079
  ].join('\n');
3991
4080
  }
3992
4081
 
3993
- // log message — prints the current message record. Handler-only by
4082
+ // log message - prints the current message record. Handler-only by
3994
4083
  // design: outside "on message" there is no message to log.
3995
4084
  case 'WhatsAppLogStatement':
3996
4085
  if (!_inWhatsApp) {
@@ -3999,7 +4088,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3999
4088
  ensureBuiltin(context, 'whatsapp');
4000
4089
  return `${indent}console.log(__waCtx.message);`;
4001
4090
 
4002
- // v2.14 — download "<path>" — saves the current message's media to a file.
4091
+ // v2.14 - download "<path>" - saves the current message's media to a file.
4003
4092
  // Handler-only by design: outside "on message" there is no message media.
4004
4093
  case 'WhatsAppDownloadStatement':
4005
4094
  if (!_inWhatsApp) {
@@ -4009,7 +4098,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4009
4098
  markAsync(context);
4010
4099
  return `${indent}await __whatsappDownload(__waCtx.message, ${JSON.stringify(node.filePath)});`;
4011
4100
 
4012
- // v2.1.0 — mail, cache, scheduling, background jobs, websocket
4101
+ // v2.1.0 - mail, cache, scheduling, background jobs, websocket
4013
4102
 
4014
4103
  case 'MailTransportStatement': {
4015
4104
  ensureBuiltin(context, 'mailer');
@@ -4043,7 +4132,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4043
4132
  return `${indent}await __mailSend({ ${fields} });`;
4044
4133
  }
4045
4134
 
4046
- // cache "<redis-url>" — connects the shared Redis client. At the top
4135
+ // cache "<redis-url>" - connects the shared Redis client. At the top
4047
4136
  // level the connect is awaited in program order; inside functions it is
4048
4137
  // connected fire-and-forget.
4049
4138
  case 'CacheStatement': {
@@ -4077,7 +4166,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4077
4166
  ].join('\n');
4078
4167
  }
4079
4168
 
4080
- // v1.0.36 — every frame … done: one requestAnimationFrame loop. The next
4169
+ // v1.0.362 - every frame … done: one requestAnimationFrame loop. The next
4081
4170
  // frame is scheduled after the body so the body always runs once per
4082
4171
  // frame; an awaiting body makes the callback async automatically.
4083
4172
  case 'EveryFrameStatement': {
@@ -4094,7 +4183,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4094
4183
  ].join('\n');
4095
4184
  }
4096
4185
 
4097
- // v1.0.36 — after <n> <unit> … done: one-shot setTimeout. The delay is an
4186
+ // v1.0.362 - after <n> <unit> … done: one-shot setTimeout. The delay is an
4098
4187
  // expression scaled by the unit; an awaiting body makes the callback async.
4099
4188
  case 'AfterStatement': {
4100
4189
  const delay = generateExpr(node.delay, context);
@@ -4231,7 +4320,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4231
4320
  return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
4232
4321
  }
4233
4322
 
4234
- // v1.0.36 — when <target> "<event>" happens [as <name>] … done: DOM event
4323
+ // v1.0.362 - when <target> "<event>" happens [as <name>] … done: DOM event
4235
4324
  // listener. The handler param defaults to "event"; an awaiting body makes
4236
4325
  // the callback async automatically.
4237
4326
  case 'WhenTargetedStatement': {
@@ -4281,6 +4370,16 @@ function generateLValue(node, context) {
4281
4370
 
4282
4371
  function generateExpr(node, context = createGenerationContext()) {
4283
4372
  switch (node.type) {
4373
+ case 'BinaryCondition':
4374
+ case 'UnaryCondition':
4375
+ case 'BetweenCondition':
4376
+ case 'InCondition':
4377
+ case 'NotInCondition':
4378
+ case 'StringCondition':
4379
+ case 'LogicalCondition':
4380
+ // Comparisons are first-class expressions (e.g. `(x) -> x is above 3`),
4381
+ // so emit the same code the condition level produces.
4382
+ return generateCondition(node, context);
4284
4383
  case 'DictionaryLiteral': {
4285
4384
  if (!node.pairs || node.pairs.length === 0) return 'new Map()';
4286
4385
  const pairs = node.pairs.map(p => `[${generateExpr(p.key, context)}, ${generateExpr(p.value, context)}]`);
@@ -4315,13 +4414,13 @@ function generateExpr(node, context = createGenerationContext()) {
4315
4414
  case 'CollectionReflectExpression': {
4316
4415
  const target = generateExpr(node.target, context);
4317
4416
  if (node.accessor === 'keys') {
4318
- return `Array.from(${target}.keys())`;
4417
+ return `(${target} instanceof Map || ${target} instanceof Set ? Array.from(${target}.keys()) : Object.keys(${target}))`;
4319
4418
  }
4320
4419
  if (node.accessor === 'values') {
4321
- return `Array.from(${target}.values())`;
4420
+ return `(${target} instanceof Map || ${target} instanceof Set ? Array.from(${target}.values()) : Object.values(${target}))`;
4322
4421
  }
4323
4422
  if (node.accessor === 'entries') {
4324
- return `Array.from(${target}.entries())`;
4423
+ return `(${target} instanceof Map || ${target} instanceof Set ? Array.from(${target}.entries()) : Object.entries(${target}))`;
4325
4424
  }
4326
4425
  if (node.accessor === 'size') {
4327
4426
  return `(${target} instanceof Map || ${target} instanceof Set ? ${target}.size : (${target} && ${target}.size !== undefined ? ${target}.size : ${target}?.length))`;
@@ -4330,23 +4429,11 @@ function generateExpr(node, context = createGenerationContext()) {
4330
4429
  }
4331
4430
  case 'StringLiteral': return JSON.stringify(node.value);
4332
4431
  case 'NumberLiteral': return String(node.value);
4333
- // v2.1.1 — boolean and null literals are PlainScript keywords.
4432
+ // v2.1.1 - boolean and null literals are PlainScript keywords.
4334
4433
  case 'BooleanLiteral': return String(node.value);
4335
4434
  case 'NullLiteral': return 'null';
4336
- // v2.1.1 — arithmetic: unary minus (binary + - * / % reuse
4337
- // BinaryExpression). Binary operands need parentheses so that
4338
- // -(2 + 3) does not flatten to -2 + 3.
4339
- case 'UnaryExpression':
4340
- return `${node.operator}${node.operand.type === 'BinaryExpression'
4341
- ? `(${generateExpr(node.operand, context)})`
4342
- : generateExpr(node.operand, context)}`;
4343
- // v2.1.1 — wait for <expr>: awaits an async value (fetch promises,
4344
- // async functions called from PlainScript, etc.).
4345
- case 'AwaitExpression': {
4346
- markAsync(context);
4347
- return `(await ${generateExpr(node.value, context)})`;
4348
- }
4349
- // v2.1.1 — HTTP client: get/post/put/patch/delete "<url>" with clauses.
4435
+
4436
+ // v2.1.1 - HTTP client: get/post/put/patch/delete "<url>" with clauses.
4350
4437
  case 'HttpCall': {
4351
4438
  ensureBuiltin(context, 'http');
4352
4439
  markAsync(context);
@@ -4409,7 +4496,7 @@ function generateExpr(node, context = createGenerationContext()) {
4409
4496
  return `{ ${props} }`;
4410
4497
  }
4411
4498
 
4412
- // v1.2 — Inline object literal: { key: value, ... }
4499
+ // v1.2 - Inline object literal: { key: value, ... }
4413
4500
  case 'InlineObjectLiteral': {
4414
4501
  const props = node.properties
4415
4502
  .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
@@ -4435,12 +4522,47 @@ function generateExpr(node, context = createGenerationContext()) {
4435
4522
  case 'OptionalCallExpression':
4436
4523
  return `${generateExpr(node.callee.object, context)}?.${node.callee.property}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
4437
4524
 
4525
+ // Function expression: (params) -> expression → (params) => expression.
4526
+ // Block-bodied form: (params) do ... done → (params) => { ... } - reuses
4527
+ // generateBlock, the same body emitter as `make` functions, so closures,
4528
+ // effects, loops, conditionals, early returns, and async/await behave
4529
+ // exactly like ordinary functions.
4530
+ case 'ArrowFunctionExpression': {
4531
+ const prevInFunction = context.inFunction;
4532
+ context.inFunction = true;
4533
+ const prevAwait = context.emittedAwait;
4534
+ context.emittedAwait = false;
4535
+ const paramStr = node.params.map(p => typeof p === 'object' && p ? p.name : p).join(', ');
4536
+ if (node.block) {
4537
+ const block = generateBlock(node.body, ' ', context);
4538
+ const isAsync = block.emitted ? 'async ' : '';
4539
+ context.emittedAwait = prevAwait;
4540
+ context.inFunction = prevInFunction;
4541
+ return `${isAsync}(${paramStr}) => {\n${block.out}\n}`;
4542
+ }
4543
+ const body = generateExpr(node.body, context);
4544
+ const emitted = context.emittedAwait;
4545
+ context.emittedAwait = prevAwait;
4546
+ context.inFunction = prevInFunction;
4547
+ const isAsync = emitted ? 'async ' : '';
4548
+ return `${isAsync}(${paramStr}) => ${body}`;
4549
+ }
4550
+
4438
4551
  case 'CallExpression': {
4439
- // Method call: receiver.method(args). Member access invoked with parens —
4552
+ // Method call: receiver.method(args). Member access invoked with parens -
4440
4553
  // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
4554
+ // Postfix calls f()(), arr[0](1), mul(6)(7) also bind here; any composite
4555
+ // callee (arrow, binary, comparison/logical condition) is parenthesised so
4556
+ // the call still applies to the whole value, not its last operand.
4441
4557
  if (node.callee) {
4442
4558
  const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
4443
- return `${generateExpr(node.callee, context)}(${args})`;
4559
+ const callee = generateExpr(node.callee, context);
4560
+ const composite = node.callee.type === 'ArrowFunctionExpression' ||
4561
+ node.callee.type === 'BinaryExpression' ||
4562
+ node.callee.type === 'LogicalCondition' ||
4563
+ node.callee.type === 'ComparisonCondition' ||
4564
+ node.callee.type === 'UnaryExpression';
4565
+ return `${composite ? `(${callee})` : callee}(${args})`;
4444
4566
  }
4445
4567
  if (STDLIB[node.name]) {
4446
4568
  if (node.name === 'readFile' || node.name === 'writeFile' ||
@@ -4454,7 +4576,7 @@ function generateExpr(node, context = createGenerationContext()) {
4454
4576
  return `${node.name}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
4455
4577
  }
4456
4578
 
4457
- // v1.1 — Item expressions
4579
+ // v1.1 - Item expressions
4458
4580
  case 'FirstItem':
4459
4581
  return `${generateExpr(node.collection, context)}[0]`;
4460
4582
 
@@ -4467,9 +4589,14 @@ function generateExpr(node, context = createGenerationContext()) {
4467
4589
  case 'LengthExpression':
4468
4590
  return `${generateExpr(node.object, context)}.length`;
4469
4591
 
4470
- // v1.1 — Property access
4592
+ case 'CountOfExpression': {
4593
+ const obj = generateExpr(node.object, context);
4594
+ return `((${obj} && ${obj}.count !== undefined) ? ${obj}.count : ((${obj} && ${obj}.length !== undefined) ? ${obj}.length : ((${obj} && ${obj}.size !== undefined) ? ${obj}.size : 0)))`;
4595
+ }
4596
+
4597
+ // v1.1 - Property access
4471
4598
  case 'OfExpression': {
4472
- // v2.1.1 — "session of request" / "user of request" read server-side
4599
+ // v2.1.1 - "session of request" / "user of request" read server-side
4473
4600
  // state managed by the session and OAuth runtimes.
4474
4601
  if (node.object.type === 'Identifier' && node.object.name === 'request' &&
4475
4602
  node.property.type === 'Identifier') {
@@ -4487,18 +4614,21 @@ function generateExpr(node, context = createGenerationContext()) {
4487
4614
  return `${generateExpr(node.object, context)}.${generateExpr(node.property, context)}`;
4488
4615
  }
4489
4616
 
4490
- // v1.1 — Collection operations
4617
+ // v1.1 - Collection operations
4491
4618
  case 'AddCall':
4492
4619
  return `${generateExpr(node.collection, context)}.push(${generateExpr(node.value, context)})`;
4493
4620
 
4494
- case 'RemoveCall':
4495
- return `${generateExpr(node.collection, context)}.splice(${generateExpr(node.collection, context)}.indexOf(${generateExpr(node.value, context)}), 1)`;
4621
+ case 'RemoveCall': {
4622
+ const coll = generateExpr(node.collection, context);
4623
+ const val = generateExpr(node.value, context);
4624
+ return `${coll} instanceof Map || ${coll} instanceof Set ? ${coll}.delete(${val}) : ${coll}.splice(${coll}.indexOf(${val}), 1)`;
4625
+ }
4496
4626
 
4497
4627
  case 'WriteCall':
4498
4628
  ensureBuiltin(context, 'fs');
4499
4629
  return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
4500
4630
 
4501
- // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`
4631
+ // v1.0.1 - record constructor: `create a Person with name "Ada" and age 17`
4502
4632
  // calls the kind factory that `define a kind called "Person"` registered.
4503
4633
  case 'CreateKindExpression': {
4504
4634
  const fields = node.pairs
@@ -4507,7 +4637,7 @@ function generateExpr(node, context = createGenerationContext()) {
4507
4637
  return `${node.kind}({ ${fields} })`;
4508
4638
  }
4509
4639
 
4510
- // v1.0.1 — concurrency combinators: `all of [...]` / `any of [...]` /
4640
+ // v1.0.1 - concurrency combinators: `all of [...]` / `any of [...]` /
4511
4641
  // `settled of [...]`. All are awaited; `settled` returns status records.
4512
4642
  case 'ConcurrencyExpression': {
4513
4643
  markAsync(context);
@@ -4517,7 +4647,7 @@ function generateExpr(node, context = createGenerationContext()) {
4517
4647
  return `(await Promise.all(${rhs}))`;
4518
4648
  }
4519
4649
 
4520
- // v1.0.1 — `spread of <collection>` → a fresh array from an iterable.
4650
+ // v1.0.1 - `spread of <collection>` → a fresh array from an iterable.
4521
4651
  case 'SpreadExpression':
4522
4652
  return `[...${generateExpr(node.collection, context)}]`;
4523
4653