plainscript-lang 1.0.361 → 1.0.363

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 (97) hide show
  1. package/README.md +383 -55
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +224 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +490 -114
  6. package/compiler/ir.js +61 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +234 -0
  9. package/compiler/parser.js +780 -110
  10. package/compiler/type-checker.js +246 -0
  11. package/compiler/version.js +1 -1
  12. package/docs/CAPABILITY_GAP_AUDIT.md +19 -3
  13. package/docs/GAME-PROMPT.md +3 -3
  14. package/docs/PLAINSCRIPT-GRAMMAR.md +308 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +231 -5
  16. package/docs/index.html +5 -5
  17. package/docs/website/script.js +1 -1
  18. package/examples/ai-memory-cli.pln +221 -0
  19. package/examples/ai-memory.json +1 -0
  20. package/examples/ai-providers.pln +1 -1
  21. package/examples/arrays.pln +1 -1
  22. package/examples/async-errors.pln +1 -1
  23. package/examples/auth-api.pln +1 -1
  24. package/examples/auth-sessions.pln +1 -1
  25. package/examples/basics.pln +1 -1
  26. package/examples/bots.pln +1 -1
  27. package/examples/browser-interactive/README.md +1 -1
  28. package/examples/browser-interactive/src/interactive.pln +1 -1
  29. package/examples/cache-and-jobs.pln +1 -1
  30. package/examples/cache-schedule.pln +1 -1
  31. package/examples/canvas-game/README.md +1 -1
  32. package/examples/canvas-game/src/game.pln +1 -1
  33. package/examples/collections.pln +1 -1
  34. package/examples/compound-assignments.pln +24 -0
  35. package/examples/concurrency.pln +2 -2
  36. package/examples/conditions.pln +1 -1
  37. package/examples/database.pln +1 -1
  38. package/examples/day2.pln +1 -1
  39. package/examples/day3.pln +1 -1
  40. package/examples/deployment.pln +1 -1
  41. package/examples/email-send.pln +1 -1
  42. package/examples/error-handling.pln +1 -1
  43. package/examples/expressions.pln +1 -1
  44. package/examples/file-manager-cli.pln +51 -0
  45. package/examples/file-uploads.pln +1 -1
  46. package/examples/files-and-config.pln +1 -1
  47. package/examples/files.pln +1 -1
  48. package/examples/football-backend/app.pln +1 -1
  49. package/examples/functions.pln +1 -1
  50. package/examples/hello.pln +1 -1
  51. package/examples/http-client.pln +1 -1
  52. package/examples/http.pln +1 -1
  53. package/examples/id-verification/app.pln +1 -1
  54. package/examples/interactive-cli.pln +34 -0
  55. package/examples/javascript-library/README.md +1 -1
  56. package/examples/javascript-library/src/interop.pln +1 -1
  57. package/examples/json.pln +1 -1
  58. package/examples/loops.pln +1 -1
  59. package/examples/memoize-demo.pln +31 -0
  60. package/examples/modules/app.pln +1 -1
  61. package/examples/modules/main.pln +1 -1
  62. package/examples/modules/math.pln +1 -1
  63. package/examples/mongo.pln +1 -1
  64. package/examples/normalization-forms.pln +22 -0
  65. package/examples/objects.pln +1 -1
  66. package/examples/ocr.pln +1 -1
  67. package/examples/packages.pln +1 -1
  68. package/examples/random-cli.pln +32 -0
  69. package/examples/record-kinds.pln +1 -1
  70. package/examples/records.pln +1 -1
  71. package/examples/rest-api-fetch.pln +1 -1
  72. package/examples/rest-api.pln +1 -1
  73. package/examples/run-in-parallel.pln +25 -0
  74. package/examples/scheduled-tasks.pln +1 -1
  75. package/examples/search-and-filter.pln +1 -1
  76. package/examples/server.pln +1 -1
  77. package/examples/sessions-and-cookies.pln +1 -1
  78. package/examples/sqlite.pln +1 -1
  79. package/examples/start.pln +1 -1
  80. package/examples/stats-cli.pln +29 -0
  81. package/examples/stdlib.pln +1 -1
  82. package/examples/string-helpers.pln +23 -0
  83. package/examples/string-verbs.pln +1 -1
  84. package/examples/telegram-ai-bot.pln +1 -1
  85. package/examples/telegram-bot.pln +1 -1
  86. package/examples/terminal-cli.pln +11 -0
  87. package/examples/testing.pln +1 -1
  88. package/examples/three-dimensional/README.md +1 -1
  89. package/examples/three-dimensional/src/scene.pln +1 -1
  90. package/examples/todo-cli.pln +98 -0
  91. package/examples/web-api.pln +1 -1
  92. package/examples/web-app.pln +1 -1
  93. package/examples/websocket-server.pln +1 -1
  94. package/examples/websocket.pln +1 -1
  95. package/examples/whatsapp-bot/pairing.pln +1 -1
  96. package/examples/whatsapp-bot/qr.pln +1 -1
  97. package/package.json +16 -6
@@ -6,9 +6,15 @@ 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');`,
10
- fs: `const fs = require('fs');`,
11
- path: `const path = require('path');`,
9
+ // v1.0.363 - 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"'); }; }`,
12
18
  axios: `const axios = require('axios');`,
13
19
  chalk: `const chalk = require('chalk');`,
14
20
  // v2.1.0 - PostgreSQL driver behind the friendly "postgres" name.
@@ -17,6 +23,13 @@ const KNOWN_PACKAGES = {
17
23
  mongodb: `const { MongoClient } = require('mongodb');`,
18
24
  };
19
25
 
26
+ // Node built-ins whose internal runtime binding is namespaced (__fs, __path,
27
+ // __crypto) so generated STDLIB code cannot collide with user variables named
28
+ // fs/path/crypto. `use fs` still binds the public name the user asked for, plus
29
+ // the internal alias; the two bindings are tracked under separate keys so a
30
+ // stdlib prelude (readFile etc.) never suppresses the user-facing binding.
31
+ const ALIASED_NODE_BUILTINS = { fs: 'fs', path: 'path', crypto: 'crypto' };
32
+
20
33
  // PlainScript module names whose npm package name differs from the PlainScript name.
21
34
  // Used to de-duplicate runtime requires across aliases (RFC-0011 §22).
22
35
  const NPM_NAME = {
@@ -39,16 +52,16 @@ const JS_RESERVED = new Set([
39
52
  ]);
40
53
 
41
54
  const BUILTIN_DECLARATIONS = {
42
- fs: `const fs = require('fs');`,
43
- path: `const path = require('path');`,
44
- crypto: `const crypto = require('crypto');`,
55
+ fs: `const __fs = require('fs');`,
56
+ path: `const __path = require('path');`,
57
+ crypto: `const __crypto = require('crypto');`,
45
58
  // v1.0.1 - env-file runtime. Applies KEY=VALUE pairs from a .env file to
46
59
  // process.env. Blank lines and `#` comment lines are skipped.
47
60
  dotenv: [
48
61
  `function __loadEnvFile(path) {`,
49
- ` const fs = require('fs');`,
62
+ ` const __fs = require('fs');`,
50
63
  ` let raw;`,
51
- ` try { raw = fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
64
+ ` try { raw = __fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
52
65
  ` for (const line of raw.split(/\\r?\\n/)) {`,
53
66
  ` const trimmed = line.trim();`,
54
67
  ` if (!trimmed || trimmed.startsWith('#')) continue;`,
@@ -61,7 +74,8 @@ const BUILTIN_DECLARATIONS = {
61
74
  ` }`,
62
75
  `}`,
63
76
  ].join('\n'),
64
- // v1.1.1 - ask runtime (RFC-0011 §14)
77
+ // v1.1.1 - ask runtime (RFC-0011 §14). v1.0.363 also provides confirm /
78
+ // choose for interactive CLI programs.
65
79
  ask: [
66
80
  `const readline = require('readline');`,
67
81
  `async function __ask(prompt = '') {`,
@@ -72,6 +86,26 @@ const BUILTIN_DECLARATIONS = {
72
86
  ` rl.close();`,
73
87
  ` }`,
74
88
  `}`,
89
+ `async function __confirm(prompt) {`,
90
+ ` const answer = await __ask(prompt + ' (y/n) ');`,
91
+ ` return /^(y|yes|true|1)$/i.test(answer.trim());`,
92
+ `}`,
93
+ `async function __choose(prompt, options) {`,
94
+ ` const list = Array.from(options || []);`,
95
+ ` if (list.length === 0) return null;`,
96
+ ` if (list.length === 1) { console.log(prompt + ': ' + list[0]); return list[0]; }`,
97
+ ` const rl = readline.createInterface({ input: process.stdin, output: process.stdout });`,
98
+ ` try {`,
99
+ ` console.log(prompt);`,
100
+ ` list.forEach((option, index) => console.log((index + 1) + ') ' + String(option)));`,
101
+ ` const answer = await new Promise((resolve) => rl.question('Choice (1-' + list.length + '): ', resolve));`,
102
+ ` const picked = parseInt(answer, 10);`,
103
+ ` if (Number.isInteger(picked) && picked >= 1 && picked <= list.length) return list[picked - 1];`,
104
+ ` return null;`,
105
+ ` } finally {`,
106
+ ` rl.close();`,
107
+ ` }`,
108
+ `}`,
75
109
  ].join('\n'),
76
110
  // v2.0.1 - OCR runtime (tesseract.js). Extracts text from an image file.
77
111
  // The worker is created per call and always terminated, so repeated ocr
@@ -88,7 +122,7 @@ const BUILTIN_DECLARATIONS = {
88
122
  ` }`,
89
123
  `}`,
90
124
  ].join('\n'),
91
- // v1.0.361 - DOM browser runtime (select/selectAll/parseHTML). Browser
125
+ // v1.0.363 - DOM browser runtime (select/selectAll/parseHTML). Browser
92
126
  // globals are guarded so the generated JS explains the problem when it is
93
127
  // run under Node instead of failing with a ReferenceError midpoint.
94
128
  dom: [
@@ -107,7 +141,7 @@ const BUILTIN_DECLARATIONS = {
107
141
  ` return template.content;`,
108
142
  `}`,
109
143
  ].join('\n'),
110
- // v1.0.361 - input runtime: pointer coordinates, gamepads, dropped files.
144
+ // v1.0.363 - input runtime: pointer coordinates, gamepads, dropped files.
111
145
  input: [
112
146
  `function __localPoint(e, canvas) {`,
113
147
  ` if (typeof document === 'undefined') throw new Error('localPoint(...) needs a browser (document is not defined in Node).');`,
@@ -125,7 +159,7 @@ const BUILTIN_DECLARATIONS = {
125
159
  ` return [...(event && event.dataTransfer ? event.dataTransfer.files : [])];`,
126
160
  `}`,
127
161
  ].join('\n'),
128
- // v1.0.361 - asset-loading runtime (images, JSON, bytes, data URLs). All
162
+ // v1.0.363 - asset-loading runtime (images, JSON, bytes, data URLs). All
129
163
  // helpers return promises; the STDLIB entries await them.
130
164
  assets: [
131
165
  `function __loadImage(url) {`,
@@ -162,7 +196,7 @@ const BUILTIN_DECLARATIONS = {
162
196
  ` });`,
163
197
  `}`,
164
198
  ].join('\n'),
165
- // v1.0.361 - Web Audio runtime. The AudioContext is created once and shared
199
+ // v1.0.363 - Web Audio runtime. The AudioContext is created once and shared
166
200
  // (browsers cap the number), and resumed on demand because autoplay policies
167
201
  // start it suspended.
168
202
  audio: [
@@ -205,7 +239,7 @@ const BUILTIN_DECLARATIONS = {
205
239
  ` });`,
206
240
  `}`,
207
241
  ].join('\n'),
208
- // v1.0.361 - WebGL runtime: context selection plus the three compile/link/
242
+ // v1.0.363 - WebGL runtime: context selection plus the three compile/link/
209
243
  // buffer helpers behind the gl* stdlib entries.
210
244
  gl: [
211
245
  `function __glContext(canvas) {`,
@@ -379,7 +413,7 @@ const BUILTIN_DECLARATIONS = {
379
413
  ` });`,
380
414
  `}`,
381
415
  ].join('\n'),
382
- // v1.0.35 - dependency-free SVG images and visualizations.
416
+ // v1.0.363 - dependency-free SVG images and visualizations.
383
417
  // The image value is an SVG string, so it can be saved, embedded, or returned
384
418
  // from a web route without a native graphics dependency.
385
419
  visualization: [
@@ -532,8 +566,8 @@ const BUILTIN_DECLARATIONS = {
532
566
  // v1.0.1 - dynamic module loader.
533
567
  loadmodule: [
534
568
  `function __loadModule(spec) {`,
535
- ` const path = require('path');`,
536
- ` const target = (spec[0] === '.' ) ? path.resolve(process.cwd(), spec) : spec;`,
569
+ ` const __path = require('path');`,
570
+ ` const target = (spec[0] === '.' ) ? __path.resolve(process.cwd(), spec) : spec;`,
537
571
  ` try { return require(target); }`,
538
572
  ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
539
573
  `}`,
@@ -541,13 +575,13 @@ const BUILTIN_DECLARATIONS = {
541
575
  // v1.0.1 - recursive directory walker (returns full paths, files first).
542
576
  walk: [
543
577
  `function __walkFolder(dir) {`,
544
- ` const fs = require('fs');`,
545
- ` const path = require('path');`,
578
+ ` const __fs = require('fs');`,
579
+ ` const __path = require('path');`,
546
580
  ` const out = [];`,
547
581
  ` function rec(d) {`,
548
- ` for (const entry of fs.readdirSync(d)) {`,
549
- ` const full = path.join(d, entry);`,
550
- ` const st = fs.statSync(full);`,
582
+ ` for (const entry of __fs.readdirSync(d)) {`,
583
+ ` const full = __path.join(d, entry);`,
584
+ ` const st = __fs.statSync(full);`,
551
585
  ` if (st.isDirectory()) rec(full);`,
552
586
  ` else out.push(full);`,
553
587
  ` }`,
@@ -729,10 +763,10 @@ const BUILTIN_DECLARATIONS = {
729
763
  ` const raw = message && message.raw ? message.raw : message;`,
730
764
  ` const buffer = await downloadMediaMessage(raw, 'buffer', {}, { logger: __waSilentLogger, reuploadRequest: sock.updateMediaMessage });`,
731
765
  ` if (!dest) return buffer;`,
732
- ` const fs = require('fs'), path = require('path');`,
733
- ` const dir = path.dirname(path.resolve(dest));`,
734
- ` if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });`,
735
- ` fs.writeFileSync(dest, buffer);`,
766
+ ` const __fs = require('fs'), __path = require('path');`,
767
+ ` const dir = __path.dirname(__path.resolve(dest));`,
768
+ ` if (dir && dir !== '.') __fs.mkdirSync(dir, { recursive: true });`,
769
+ ` __fs.writeFileSync(dest, buffer);`,
736
770
  ` return dest;`,
737
771
  ` }`,
738
772
  ` async function __whatsappDownload(message, dest) {`,
@@ -1082,7 +1116,7 @@ const BUILTIN_DECLARATIONS = {
1082
1116
  ].join('\n'),
1083
1117
  // v2.1.1 - file upload runtime (multer behind "accept uploads"). Files are
1084
1118
  // held in memory by default or written to disk when a folder is given.
1085
- // Normalised records expose: name, type, size, data (buffer) and path.
1119
+ // Normalised records expose: name, type, size, data (buffer) and __path.
1086
1120
  uploads: [
1087
1121
  `function __uploads(options = {}) {`,
1088
1122
  ` const multer = require('multer');`,
@@ -1322,8 +1356,8 @@ const BUILTIN_DECLARATIONS = {
1322
1356
  // IOPL-native - line-by-line file streaming runtime.
1323
1357
  __streamFile: [
1324
1358
  `async function __streamFile(path, fn) {`,
1325
- ` const fs = require('fs');`,
1326
- ` const rl = require('readline').createInterface({ input: fs.createReadStream(path), crlfDelay: Infinity });`,
1359
+ ` const __fs = require('fs');`,
1360
+ ` const rl = require('readline').createInterface({ input: __fs.createReadStream(path), crlfDelay: Infinity });`,
1327
1361
  ` for await (const line of rl) await fn(line);`,
1328
1362
  `}`,
1329
1363
  ].join('\n'),
@@ -1345,7 +1379,12 @@ const BUILTIN_DECLARATIONS = {
1345
1379
  ` }`,
1346
1380
  ` console.error('PlainScript: native SQLite unavailable (' + __sqliteNativeReason + '); using the WebAssembly engine instead.');`,
1347
1381
  ` }`,
1348
- ` const initSqlJs = require('sql.js');`,
1382
+ ` let initSqlJs;`,
1383
+ ` try {`,
1384
+ ` initSqlJs = require('sql.js');`,
1385
+ ` } catch (__e) {`,
1386
+ ` 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');`,
1387
+ ` }`,
1349
1388
  ` const SQL = await initSqlJs();`,
1350
1389
  ` let raw;`,
1351
1390
  ` try {`,
@@ -1379,8 +1418,14 @@ const BUILTIN_DECLARATIONS = {
1379
1418
  ` };`,
1380
1419
  `}`,
1381
1420
  `function __sqliteWrapWasm(db, file) {`,
1421
+ ` // v1.0.363 - sql.js's export() ends an open transaction, so persisting`,
1422
+ ` // mid-transaction would break the explicit COMMIT that follows. While a`,
1423
+ ` // transaction is active, writes are only flushed to disk once, after the`,
1424
+ ` // COMMIT succeeds (the wrapper's own persist at that point covers it).`,
1425
+ ` let __sqliteTxn = 0;`,
1382
1426
  ` const persist = () => {`,
1383
1427
  ` if (file === ':memory:') return;`,
1428
+ ` if (__sqliteTxn > 0) return;`,
1384
1429
  ` try {`,
1385
1430
  ` require('fs').writeFileSync(file, Buffer.from(db.export()));`,
1386
1431
  ` } catch (error) {`,
@@ -1420,15 +1465,19 @@ const BUILTIN_DECLARATIONS = {
1420
1465
  ` transaction(fn) {`,
1421
1466
  ` return () => {`,
1422
1467
  ` db.run('BEGIN');`,
1468
+ ` __sqliteTxn++;`,
1469
+ ` let out;`,
1423
1470
  ` try {`,
1424
- ` const out = fn();`,
1471
+ ` out = fn();`,
1425
1472
  ` db.run('COMMIT');`,
1426
- ` persist();`,
1427
- ` return out;`,
1428
1473
  ` } catch (error) {`,
1429
1474
  ` try { db.run('ROLLBACK'); } catch (_) {}`,
1430
1475
  ` throw error;`,
1476
+ ` } finally {`,
1477
+ ` __sqliteTxn--;`,
1431
1478
  ` }`,
1479
+ ` persist();`,
1480
+ ` return out;`,
1432
1481
  ` };`,
1433
1482
  ` },`,
1434
1483
  ` };`,
@@ -1666,8 +1715,8 @@ const BUILTIN_DECLARATIONS = {
1666
1715
  sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1667
1716
  // v0.6 - runtime standard library
1668
1717
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1669
- readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1670
- writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
1718
+ readFile: (args, context) => `__fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1719
+ writeFile: (args, context) => `__fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
1671
1720
  // v2.4.0 - dependency-free SVG image and visualization helpers.
1672
1721
  svgImage: (args, context) => {
1673
1722
  ensureBuiltin(context, 'visualization');
@@ -1689,9 +1738,23 @@ const BUILTIN_DECLARATIONS = {
1689
1738
  ensureBuiltin(context, 'visualization');
1690
1739
  return `__imageDataUri(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1691
1740
  },
1692
- fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
1693
- read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1694
- sleep: (args, context) => `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${generateExpr(args[0], context)})`,
1741
+ fileExists: (args, context) => `__fs.existsSync(${generateExpr(args[0], context)})`,
1742
+ read: (args, context) => `__fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1743
+ // v1.0.363 - write(data, "file") mirrors the natural form write(data to
1744
+ // "file") and writeFile("file", data); previously only the "to" form existed
1745
+ // and the comma spelling produced "write is not defined" at runtime.
1746
+ write: (args, context) => {
1747
+ requireArgs('write', args, 2, 'write(data, "file.txt")');
1748
+ // fs.writeFileSync(path, data): data first in PlainScript, file first in fs.
1749
+ return `__fs.writeFileSync(${generateExpr(args[1], context)}, ${generateExpr(args[0], context)}, 'utf8')`;
1750
+ },
1751
+ // sleep(ms) is genuinely async: it yields a promise so it composes with
1752
+ // all of / any of / wait for. The old Atomics.wait spelling blocked the
1753
+ // whole event loop and silently serialized "parallel" code.
1754
+ sleep: (args, context) => {
1755
+ requireArgs('sleep', args, 1, 'sleep(ms)');
1756
+ return `new Promise(r => setTimeout(r, ${generateExpr(args[0], context)}))`;
1757
+ },
1695
1758
  time: (_args) => `Date.now()`,
1696
1759
  date: (_args) => `new Date().toISOString()`,
1697
1760
  jsonEncode: (args, context) => `JSON.stringify(${generateExpr(args[0], context)})`,
@@ -1766,20 +1829,20 @@ const BUILTIN_DECLARATIONS = {
1766
1829
 
1767
1830
  // ── v2.1.0 - filesystem helpers (sync, matching readFile/writeFile style)
1768
1831
 
1769
- copyFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.copyFileSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1770
- moveFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.renameSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1771
- deleteFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.unlinkSync(${generateExpr(args[0], context)})`; },
1772
- makeFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.mkdirSync(${generateExpr(args[0], context)}, { recursive: true })`; },
1773
- deleteFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.rmSync(${generateExpr(args[0], context)}, { recursive: true, force: true })`; },
1774
- listFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.readdirSync(${generateExpr(args[0], context)})`; },
1832
+ copyFile: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.copyFileSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1833
+ moveFile: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.renameSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1834
+ deleteFile: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.unlinkSync(${generateExpr(args[0], context)})`; },
1835
+ makeFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.mkdirSync(${generateExpr(args[0], context)}, { recursive: true })`; },
1836
+ deleteFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.rmSync(${generateExpr(args[0], context)}, { recursive: true, force: true })`; },
1837
+ listFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.readdirSync(${generateExpr(args[0], context)})`; },
1775
1838
  appendFile: (args, context) => {
1776
1839
  ensureBuiltin(context, 'fs');
1777
- return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`;
1840
+ return `__fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`;
1778
1841
  },
1779
- readBytes: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.readFileSync(${generateExpr(args[0], context)})`; },
1842
+ readBytes: (args, context) => { ensureBuiltin(context, 'fs'); return `__fs.readFileSync(${generateExpr(args[0], context)})`; },
1780
1843
  writeBytes: (args, context) => {
1781
1844
  ensureBuiltin(context, 'fs');
1782
- return `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1845
+ return `__fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1783
1846
  },
1784
1847
 
1785
1848
  // ── v2.1.0 - text, number and collection helpers
@@ -2130,15 +2193,15 @@ const BUILTIN_DECLARATIONS = {
2130
2193
  bytesToText: (args, context) => `Buffer.from(${generateExpr(args[0], context)}).toString('utf8')`,
2131
2194
  sha256: (args, context) => {
2132
2195
  ensureBuiltin(context, 'crypto');
2133
- return `crypto.createHash('sha256').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2196
+ return `__crypto.createHash('sha256').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2134
2197
  },
2135
2198
  sha1: (args, context) => {
2136
2199
  ensureBuiltin(context, 'crypto');
2137
- return `crypto.createHash('sha1').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2200
+ return `__crypto.createHash('sha1').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2138
2201
  },
2139
2202
  md5: (args, context) => {
2140
2203
  ensureBuiltin(context, 'crypto');
2141
- return `crypto.createHash('md5').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2204
+ return `__crypto.createHash('md5').update(String(${generateExpr(args[0], context)})).digest('hex')`;
2142
2205
  },
2143
2206
 
2144
2207
  // Serialization - minimal dependency-free YAML subset (see __yamlParse).
@@ -2168,6 +2231,46 @@ const BUILTIN_DECLARATIONS = {
2168
2231
  return `(await __withTimeout(${generateExpr(args[0], context)}${ms}))`;
2169
2232
  },
2170
2233
 
2234
+ // ── v1.0.363 - interactive CLI / terminal ───────────────────────────────
2235
+ // confirm "Delete this file?" -> boolean (y/n prompt)
2236
+ // choose "Pick one" list with "a", "b" -> the chosen option
2237
+ // clearTerminal() / terminalWidth() / terminalHeight() / stderr(...)
2238
+ confirm: (args, context) => {
2239
+ ensureBuiltin(context, 'ask');
2240
+ markAsync(context);
2241
+ return `(await __confirm(${generateExpr(args[0], context)}))`;
2242
+ },
2243
+ choose: (args, context) => {
2244
+ ensureBuiltin(context, 'ask');
2245
+ markAsync(context);
2246
+ return `(await __choose(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}))`;
2247
+ },
2248
+ clearTerminal: () => `(process.stdout.write('\\x1b[2J\\x1b[H'), undefined)`,
2249
+ terminalWidth: () => `(process.stdout.columns || 80)`,
2250
+ terminalHeight: () => `(process.stdout.rows || 24)`,
2251
+ stderr: (args, context) => `(console.error(${args.map(a => generateExpr(a, context)).join(', ')}))`,
2252
+
2253
+ // ── v1.0.363 - statistics, vectors, randomness ──────────────────────────
2254
+ // Data + AI-readiness primitives for numeric arrays and sampling. All are
2255
+ // pure, deterministic helpers except the random* family.
2256
+ mean: (args, context) => `((a) => a.length ? a.reduce((x, y) => x + y, 0) / a.length : NaN)(${generateExpr(args[0], context)})`,
2257
+ median: (args, context) => `((a) => { const s = a.slice().sort((x, y) => x - y); const m = Math.floor(s.length / 2); return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : NaN; })(${generateExpr(args[0], context)})`,
2258
+ variance: (args, context) => `((a) => { const m = a.reduce((x, y) => x + y, 0) / (a.length || 1); return a.length > 1 ? a.reduce((s, x) => s + (x - m) * (x - m), 0) / (a.length - 1) : 0; })(${generateExpr(args[0], context)})`,
2259
+ deviation: (args, context) => `Math.sqrt(((a) => { const m = a.reduce((x, y) => x + y, 0) / (a.length || 1); return a.length > 1 ? a.reduce((s, x) => s + (x - m) * (x - m), 0) / (a.length - 1) : 0; })(${generateExpr(args[0], context)}))`,
2260
+ dotProduct: (args, context) => `((a, b) => a.reduce((s, x, i) => s + x * b[i], 0))(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2261
+ magnitude: (args, context) => `Math.hypot(...${generateExpr(args[0], context)})`,
2262
+ normalize: (args, context) => `((v) => { const m = Math.hypot(...v); return m === 0 ? v.map(x => 0) : v.map(x => x / m); })(${generateExpr(args[0], context)})`,
2263
+ randomInteger: (args, context) => `(Math.floor(Math.random() * (${generateExpr(args[1], context)} - ${generateExpr(args[0], context)} + 1)) + ${generateExpr(args[0], context)})`,
2264
+ randomChoice: (args, context) => `((a) => a[Math.floor(Math.random() * a.length)] || a[0])(${generateExpr(args[0], context)})`,
2265
+ shuffle: (args, context) => `((a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const t = a[i]; a[i] = a[j]; a[j] = t; } return a; })(${generateExpr(args[0], context)})`,
2266
+ sample: (args, context) => `((a, n) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const t = a[i]; a[i] = a[j]; a[j] = t; } return a.slice(0, n); })(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2267
+ weightedChoice: (args, context) => `((items, weights) => { const total = weights.reduce((x, y) => x + y, 0); if (total <= 0) return items[items.length - 1]; let r = Math.random() * total; for (let i = 0; i < items.length; i++) { r -= weights[i]; if (r <= 0) return items[i]; } return items[items.length - 1]; })(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2268
+
2269
+ // ── v1.0.363 - memoization, boolean/character string helpers ────────────
2270
+ memoize: (args, context) => `((f) => { const cache = new Map(); return function (...callArgs) { const key = callArgs.join('\\u0000'); if (cache.has(key)) return cache.get(key); const value = f(...callArgs); cache.set(key, value); return value; }; })(${generateExpr(args[0], context)})`,
2271
+ parseBoolean: (args, context) => `(['true', 'yes', '1', 'on'].includes(String(${generateExpr(args[0], context)}).trim().toLowerCase()))`,
2272
+ characters: (args, context) => `[...String(${generateExpr(args[0], context)})]`,
2273
+
2171
2274
  // Generators / iterables
2172
2275
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
2173
2276
 
@@ -2239,15 +2342,15 @@ const BUILTIN_DECLARATIONS = {
2239
2342
  // Filesystem metadata, walking, and path helpers
2240
2343
  fileSize: (args, context) => {
2241
2344
  ensureBuiltin(context, 'fs');
2242
- return `fs.statSync(${generateExpr(args[0], context)}).size`;
2345
+ return `__fs.statSync(${generateExpr(args[0], context)}).size`;
2243
2346
  },
2244
2347
  fileType: (args, context) => {
2245
2348
  ensureBuiltin(context, 'fs');
2246
- return `fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
2349
+ return `__fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
2247
2350
  },
2248
2351
  lastModified: (args, context) => {
2249
2352
  ensureBuiltin(context, 'fs');
2250
- return `new Date(fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
2353
+ return `new Date(__fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
2251
2354
  },
2252
2355
  walkFolder: (args, context) => {
2253
2356
  ensureBuiltin(context, 'walk');
@@ -2255,29 +2358,29 @@ const BUILTIN_DECLARATIONS = {
2255
2358
  },
2256
2359
  joinPath: (_args, context) => {
2257
2360
  ensureBuiltin(context, 'path');
2258
- return `path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
2361
+ return `__path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
2259
2362
  },
2260
2363
  baseName: (_args, context) => {
2261
2364
  ensureBuiltin(context, 'path');
2262
- return `path.basename(${generateExpr(_args[0], context)})`;
2365
+ return `__path.basename(${generateExpr(_args[0], context)})`;
2263
2366
  },
2264
2367
  folderOf: (_args, context) => {
2265
2368
  ensureBuiltin(context, 'path');
2266
- return `path.dirname(${generateExpr(_args[0], context)})`;
2369
+ return `__path.dirname(${generateExpr(_args[0], context)})`;
2267
2370
  },
2268
2371
  extensionOf: (_args, context) => {
2269
2372
  ensureBuiltin(context, 'path');
2270
- return `path.extname(${generateExpr(_args[0], context)})`;
2373
+ return `__path.extname(${generateExpr(_args[0], context)})`;
2271
2374
  },
2272
2375
 
2273
2376
  // Streams
2274
2377
  writeLine: (args, context) => {
2275
2378
  ensureBuiltin(context, 'fs');
2276
- return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
2379
+ return `__fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
2277
2380
  },
2278
2381
  appendLine: (args, context) => {
2279
2382
  ensureBuiltin(context, 'fs');
2280
- return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
2383
+ return `__fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
2281
2384
  },
2282
2385
 
2283
2386
  // ── v1.0.2 - Extended Math functions (IOPL-native).
@@ -2664,7 +2767,7 @@ const BUILTIN_DECLARATIONS = {
2664
2767
  file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2665
2768
  formData: (_args) => `new FormData()`,
2666
2769
 
2667
- // ── v1.0.361 - browser DOM (IOPL-native). All helpers guard their browser
2770
+ // ── v1.0.363 - browser DOM (IOPL-native). All helpers guard their browser
2668
2771
  // global, so the generated output throws a clear teaching error under Node.
2669
2772
  select: (args, context) => {
2670
2773
  ensureBuiltin(context, 'dom');
@@ -2682,7 +2785,7 @@ const BUILTIN_DECLARATIONS = {
2682
2785
  return `__parseHTML(${generateExpr(args[0], context)})`;
2683
2786
  },
2684
2787
 
2685
- // ── v1.0.361 - browser input (IOPL-native).
2788
+ // ── v1.0.363 - browser input (IOPL-native).
2686
2789
  localPoint: (args, context) => {
2687
2790
  ensureBuiltin(context, 'input');
2688
2791
  requireArgs('localPoint', args, 2, 'localPoint(event, canvas)');
@@ -2698,7 +2801,7 @@ const BUILTIN_DECLARATIONS = {
2698
2801
  return `__droppedFiles(${generateExpr(args[0], context)})`;
2699
2802
  },
2700
2803
 
2701
- // ── v1.0.361 - browser assets (IOPL-native). Each awaitable helper is
2804
+ // ── v1.0.363 - browser assets (IOPL-native). Each awaitable helper is
2702
2805
  // awaited here, so the surrounding function/handler is marked async.
2703
2806
  loadImage: (args, context) => {
2704
2807
  ensureBuiltin(context, 'assets');
@@ -2731,7 +2834,7 @@ const BUILTIN_DECLARATIONS = {
2731
2834
  return `(await __readDataUrl(${generateExpr(args[0], context)}))`;
2732
2835
  },
2733
2836
 
2734
- // ── v1.0.361 - Web Audio (IOPL-native).
2837
+ // ── v1.0.363 - Web Audio (IOPL-native).
2735
2838
  audioContext: (_args, context) => {
2736
2839
  ensureBuiltin(context, 'audio');
2737
2840
  return `__audioContext()`;
@@ -2742,7 +2845,7 @@ const BUILTIN_DECLARATIONS = {
2742
2845
  return `__audioTone(${args.map(a => generateExpr(a, context)).join(', ')})`;
2743
2846
  },
2744
2847
 
2745
- // ── v1.0.361 - WebSocket send helper (works with any WebSocket-like object,
2848
+ // ── v1.0.363 - WebSocket send helper (works with any WebSocket-like object,
2746
2849
  // browser or Node): strings go through verbatim, everything else is JSON.
2747
2850
  webSocketSend: (args, context) => {
2748
2851
  requireArgs('webSocketSend', args, 2, 'webSocketSend(socket, { type: "move", x: 10 })');
@@ -2751,7 +2854,7 @@ const BUILTIN_DECLARATIONS = {
2751
2854
  return `${ws}.send(typeof (${value}) === 'string' ? (${value}) : JSON.stringify(${value}))`;
2752
2855
  },
2753
2856
 
2754
- // ── v1.0.361 - WebGL (IOPL-native).
2857
+ // ── v1.0.363 - WebGL (IOPL-native).
2755
2858
  webglContext: (args, context) => {
2756
2859
  ensureBuiltin(context, 'gl');
2757
2860
  requireOneArg('webglContext', args);
@@ -2811,6 +2914,42 @@ function generateBlock(statements, indent, context) {
2811
2914
  return { out, emitted };
2812
2915
  }
2813
2916
 
2917
+ // Runtime contract support for the contextual `type` declaration. Schemas are
2918
+ // deliberately plain data so a future static checker or alternate backend can
2919
+ // consume the same AST representation.
2920
+ function ensureTypeRuntime(context) {
2921
+ if (context.typeRuntime) return;
2922
+ context.typeRuntime = true;
2923
+ context.pendingPrelude.push([
2924
+ 'const __plainTypes = Object.create(null);',
2925
+ 'function __plainMatchesType(value, spec, path) {',
2926
+ ' if (spec.kind === "optional") return value == null || __plainMatchesType(value, spec.value, path);',
2927
+ ' if (spec.kind === "union") return spec.values.some(s => __plainMatchesType(value, s, path));',
2928
+ ' if (spec.kind === "list") return Array.isArray(value) && value.every((v, i) => __plainMatchesType(v, spec.value, `${path}[${i}]`));',
2929
+ ' if (spec.kind === "dictionary") return value !== null && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([k, v]) => __plainMatchesType(v, spec.value, `${path}.${k}`));',
2930
+ ' if (spec.name === "any") return true;',
2931
+ ' if (spec.name === "number") return typeof value === "number" && Number.isFinite(value);',
2932
+ ' if (spec.name === "text") return typeof value === "string";',
2933
+ ' if (spec.name === "boolean") return typeof value === "boolean";',
2934
+ ' if (spec.name === "null") return value === null;',
2935
+ ' if (spec.name === "object") return value !== null && typeof value === "object";',
2936
+ ' try { __plainValidateType(spec.name, value, path); return true; } catch (_) { return false; }',
2937
+ '}',
2938
+ 'function __plainValidateType(name, value, path = name) {',
2939
+ ' const schema = __plainTypes[name];',
2940
+ ' if (!schema) throw new Error(`Unknown PlainScript type "${name}".`);',
2941
+ ' if (value == null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object matching type ${name}.`);',
2942
+ ' for (const field of schema.fields) {',
2943
+ ' const fieldPath = `${path}.${field.key}`;',
2944
+ ' if (value[field.key] === undefined) { if (field.type.kind !== "optional") throw new Error(`${fieldPath} is required by type ${name}.`); continue; }',
2945
+ ' if (!__plainMatchesType(value[field.key], field.type, fieldPath)) throw new Error(`${fieldPath} does not match type ${name}.${field.key}.`);',
2946
+ ' }',
2947
+ ' return true;',
2948
+ '}',
2949
+ 'function __plainAssertType(spec, value, path) { if (!__plainMatchesType(value, spec, path)) throw new Error(`${path} does not match its declared type.`); return value; }',
2950
+ ].join('\n'));
2951
+ }
2952
+
2814
2953
  // v2.1.0 - generate a request accessor (param/query/header). These compile to
2815
2954
  // direct Express req.<bucket>[key] reads and are rejected outside routes so
2816
2955
  // mistakes surface at compile time with a teaching error.
@@ -2900,11 +3039,31 @@ function emitSqlCall(kind, sql, params, indent, context) {
2900
3039
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
2901
3040
  case 'update': return `db.prepare(\`${sql}\`).run(${args})`;
2902
3041
  case 'delete': return `db.prepare(\`${sql}\`).run(${args})`;
2903
- case 'execute': return `db.exec(\`${sql}\`)`;
3042
+ case 'execute':
3043
+ // Raw exec is fine for constant SQL, but `execute` with {placeholders}
3044
+ // must bind them: db.exec() accepts no parameters and would silently
3045
+ // insert NULLs, so use a prepared statement when any are present.
3046
+ return params.length === 0
3047
+ ? `db.exec(\`${sql}\`)`
3048
+ : `db.prepare(\`${sql}\`).run(${args})`;
2904
3049
  default: throw new Error(`Unknown SQL kind "${kind}".`);
2905
3050
  }
2906
3051
  }
2907
3052
 
3053
+ // v1.0.364 - node types that generateCondition handles directly. Inside
3054
+ // "a and b" / "a or b" chains, operands of these types keep the classic inline
3055
+ // emission; anything else is a value expression and is evaluated exactly once.
3056
+ const CONDITION_TYPES = new Set([
3057
+ 'BinaryCondition',
3058
+ 'UnaryCondition',
3059
+ 'BetweenCondition',
3060
+ 'StringCondition',
3061
+ 'InCondition',
3062
+ 'NotInCondition',
3063
+ 'ConditionExpression',
3064
+ 'LogicalCondition',
3065
+ ]);
3066
+
2908
3067
  function createGenerationContext(options = {}) {
2909
3068
  const sourceMap = options.sourceMap || false;
2910
3069
  const sourceFile = options.sourceFile || 'source.pln';
@@ -2926,6 +3085,10 @@ function createGenerationContext(options = {}) {
2926
3085
  sourceContent,
2927
3086
  sourceMapBuilder: builder,
2928
3087
  currentLine: 1,
3088
+ bundled: false, // true while generating inside a multi-file bundle
3089
+ pendingExports: [], // per-file deferred export assignments (emitted at end of file)
3090
+ importSurfaces: null, // Map<path, string[]> of local module export surfaces (bundler)
3091
+ typeRuntime: false,
2929
3092
  };
2930
3093
  }
2931
3094
 
@@ -2956,12 +3119,19 @@ function emitRequire(context, moduleName, alias) {
2956
3119
  }
2957
3120
  const known = KNOWN_PACKAGES[bareName];
2958
3121
  if (known) {
2959
- const boundAs = known.match(/const (\w+)/)[1];
3122
+ const boundAs = known.match(/(?:const|let) (\w+)/)[1];
2960
3123
  if (alias !== boundAs) {
2961
3124
  throw new Error(
2962
3125
  `"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
2963
3126
  );
2964
3127
  }
3128
+ const key = `${npmName}\0${alias}`;
3129
+ if (context.requires.has(key)) return '';
3130
+ context.requires.add(key);
3131
+ // Canonical binding, e.g. express to express, sqlite to Database. Using
3132
+ // the KNOWN entry keeps sqlite's lazy loader (better-sqlite3 is an
3133
+ // optional backend) instead of emitting a fresh eager require.
3134
+ return known;
2965
3135
  }
2966
3136
  const key = `${npmName}\0${alias}`;
2967
3137
  if (context.requires.has(key)) return '';
@@ -2969,6 +3139,20 @@ function emitRequire(context, moduleName, alias) {
2969
3139
  return `const ${alias} = require('${npmName}');`;
2970
3140
  }
2971
3141
 
3142
+ // `use fs` / `use path` / `use crypto` bind the PUBLIC name only
3143
+ // (fs.readFileSync(...)). The namespaced internal alias (__fs etc.) is owned
3144
+ // exclusively by the stdlib prelude, so the two can never collide and Node's
3145
+ // module cache makes both requires the same object anyway. Tracked under its
3146
+ // own key: a stdlib prelude that already required the module must not
3147
+ // suppress the user-facing binding (and vice versa).
3148
+ if (ALIASED_NODE_BUILTINS[bareName]) {
3149
+ const key = `${bareName}:user`;
3150
+ if (context.requires.has(key)) return '';
3151
+ context.requires.add(key);
3152
+ const publicName = ALIASED_NODE_BUILTINS[bareName];
3153
+ return `const ${publicName} = require('${npmName}');`;
3154
+ }
3155
+
2972
3156
  if (context.requires.has(npmName)) return '';
2973
3157
  context.requires.add(npmName);
2974
3158
 
@@ -3000,7 +3184,7 @@ function containsYield(statements) {
3000
3184
  if (stmt.type === 'IfStatement') {
3001
3185
  if (containsYield(stmt.consequent)) return true;
3002
3186
  if (stmt.alternate && containsYield(stmt.alternate)) return true;
3003
- } else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
3187
+ } else if (stmt.type !== 'FunctionDeclaration' && stmt.type !== 'IntentDeclaration' && stmt.body && Array.isArray(stmt.body)) {
3004
3188
  if (containsYield(stmt.body)) return true;
3005
3189
  }
3006
3190
  }
@@ -3037,6 +3221,40 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3037
3221
  __testCatchers = [];
3038
3222
  __inTest = false;
3039
3223
 
3224
+ // Duplicate top-level declaration check: two `remember x` statements at the
3225
+ // top level of one file (or across bundled files sharing the flat scope)
3226
+ // emit two `let x` bindings, which Node reports as a raw SyntaxError with a
3227
+ // stack trace. Failing here gives a clear compile-time message instead.
3228
+ // Only direct children of the program count — route handlers and other
3229
+ // nested blocks get their own function scopes.
3230
+ {
3231
+ const seen = new Set();
3232
+ for (const stmt of ast.body) {
3233
+ const name = (stmt.type === 'RememberStatement' || stmt.type === 'RememberSqlStatement') && typeof stmt.name === 'string'
3234
+ ? stmt.name
3235
+ : null;
3236
+ if (name === null) continue;
3237
+ if (seen.has(name)) {
3238
+ throw new Error(
3239
+ `Duplicate declaration: "${name}" is already declared at the top level.\n\n` +
3240
+ `Use "${name} becomes <value>" to reassign it instead of declaring it again.`
3241
+ );
3242
+ }
3243
+ seen.add(name);
3244
+ }
3245
+ }
3246
+
3247
+ // User-declared top-level functions shadow STDLIB names at call sites
3248
+ // (make sort(x) must call the user's sort, not the builtin). Merged across
3249
+ // files so a module that declares a builtin-named function stays callable
3250
+ // from imports. Computed before generation so calls inside the program (and
3251
+ // the exported module surface below) see it.
3252
+ const exported = ast.body
3253
+ .filter(node => node.type === 'FunctionDeclaration' || node.type === 'IntentDeclaration')
3254
+ .map(node => node.name);
3255
+ const declared = new Set(exported);
3256
+ context.declaredFunctions = new Set([...(context.declaredFunctions || []), ...declared]);
3257
+
3040
3258
  const preludeStart = context.pendingPrelude.length;
3041
3259
 
3042
3260
  const bodyParts = [];
@@ -3059,12 +3277,6 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3059
3277
  const body = bodyParts.join('\n');
3060
3278
  const lines = preludeLines.concat(body).filter(Boolean);
3061
3279
 
3062
- // Top-level functions are the module's public API: export them so a built
3063
- // PlainScript file works as a normal CommonJS module (npm packages, require()).
3064
- // Harmless for programs that are only executed.
3065
- const exported = ast.body
3066
- .filter(node => node.type === 'FunctionDeclaration')
3067
- .map(node => node.name);
3068
3280
  const hasExplicitExport = ast.body.some(node => node.type === 'ExportStatement');
3069
3281
  // When the author uses explicit `export <name>`, they control the module
3070
3282
  // surface; skip the automatic function export so it does not clobber it.
@@ -3072,6 +3284,13 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3072
3284
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
3073
3285
  }
3074
3286
 
3287
+ // Deferred export assignments (from ExportStatement) are emitted at the end
3288
+ // of the file's code so they reference fully-initialized bindings.
3289
+ if (context.pendingExports.length > 0) {
3290
+ lines.push(...context.pendingExports);
3291
+ context.pendingExports = [];
3292
+ }
3293
+
3075
3294
  // v1.0.1 - native test runner. When any "test ... done" block exists, emit
3076
3295
  // the runner helper, register each test after its function declaration, and
3077
3296
  // execute them. Each failure prints a message and sets process.exitCode = 1.
@@ -3125,8 +3344,42 @@ let __inTest = false;
3125
3344
 
3126
3345
  function generateCondition(cond, context) {
3127
3346
  switch (cond.type) {
3128
- case 'BinaryCondition':
3347
+ case 'ConditionExpression':
3348
+ // A bare boolean value used as a condition (`if ok`): truthy check.
3349
+ return generateExpr(cond.value, context);
3350
+
3351
+ case 'BinaryCondition': {
3352
+ // v1.0.364 - nullish equality. `x is null` guards against BOTH null and
3353
+ // undefined, because PlainScript builtins deliberately differ: env() of a
3354
+ // missing variable yields null while `first of []` yields undefined. A
3355
+ // guard the programmer wrote correctly must not silently fail (torture
3356
+ // finding: `if x is null` was false for missing array slots). `is null`
3357
+ // is therefore nullish (== null); `is undefined` stays the strict
3358
+ // escape hatch (=== undefined). Literal-vs-literal keeps JS semantics.
3359
+ const NULLISH_OPS = { '===': '==', '!==': '!=' };
3360
+ if (NULLISH_OPS[cond.op]) {
3361
+ const isNullLit = n => n.type === 'NullLiteral';
3362
+ const isUndefLit = n => n.type === 'UndefinedLiteral';
3363
+ const litSide = isNullLit(cond.left) ? 'left' : isNullLit(cond.right) ? 'right'
3364
+ : isUndefLit(cond.left) ? 'left' : isUndefLit(cond.right) ? 'right' : null;
3365
+ if (litSide !== null) {
3366
+ const otherSide = litSide === 'left' ? 'right' : 'left';
3367
+ const litNode = cond[litSide];
3368
+ const otherNode = cond[otherSide];
3369
+ // Only bridge when the other operand is a real value, so
3370
+ // `null is undefined` keeps its JS meaning (false).
3371
+ if (!isNullLit(otherNode) && !isUndefLit(otherNode)) {
3372
+ const otherCode = `(${generateExpr(otherNode, context)})`;
3373
+ if (isNullLit(litNode)) {
3374
+ return `${otherCode} ${NULLISH_OPS[cond.op]} null`;
3375
+ }
3376
+ // strict escape hatch: `is undefined` matches undefined only
3377
+ return `${otherCode} ${cond.op} undefined`;
3378
+ }
3379
+ }
3380
+ }
3129
3381
  return `${generateExpr(cond.left, context)} ${cond.op} ${generateExpr(cond.right, context)}`;
3382
+ }
3130
3383
 
3131
3384
  case 'UnaryCondition':
3132
3385
  if (cond.op === 'isEmpty') {
@@ -3172,21 +3425,25 @@ function generateCondition(cond, context) {
3172
3425
  // number, a `set with ...` literal). Pure conditions recurse through the
3173
3426
  // condition generator; everything else is emitted as a general expression.
3174
3427
  case 'LogicalCondition': {
3175
- const CONDITION_TYPES = [
3176
- 'BinaryCondition',
3177
- 'UnaryCondition',
3178
- 'BetweenCondition',
3179
- 'StringCondition',
3180
- 'InCondition',
3181
- 'NotInCondition',
3182
- 'LogicalCondition',
3183
- ];
3184
- const emit = (n) => CONDITION_TYPES.includes(n.type)
3428
+ const emit = (n) => CONDITION_TYPES.has(n.type)
3185
3429
  ? generateCondition(n, context)
3186
3430
  : generateExpr(n, context);
3187
3431
  if (cond.op === 'not') return `!(${emit(cond.operand)})`;
3188
3432
  const jsOp = cond.op === 'and' ? '&&' : '||';
3189
- return `${emit(cond.left)} ${jsOp} ${emit(cond.right)}`;
3433
+ const leftCode = emit(cond.left);
3434
+ const rightCode = emit(cond.right);
3435
+ // v1.0.364 - when the left operand is a value expression (not a pure
3436
+ // comparison node), evaluate it exactly once. "f() and g()" used to
3437
+ // regenerate f() three times (once for the test, once per truthiness
3438
+ // branch), doubling side effects, network calls, and awaits.
3439
+ if (!CONDITION_TYPES.has(cond.left.type)) {
3440
+ if (/\bawait\b/.test(leftCode) || /\bawait\b/.test(rightCode)) {
3441
+ context.emittedAwait = true;
3442
+ return `(await (async () => { const __lv = ${leftCode}; return __lv ${jsOp} ${rightCode}; })())`;
3443
+ }
3444
+ return `(() => { const __lv = ${leftCode}; return __lv ${jsOp} ${rightCode}; })()`;
3445
+ }
3446
+ return `${leftCode} ${jsOp} ${rightCode}`;
3190
3447
  }
3191
3448
 
3192
3449
  default:
@@ -3206,6 +3463,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3206
3463
  : `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
3207
3464
  return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
3208
3465
  }
3466
+ // v1.0.363 - uninitialized declaration ("let undef") binds undefined.
3467
+ if (node.value === null || node.value === undefined) {
3468
+ return `${indent}let ${node.name} = undefined;`;
3469
+ }
3209
3470
  return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
3210
3471
  }
3211
3472
 
@@ -3309,16 +3570,26 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3309
3570
 
3310
3571
  // Enterprise & Intent-Oriented Exporting
3311
3572
  case 'ExportStatement': {
3573
+ const names = node.names || (node.name ? [node.name] : []);
3312
3574
  if (node.exportAll && node.fromPath) {
3575
+ // In a bundle the re-exported module is inlined lexically; the bundler
3576
+ // merges its export surface into this file's own surface.
3577
+ if (context.bundled) return '';
3313
3578
  return `${indent}Object.assign(module.exports, require(${JSON.stringify(node.fromPath)}));`;
3314
3579
  }
3315
- const names = node.names || (node.name ? [node.name] : []);
3316
3580
  if (node.fromPath) {
3581
+ if (context.bundled) return '';
3317
3582
  const exports = names.map(n => `module.exports.${n} = require(${JSON.stringify(node.fromPath)}).${n};`);
3318
- return exports.map(e => `${indent}${e}`).join('\n');
3583
+ const line = exports.map(e => `${indent}${e}`).join('\n');
3584
+ context.pendingExports.push(line);
3585
+ return '';
3319
3586
  }
3587
+ // Deferred to the end of the file so `share x` before `remember x`
3588
+ // does not crash with a TDZ error at runtime.
3320
3589
  const exports = names.map(n => `module.exports.${n} = ${n};`);
3321
- return exports.map(e => `${indent}${e}`).join('\n');
3590
+ const line = exports.map(e => `${indent}${e}`).join('\n');
3591
+ context.pendingExports.push(line);
3592
+ return '';
3322
3593
  }
3323
3594
 
3324
3595
  // v1.0.1 - generators: `yield <expr>` (or bare `yield`).
@@ -3344,8 +3615,27 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3344
3615
  return `${indent}let [${vars}] = ${tuple};`;
3345
3616
  }
3346
3617
 
3347
- case 'ExpressionStatement':
3618
+ case 'ExpressionStatement': {
3619
+ // add(... to c) / remove(... from c) / write(... to f) keep their compact
3620
+ // statement form only when used as a bare statement. In any value
3621
+ // position they must evaluate to the collection instead of push()'s
3622
+ // length / writeFileSync's undefined (torture-test regression).
3623
+ const expr = node.expression;
3624
+ if (expr && (expr.type === 'AddCall' || expr.type === 'RemoveCall')) {
3625
+ const coll = generateExpr(expr.collection, context);
3626
+ const val = generateExpr(expr.value, context);
3627
+ if (expr.type === 'AddCall') return `${indent}${coll}.push(${val});`;
3628
+ return `${indent}${coll} instanceof Map || ${coll} instanceof Set ? ${coll}.delete(${val}) : ${coll}.splice(${coll}.indexOf(${val}), 1);`;
3629
+ }
3630
+ // Bare `sleep(ms)` statements await the async sleep so plain sequential
3631
+ // programs keep their meaning ("pause here"). In expression positions
3632
+ // (all of [...], wait for sleep(...)) the raw promise is used instead.
3633
+ if (expr && expr.type === 'CallExpression' && expr.name === 'sleep' && expr.args && expr.args.length === 1) {
3634
+ markAsync(context);
3635
+ return `${indent}await new Promise(r => setTimeout(r, ${generateExpr(expr.args[0], context)}));`;
3636
+ }
3348
3637
  return `${indent}${generateExpr(node.expression, context)};`;
3638
+ }
3349
3639
 
3350
3640
  // Enterprise & Intent-Oriented Importing
3351
3641
  case 'ImportStatement': {
@@ -3373,9 +3663,18 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3373
3663
 
3374
3664
  // Local PlainScript module import
3375
3665
  if (node.namespace) {
3666
+ // In a bundle the dependency's top-level bindings are already
3667
+ // initialized (dependencies compile first), so expose them as live
3668
+ // getters instead of a require() that can never resolve from the
3669
+ // generated file's location.
3670
+ const surface = context.importSurfaces && context.importSurfaces.get(node.path);
3671
+ if (context.bundled && surface) {
3672
+ const getters = surface.map(n => `get ${n}() { return ${n}; }`).join(', ');
3673
+ return `${indent}const ${node.namespace} = { ${getters} };`;
3674
+ }
3376
3675
  const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3377
3676
  return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
3378
- }
3677
+ }
3379
3678
  return '';
3380
3679
  }
3381
3680
 
@@ -3401,7 +3700,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3401
3700
  return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
3402
3701
  }
3403
3702
 
3404
- case 'FunctionDeclaration': {
3703
+ case 'TypeDeclaration': {
3704
+ ensureTypeRuntime(context);
3705
+ const schema = JSON.stringify(node.fields || []);
3706
+ return `${indent}__plainTypes[${JSON.stringify(node.name)}] = { fields: ${schema} };`;
3707
+ }
3708
+
3709
+ case 'FunctionDeclaration':
3710
+ case 'IntentDeclaration': {
3405
3711
  const prevInFunction = context.inFunction;
3406
3712
  context.inFunction = true;
3407
3713
  const block = generateBlock(node.body, indent + ' ', context);
@@ -3430,7 +3736,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3430
3736
  }
3431
3737
  return p;
3432
3738
  }).join(', ');
3433
- return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${block.out}\n${indent}}`;
3739
+ const checks = node.params
3740
+ .filter(p => p && p.typeAnnotation && p.name)
3741
+ .map(p => `${indent} __plainAssertType(${JSON.stringify(p.typeAnnotation)}, ${p.name}, ${JSON.stringify(`${node.name}.${p.name}`)});`)
3742
+ .join('\n');
3743
+ if (checks) ensureTypeRuntime(context);
3744
+ const bodyWithChecks = checks ? `${checks}\n${block.out}` : block.out;
3745
+ return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${bodyWithChecks}\n${indent}}`;
3434
3746
  }
3435
3747
 
3436
3748
  case 'IfStatement': {
@@ -3586,7 +3898,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3586
3898
  if (!_inRoute) {
3587
3899
  throw new Error('"reply file" can only be used inside a route handler.\n\nExample:\n route get "/"\n reply file "public/index.html"\n done');
3588
3900
  }
3589
- // Use path.resolve to handle relative paths correctly
3901
+ // Use __path.resolve to handle relative paths correctly
3590
3902
  return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
3591
3903
 
3592
3904
  case 'ReplyJsonStatement': {
@@ -3798,6 +4110,15 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3798
4110
  lines.push(`${indent} }`);
3799
4111
  if (isLast) lines.push(`${indent}}`);
3800
4112
  } else {
4113
+ // Untyped recover (recover as err / recover): normalize primitive
4114
+ // throws (throw "kaboom") so both `message of err` and `text(err)`
4115
+ // see the value; Error objects and thrown objects pass through.
4116
+ lines.push(`${indent} if (!(${errorName} instanceof Error)) {`);
4117
+ lines.push(`${indent} const __plainOrig = ${errorName};`);
4118
+ lines.push(`${indent} if (typeof __plainOrig !== 'object' || __plainOrig === null) {`);
4119
+ lines.push(`${indent} ${errorName} = { message: String(__plainOrig), toString: () => String(__plainOrig) };`);
4120
+ lines.push(`${indent} }`);
4121
+ lines.push(`${indent} }`);
3801
4122
  if (isFirst && isLast) {
3802
4123
  lines.push(catchBody);
3803
4124
  lines.push(`${indent}}`);
@@ -3813,6 +4134,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3813
4134
  const errorName = node.catchName || '__plainError';
3814
4135
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
3815
4136
  lines.push(`${indent}} catch (${errorName}) {`);
4137
+ // Normalize primitive throws (throw "kaboom") so both `message of err`
4138
+ // and `text(err)` see the value; objects/Errors pass through untouched.
4139
+ lines.push(`${indent} if (!(${errorName} instanceof Error)) {`);
4140
+ lines.push(`${indent} const __plainOrig = ${errorName};`);
4141
+ lines.push(`${indent} if (typeof __plainOrig !== 'object' || __plainOrig === null) {`);
4142
+ lines.push(`${indent} ${errorName} = { message: String(__plainOrig), toString: () => String(__plainOrig) };`);
4143
+ lines.push(`${indent} }`);
4144
+ lines.push(`${indent} }`);
3816
4145
  lines.push(recoverBody);
3817
4146
  lines.push(`${indent}}`);
3818
4147
  } else {
@@ -3880,16 +4209,16 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3880
4209
  // v2.2.0 - mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
3881
4210
  // Uses the mongodb driver; subsequent query/insert/update/delete/execute
3882
4211
  // statements compile to MongoDB collection operations.
4212
+ // v1.0.363 - mongodb is an optional backend: the require lives inside
4213
+ // __mongoOpen (it is only evaluated when a database is actually opened),
4214
+ // so programs that never use it start without needing the module.
3883
4215
  case 'MongoStatement': {
3884
4216
  _sqlDriver = 'mongo';
3885
4217
  _sqlClientVar = 'db';
3886
4218
  markAsync(context);
3887
4219
  ensureBuiltin(context, 'mongodb');
3888
4220
  const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
3889
- return [
3890
- emitRequire(context, 'mongodb'),
3891
- `${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
3892
- ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
4221
+ return `${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`;
3893
4222
  }
3894
4223
 
3895
4224
  case 'QueryStatement':
@@ -3905,6 +4234,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3905
4234
  case 'ExecuteStatement':
3906
4235
  return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
3907
4236
 
4237
+
3908
4238
  // v2.1.0 - remember <name> as query|insert|update|delete … done
3909
4239
  case 'RememberSqlStatement': {
3910
4240
  const kind = node.kind === 'query' ? 'query'
@@ -4136,7 +4466,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4136
4466
  ].join('\n');
4137
4467
  }
4138
4468
 
4139
- // v1.0.361 - every frame … done: one requestAnimationFrame loop. The next
4469
+ // v1.0.363 - every frame … done: one requestAnimationFrame loop. The next
4140
4470
  // frame is scheduled after the body so the body always runs once per
4141
4471
  // frame; an awaiting body makes the callback async automatically.
4142
4472
  case 'EveryFrameStatement': {
@@ -4153,7 +4483,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4153
4483
  ].join('\n');
4154
4484
  }
4155
4485
 
4156
- // v1.0.361 - after <n> <unit> … done: one-shot setTimeout. The delay is an
4486
+ // v1.0.363 - after <n> <unit> … done: one-shot setTimeout. The delay is an
4157
4487
  // expression scaled by the unit; an awaiting body makes the callback async.
4158
4488
  case 'AfterStatement': {
4159
4489
  const delay = generateExpr(node.delay, context);
@@ -4290,7 +4620,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4290
4620
  return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
4291
4621
  }
4292
4622
 
4293
- // v1.0.361 - when <target> "<event>" happens [as <name>] … done: DOM event
4623
+ // v1.0.363 - when <target> "<event>" happens [as <name>] … done: DOM event
4294
4624
  // listener. The handler param defaults to "event"; an awaiting body makes
4295
4625
  // the callback async automatically.
4296
4626
  case 'WhenTargetedStatement': {
@@ -4312,10 +4642,22 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4312
4642
  }
4313
4643
 
4314
4644
  case 'RunParallelStatement': {
4645
+ // Each statement in the block becomes one concurrent task; `Promise.all`
4646
+ // resolves with every task's value in body order. An expression statement
4647
+ // (typically a call) contributes its return value; any other statement
4648
+ // runs as its own async job and contributes `undefined`.
4315
4649
  markAsync(context);
4316
- const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
4650
+ const tasks = (node.body || []).map(stmt => {
4651
+ if (stmt.type === 'ExpressionStatement') {
4652
+ const expr = generateExpr(stmt.expression, context);
4653
+ return `(async () => (${expr}))()`;
4654
+ }
4655
+ const body = generateStatement(stmt, indent + ' ', context);
4656
+ return `(async () => {\n${body}\n${indent} })()`;
4657
+ });
4317
4658
  const resultName = node.resultName || '__parallelResults';
4318
- return `${indent}const ${resultName} = await Promise.all([(async () => {\n${body}\n${indent}})()]);`;
4659
+ const joined = tasks.join(',\n' + indent + ' ');
4660
+ return `${indent}const ${resultName} = await Promise.all([\n${indent} ${joined},\n${indent}]);`;
4319
4661
  }
4320
4662
 
4321
4663
  default:
@@ -4347,8 +4689,10 @@ function generateExpr(node, context = createGenerationContext()) {
4347
4689
  case 'NotInCondition':
4348
4690
  case 'StringCondition':
4349
4691
  case 'LogicalCondition':
4692
+ case 'ConditionExpression':
4350
4693
  // Comparisons are first-class expressions (e.g. `(x) -> x is above 3`),
4351
- // so emit the same code the condition level produces.
4694
+ // so emit the same code the condition level produces. ConditionExpression
4695
+ // carries a bare boolean value from `if ok` / `while connected`.
4352
4696
  return generateCondition(node, context);
4353
4697
  case 'DictionaryLiteral': {
4354
4698
  if (!node.pairs || node.pairs.length === 0) return 'new Map()';
@@ -4418,6 +4762,17 @@ function generateExpr(node, context = createGenerationContext()) {
4418
4762
  // Content is preserved verbatim (interpolation, whitespace, line breaks).
4419
4763
  // Only literal backtick characters inside the content need escaping.
4420
4764
  case 'TemplateLiteral': {
4765
+ // v1.0.364 - PlainScript-only expressions inside ${...} ("message of e",
4766
+ // "x is at least 80", "a contains b") are now parsed into real AST parts,
4767
+ // so they compile to valid JavaScript instead of being spliced in raw.
4768
+ // Templates without parsed parts keep the exact legacy emission.
4769
+ if (Array.isArray(node.parts)) {
4770
+ const pieces = node.parts.map(p => {
4771
+ if (p.kind === 'expr') return '${' + generateExpr(p.expr, context) + '}';
4772
+ return p.text.replace(/`/g, '\\`');
4773
+ });
4774
+ return '`' + pieces.join('') + '`';
4775
+ }
4421
4776
  const escaped = node.value.replace(/`/g, '\\`');
4422
4777
  return '`' + escaped + '`';
4423
4778
  }
@@ -4445,12 +4800,25 @@ function generateExpr(node, context = createGenerationContext()) {
4445
4800
  }
4446
4801
 
4447
4802
  // Nested binary operands get parentheses so (2 + 3) * 4 keeps its
4448
- // grouping instead of flattening to 2 + 3 * 4.
4803
+ // grouping instead of flattening to 2 + 3 * 4. Comparison and logical
4804
+ // operands also need them: "x" + (a is b) must not become "x" + a === b.
4449
4805
  case 'BinaryExpression': {
4450
- const left = node.left.type === 'BinaryExpression'
4806
+ const needsParens = (t) =>
4807
+ t.type === 'BinaryExpression' ||
4808
+ t.type === 'BinaryCondition' ||
4809
+ t.type === 'UnaryCondition' ||
4810
+ t.type === 'BetweenCondition' ||
4811
+ t.type === 'InCondition' ||
4812
+ t.type === 'NotInCondition' ||
4813
+ t.type === 'StringCondition' ||
4814
+ t.type === 'LogicalCondition' ||
4815
+ t.type === 'ComparisonCondition' ||
4816
+ t.type === 'ConditionalExpression' ||
4817
+ t.type === 'ArrowFunctionExpression';
4818
+ const left = needsParens(node.left)
4451
4819
  ? `(${generateExpr(node.left, context)})`
4452
4820
  : generateExpr(node.left, context);
4453
- const right = node.right.type === 'BinaryExpression'
4821
+ const right = needsParens(node.right)
4454
4822
  ? `(${generateExpr(node.right, context)})`
4455
4823
  : generateExpr(node.right, context);
4456
4824
  return `${left} ${node.operator} ${right}`;
@@ -4520,7 +4888,7 @@ function generateExpr(node, context = createGenerationContext()) {
4520
4888
 
4521
4889
  case 'CallExpression': {
4522
4890
  // Method call: receiver.method(args). Member access invoked with parens -
4523
- // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
4891
+ // e.g. __path.join("a", "b"), mrz.parse(line), __fs.existsSync(("x")).
4524
4892
  // Postfix calls f()(), arr[0](1), mul(6)(7) also bind here; any composite
4525
4893
  // callee (arrow, binary, comparison/logical condition) is parenthesised so
4526
4894
  // the call still applies to the whole value, not its last operand.
@@ -4534,9 +4902,10 @@ function generateExpr(node, context = createGenerationContext()) {
4534
4902
  node.callee.type === 'UnaryExpression';
4535
4903
  return `${composite ? `(${callee})` : callee}(${args})`;
4536
4904
  }
4537
- if (STDLIB[node.name]) {
4905
+ if (STDLIB[node.name] && !(context.declaredFunctions && context.declaredFunctions.has(node.name))) {
4538
4906
  if (node.name === 'readFile' || node.name === 'writeFile' ||
4539
- node.name === 'fileExists' || node.name === 'read') {
4907
+ node.name === 'fileExists' || node.name === 'read' ||
4908
+ node.name === 'write') {
4540
4909
  ensureBuiltin(context, 'fs');
4541
4910
  } else if (node.name === 'uuid') {
4542
4911
  ensureBuiltin(context, 'crypto');
@@ -4561,7 +4930,8 @@ function generateExpr(node, context = createGenerationContext()) {
4561
4930
 
4562
4931
  case 'CountOfExpression': {
4563
4932
  const obj = generateExpr(node.object, context);
4564
- return `((${obj} && ${obj}.count !== undefined) ? ${obj}.count : ((${obj} && ${obj}.length !== undefined) ? ${obj}.length : ((${obj} && ${obj}.size !== undefined) ? ${obj}.size : 0)))`;
4933
+ const probe = (x) => `((${obj} && (${obj}).${x} !== undefined) ? (${obj}).${x} : `;
4934
+ return `${probe('count')}${probe('length')}${probe('size')}0)))`;
4565
4935
  }
4566
4936
 
4567
4937
  // v1.1 - Property access
@@ -4586,17 +4956,23 @@ function generateExpr(node, context = createGenerationContext()) {
4586
4956
 
4587
4957
  // v1.1 - Collection operations
4588
4958
  case 'AddCall':
4589
- return `${generateExpr(node.collection, context)}.push(${generateExpr(node.value, context)})`;
4959
+ // Expression form evaluates to the (mutated) collection, not push()'s
4960
+ // new length, so `xs becomes add(x to xs)` keeps xs an array.
4961
+ return `((__psAdd) => (__psAdd.push(${generateExpr(node.value, context)}), __psAdd))(${generateExpr(node.collection, context)})`;
4590
4962
 
4591
4963
  case 'RemoveCall': {
4964
+ // Expression form evaluates to the (mutated) collection.
4592
4965
  const coll = generateExpr(node.collection, context);
4593
4966
  const val = generateExpr(node.value, context);
4594
- return `${coll} instanceof Map || ${coll} instanceof Set ? ${coll}.delete(${val}) : ${coll}.splice(${coll}.indexOf(${val}), 1)`;
4967
+ return `((__psRem) => (${coll} instanceof Map || ${coll} instanceof Set ? __psRem.delete(${val}) : __psRem.splice(__psRem.indexOf(${val}), 1), __psRem))(${coll})`;
4595
4968
  }
4596
4969
 
4597
4970
  case 'WriteCall':
4598
4971
  ensureBuiltin(context, 'fs');
4599
- return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
4972
+ // fs.writeFileSync(path, data): the natural form is write(data to "file"),
4973
+ // so the FILE is the second PlainScript argument but the FIRST fs one.
4974
+ // Both used to be swapped, creating a file named after the data string.
4975
+ return `__fs.writeFileSync(${generateExpr(node.file, context)}, ${generateExpr(node.data, context)}, 'utf8')`;
4600
4976
 
4601
4977
  // v1.0.1 - record constructor: `create a Person with name "Ada" and age 17`
4602
4978
  // calls the kind factory that `define a kind called "Person"` registered.