plainscript-lang 1.0.362 → 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 +382 -54
  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 +453 -107
  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 +13 -4
@@ -6,7 +6,7 @@ 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
- // v1.0.362 - better-sqlite3 is an OPTIONAL runtime backend. The require
9
+ // v1.0.363 - better-sqlite3 is an OPTIONAL runtime backend. The require
10
10
  // must not run at module load: on platforms without a usable native
11
11
  // binary (e.g. Android/Termux) `plainscript` must still compile and run
12
12
  // programs that never touch SQLite. `Database` is resolved lazily and only
@@ -15,8 +15,6 @@ const KNOWN_PACKAGES = {
15
15
  sqlite: `let Database;
16
16
  try { Database = require('better-sqlite3'); }
17
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"'); }; }`,
18
- fs: `const fs = require('fs');`,
19
- path: `const path = require('path');`,
20
18
  axios: `const axios = require('axios');`,
21
19
  chalk: `const chalk = require('chalk');`,
22
20
  // v2.1.0 - PostgreSQL driver behind the friendly "postgres" name.
@@ -25,6 +23,13 @@ catch (__e) { Database = function () { throw new Error('PlainScript: the native
25
23
  mongodb: `const { MongoClient } = require('mongodb');`,
26
24
  };
27
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
+
28
33
  // PlainScript module names whose npm package name differs from the PlainScript name.
29
34
  // Used to de-duplicate runtime requires across aliases (RFC-0011 §22).
30
35
  const NPM_NAME = {
@@ -47,16 +52,16 @@ const JS_RESERVED = new Set([
47
52
  ]);
48
53
 
49
54
  const BUILTIN_DECLARATIONS = {
50
- fs: `const fs = require('fs');`,
51
- path: `const path = require('path');`,
52
- crypto: `const crypto = require('crypto');`,
55
+ fs: `const __fs = require('fs');`,
56
+ path: `const __path = require('path');`,
57
+ crypto: `const __crypto = require('crypto');`,
53
58
  // v1.0.1 - env-file runtime. Applies KEY=VALUE pairs from a .env file to
54
59
  // process.env. Blank lines and `#` comment lines are skipped.
55
60
  dotenv: [
56
61
  `function __loadEnvFile(path) {`,
57
- ` const fs = require('fs');`,
62
+ ` const __fs = require('fs');`,
58
63
  ` let raw;`,
59
- ` try { raw = fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
64
+ ` try { raw = __fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
60
65
  ` for (const line of raw.split(/\\r?\\n/)) {`,
61
66
  ` const trimmed = line.trim();`,
62
67
  ` if (!trimmed || trimmed.startsWith('#')) continue;`,
@@ -69,7 +74,8 @@ const BUILTIN_DECLARATIONS = {
69
74
  ` }`,
70
75
  `}`,
71
76
  ].join('\n'),
72
- // 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.
73
79
  ask: [
74
80
  `const readline = require('readline');`,
75
81
  `async function __ask(prompt = '') {`,
@@ -80,6 +86,26 @@ const BUILTIN_DECLARATIONS = {
80
86
  ` rl.close();`,
81
87
  ` }`,
82
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
+ `}`,
83
109
  ].join('\n'),
84
110
  // v2.0.1 - OCR runtime (tesseract.js). Extracts text from an image file.
85
111
  // The worker is created per call and always terminated, so repeated ocr
@@ -96,7 +122,7 @@ const BUILTIN_DECLARATIONS = {
96
122
  ` }`,
97
123
  `}`,
98
124
  ].join('\n'),
99
- // v1.0.362 - DOM browser runtime (select/selectAll/parseHTML). Browser
125
+ // v1.0.363 - DOM browser runtime (select/selectAll/parseHTML). Browser
100
126
  // globals are guarded so the generated JS explains the problem when it is
101
127
  // run under Node instead of failing with a ReferenceError midpoint.
102
128
  dom: [
@@ -115,7 +141,7 @@ const BUILTIN_DECLARATIONS = {
115
141
  ` return template.content;`,
116
142
  `}`,
117
143
  ].join('\n'),
118
- // v1.0.362 - input runtime: pointer coordinates, gamepads, dropped files.
144
+ // v1.0.363 - input runtime: pointer coordinates, gamepads, dropped files.
119
145
  input: [
120
146
  `function __localPoint(e, canvas) {`,
121
147
  ` if (typeof document === 'undefined') throw new Error('localPoint(...) needs a browser (document is not defined in Node).');`,
@@ -133,7 +159,7 @@ const BUILTIN_DECLARATIONS = {
133
159
  ` return [...(event && event.dataTransfer ? event.dataTransfer.files : [])];`,
134
160
  `}`,
135
161
  ].join('\n'),
136
- // v1.0.362 - asset-loading runtime (images, JSON, bytes, data URLs). All
162
+ // v1.0.363 - asset-loading runtime (images, JSON, bytes, data URLs). All
137
163
  // helpers return promises; the STDLIB entries await them.
138
164
  assets: [
139
165
  `function __loadImage(url) {`,
@@ -170,7 +196,7 @@ const BUILTIN_DECLARATIONS = {
170
196
  ` });`,
171
197
  `}`,
172
198
  ].join('\n'),
173
- // v1.0.362 - Web Audio runtime. The AudioContext is created once and shared
199
+ // v1.0.363 - Web Audio runtime. The AudioContext is created once and shared
174
200
  // (browsers cap the number), and resumed on demand because autoplay policies
175
201
  // start it suspended.
176
202
  audio: [
@@ -213,7 +239,7 @@ const BUILTIN_DECLARATIONS = {
213
239
  ` });`,
214
240
  `}`,
215
241
  ].join('\n'),
216
- // v1.0.362 - WebGL runtime: context selection plus the three compile/link/
242
+ // v1.0.363 - WebGL runtime: context selection plus the three compile/link/
217
243
  // buffer helpers behind the gl* stdlib entries.
218
244
  gl: [
219
245
  `function __glContext(canvas) {`,
@@ -387,7 +413,7 @@ const BUILTIN_DECLARATIONS = {
387
413
  ` });`,
388
414
  `}`,
389
415
  ].join('\n'),
390
- // v1.0.35 - dependency-free SVG images and visualizations.
416
+ // v1.0.363 - dependency-free SVG images and visualizations.
391
417
  // The image value is an SVG string, so it can be saved, embedded, or returned
392
418
  // from a web route without a native graphics dependency.
393
419
  visualization: [
@@ -540,8 +566,8 @@ const BUILTIN_DECLARATIONS = {
540
566
  // v1.0.1 - dynamic module loader.
541
567
  loadmodule: [
542
568
  `function __loadModule(spec) {`,
543
- ` const path = require('path');`,
544
- ` 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;`,
545
571
  ` try { return require(target); }`,
546
572
  ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
547
573
  `}`,
@@ -549,13 +575,13 @@ const BUILTIN_DECLARATIONS = {
549
575
  // v1.0.1 - recursive directory walker (returns full paths, files first).
550
576
  walk: [
551
577
  `function __walkFolder(dir) {`,
552
- ` const fs = require('fs');`,
553
- ` const path = require('path');`,
578
+ ` const __fs = require('fs');`,
579
+ ` const __path = require('path');`,
554
580
  ` const out = [];`,
555
581
  ` function rec(d) {`,
556
- ` for (const entry of fs.readdirSync(d)) {`,
557
- ` const full = path.join(d, entry);`,
558
- ` 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);`,
559
585
  ` if (st.isDirectory()) rec(full);`,
560
586
  ` else out.push(full);`,
561
587
  ` }`,
@@ -737,10 +763,10 @@ const BUILTIN_DECLARATIONS = {
737
763
  ` const raw = message && message.raw ? message.raw : message;`,
738
764
  ` const buffer = await downloadMediaMessage(raw, 'buffer', {}, { logger: __waSilentLogger, reuploadRequest: sock.updateMediaMessage });`,
739
765
  ` if (!dest) return buffer;`,
740
- ` const fs = require('fs'), path = require('path');`,
741
- ` const dir = path.dirname(path.resolve(dest));`,
742
- ` if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });`,
743
- ` 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);`,
744
770
  ` return dest;`,
745
771
  ` }`,
746
772
  ` async function __whatsappDownload(message, dest) {`,
@@ -1090,7 +1116,7 @@ const BUILTIN_DECLARATIONS = {
1090
1116
  ].join('\n'),
1091
1117
  // v2.1.1 - file upload runtime (multer behind "accept uploads"). Files are
1092
1118
  // held in memory by default or written to disk when a folder is given.
1093
- // Normalised records expose: name, type, size, data (buffer) and path.
1119
+ // Normalised records expose: name, type, size, data (buffer) and __path.
1094
1120
  uploads: [
1095
1121
  `function __uploads(options = {}) {`,
1096
1122
  ` const multer = require('multer');`,
@@ -1330,8 +1356,8 @@ const BUILTIN_DECLARATIONS = {
1330
1356
  // IOPL-native - line-by-line file streaming runtime.
1331
1357
  __streamFile: [
1332
1358
  `async function __streamFile(path, fn) {`,
1333
- ` const fs = require('fs');`,
1334
- ` 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 });`,
1335
1361
  ` for await (const line of rl) await fn(line);`,
1336
1362
  `}`,
1337
1363
  ].join('\n'),
@@ -1392,7 +1418,7 @@ const BUILTIN_DECLARATIONS = {
1392
1418
  ` };`,
1393
1419
  `}`,
1394
1420
  `function __sqliteWrapWasm(db, file) {`,
1395
- ` // v1.0.362 - sql.js's export() ends an open transaction, so persisting`,
1421
+ ` // v1.0.363 - sql.js's export() ends an open transaction, so persisting`,
1396
1422
  ` // mid-transaction would break the explicit COMMIT that follows. While a`,
1397
1423
  ` // transaction is active, writes are only flushed to disk once, after the`,
1398
1424
  ` // COMMIT succeeds (the wrapper's own persist at that point covers it).`,
@@ -1689,8 +1715,8 @@ const BUILTIN_DECLARATIONS = {
1689
1715
  sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1690
1716
  // v0.6 - runtime standard library
1691
1717
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1692
- readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1693
- 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')`,
1694
1720
  // v2.4.0 - dependency-free SVG image and visualization helpers.
1695
1721
  svgImage: (args, context) => {
1696
1722
  ensureBuiltin(context, 'visualization');
@@ -1712,9 +1738,23 @@ const BUILTIN_DECLARATIONS = {
1712
1738
  ensureBuiltin(context, 'visualization');
1713
1739
  return `__imageDataUri(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1714
1740
  },
1715
- fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
1716
- read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1717
- 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
+ },
1718
1758
  time: (_args) => `Date.now()`,
1719
1759
  date: (_args) => `new Date().toISOString()`,
1720
1760
  jsonEncode: (args, context) => `JSON.stringify(${generateExpr(args[0], context)})`,
@@ -1789,20 +1829,20 @@ const BUILTIN_DECLARATIONS = {
1789
1829
 
1790
1830
  // ── v2.1.0 - filesystem helpers (sync, matching readFile/writeFile style)
1791
1831
 
1792
- copyFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.copyFileSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1793
- moveFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.renameSync(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1794
- deleteFile: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.unlinkSync(${generateExpr(args[0], context)})`; },
1795
- makeFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.mkdirSync(${generateExpr(args[0], context)}, { recursive: true })`; },
1796
- deleteFolder: (args, context) => { ensureBuiltin(context, 'fs'); return `fs.rmSync(${generateExpr(args[0], context)}, { recursive: true, force: true })`; },
1797
- 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)})`; },
1798
1838
  appendFile: (args, context) => {
1799
1839
  ensureBuiltin(context, 'fs');
1800
- 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')`;
1801
1841
  },
1802
- 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)})`; },
1803
1843
  writeBytes: (args, context) => {
1804
1844
  ensureBuiltin(context, 'fs');
1805
- return `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1845
+ return `__fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1806
1846
  },
1807
1847
 
1808
1848
  // ── v2.1.0 - text, number and collection helpers
@@ -2153,15 +2193,15 @@ const BUILTIN_DECLARATIONS = {
2153
2193
  bytesToText: (args, context) => `Buffer.from(${generateExpr(args[0], context)}).toString('utf8')`,
2154
2194
  sha256: (args, context) => {
2155
2195
  ensureBuiltin(context, 'crypto');
2156
- 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')`;
2157
2197
  },
2158
2198
  sha1: (args, context) => {
2159
2199
  ensureBuiltin(context, 'crypto');
2160
- 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')`;
2161
2201
  },
2162
2202
  md5: (args, context) => {
2163
2203
  ensureBuiltin(context, 'crypto');
2164
- 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')`;
2165
2205
  },
2166
2206
 
2167
2207
  // Serialization - minimal dependency-free YAML subset (see __yamlParse).
@@ -2191,6 +2231,46 @@ const BUILTIN_DECLARATIONS = {
2191
2231
  return `(await __withTimeout(${generateExpr(args[0], context)}${ms}))`;
2192
2232
  },
2193
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
+
2194
2274
  // Generators / iterables
2195
2275
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
2196
2276
 
@@ -2262,15 +2342,15 @@ const BUILTIN_DECLARATIONS = {
2262
2342
  // Filesystem metadata, walking, and path helpers
2263
2343
  fileSize: (args, context) => {
2264
2344
  ensureBuiltin(context, 'fs');
2265
- return `fs.statSync(${generateExpr(args[0], context)}).size`;
2345
+ return `__fs.statSync(${generateExpr(args[0], context)}).size`;
2266
2346
  },
2267
2347
  fileType: (args, context) => {
2268
2348
  ensureBuiltin(context, 'fs');
2269
- return `fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
2349
+ return `__fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
2270
2350
  },
2271
2351
  lastModified: (args, context) => {
2272
2352
  ensureBuiltin(context, 'fs');
2273
- return `new Date(fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
2353
+ return `new Date(__fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
2274
2354
  },
2275
2355
  walkFolder: (args, context) => {
2276
2356
  ensureBuiltin(context, 'walk');
@@ -2278,29 +2358,29 @@ const BUILTIN_DECLARATIONS = {
2278
2358
  },
2279
2359
  joinPath: (_args, context) => {
2280
2360
  ensureBuiltin(context, 'path');
2281
- return `path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
2361
+ return `__path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
2282
2362
  },
2283
2363
  baseName: (_args, context) => {
2284
2364
  ensureBuiltin(context, 'path');
2285
- return `path.basename(${generateExpr(_args[0], context)})`;
2365
+ return `__path.basename(${generateExpr(_args[0], context)})`;
2286
2366
  },
2287
2367
  folderOf: (_args, context) => {
2288
2368
  ensureBuiltin(context, 'path');
2289
- return `path.dirname(${generateExpr(_args[0], context)})`;
2369
+ return `__path.dirname(${generateExpr(_args[0], context)})`;
2290
2370
  },
2291
2371
  extensionOf: (_args, context) => {
2292
2372
  ensureBuiltin(context, 'path');
2293
- return `path.extname(${generateExpr(_args[0], context)})`;
2373
+ return `__path.extname(${generateExpr(_args[0], context)})`;
2294
2374
  },
2295
2375
 
2296
2376
  // Streams
2297
2377
  writeLine: (args, context) => {
2298
2378
  ensureBuiltin(context, 'fs');
2299
- 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')`;
2300
2380
  },
2301
2381
  appendLine: (args, context) => {
2302
2382
  ensureBuiltin(context, 'fs');
2303
- 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')`;
2304
2384
  },
2305
2385
 
2306
2386
  // ── v1.0.2 - Extended Math functions (IOPL-native).
@@ -2687,7 +2767,7 @@ const BUILTIN_DECLARATIONS = {
2687
2767
  file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2688
2768
  formData: (_args) => `new FormData()`,
2689
2769
 
2690
- // ── v1.0.362 - browser DOM (IOPL-native). All helpers guard their browser
2770
+ // ── v1.0.363 - browser DOM (IOPL-native). All helpers guard their browser
2691
2771
  // global, so the generated output throws a clear teaching error under Node.
2692
2772
  select: (args, context) => {
2693
2773
  ensureBuiltin(context, 'dom');
@@ -2705,7 +2785,7 @@ const BUILTIN_DECLARATIONS = {
2705
2785
  return `__parseHTML(${generateExpr(args[0], context)})`;
2706
2786
  },
2707
2787
 
2708
- // ── v1.0.362 - browser input (IOPL-native).
2788
+ // ── v1.0.363 - browser input (IOPL-native).
2709
2789
  localPoint: (args, context) => {
2710
2790
  ensureBuiltin(context, 'input');
2711
2791
  requireArgs('localPoint', args, 2, 'localPoint(event, canvas)');
@@ -2721,7 +2801,7 @@ const BUILTIN_DECLARATIONS = {
2721
2801
  return `__droppedFiles(${generateExpr(args[0], context)})`;
2722
2802
  },
2723
2803
 
2724
- // ── v1.0.362 - browser assets (IOPL-native). Each awaitable helper is
2804
+ // ── v1.0.363 - browser assets (IOPL-native). Each awaitable helper is
2725
2805
  // awaited here, so the surrounding function/handler is marked async.
2726
2806
  loadImage: (args, context) => {
2727
2807
  ensureBuiltin(context, 'assets');
@@ -2754,7 +2834,7 @@ const BUILTIN_DECLARATIONS = {
2754
2834
  return `(await __readDataUrl(${generateExpr(args[0], context)}))`;
2755
2835
  },
2756
2836
 
2757
- // ── v1.0.362 - Web Audio (IOPL-native).
2837
+ // ── v1.0.363 - Web Audio (IOPL-native).
2758
2838
  audioContext: (_args, context) => {
2759
2839
  ensureBuiltin(context, 'audio');
2760
2840
  return `__audioContext()`;
@@ -2765,7 +2845,7 @@ const BUILTIN_DECLARATIONS = {
2765
2845
  return `__audioTone(${args.map(a => generateExpr(a, context)).join(', ')})`;
2766
2846
  },
2767
2847
 
2768
- // ── v1.0.362 - WebSocket send helper (works with any WebSocket-like object,
2848
+ // ── v1.0.363 - WebSocket send helper (works with any WebSocket-like object,
2769
2849
  // browser or Node): strings go through verbatim, everything else is JSON.
2770
2850
  webSocketSend: (args, context) => {
2771
2851
  requireArgs('webSocketSend', args, 2, 'webSocketSend(socket, { type: "move", x: 10 })');
@@ -2774,7 +2854,7 @@ const BUILTIN_DECLARATIONS = {
2774
2854
  return `${ws}.send(typeof (${value}) === 'string' ? (${value}) : JSON.stringify(${value}))`;
2775
2855
  },
2776
2856
 
2777
- // ── v1.0.362 - WebGL (IOPL-native).
2857
+ // ── v1.0.363 - WebGL (IOPL-native).
2778
2858
  webglContext: (args, context) => {
2779
2859
  ensureBuiltin(context, 'gl');
2780
2860
  requireOneArg('webglContext', args);
@@ -2834,6 +2914,42 @@ function generateBlock(statements, indent, context) {
2834
2914
  return { out, emitted };
2835
2915
  }
2836
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
+
2837
2953
  // v2.1.0 - generate a request accessor (param/query/header). These compile to
2838
2954
  // direct Express req.<bucket>[key] reads and are rejected outside routes so
2839
2955
  // mistakes surface at compile time with a teaching error.
@@ -2923,11 +3039,31 @@ function emitSqlCall(kind, sql, params, indent, context) {
2923
3039
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
2924
3040
  case 'update': return `db.prepare(\`${sql}\`).run(${args})`;
2925
3041
  case 'delete': return `db.prepare(\`${sql}\`).run(${args})`;
2926
- 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})`;
2927
3049
  default: throw new Error(`Unknown SQL kind "${kind}".`);
2928
3050
  }
2929
3051
  }
2930
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
+
2931
3067
  function createGenerationContext(options = {}) {
2932
3068
  const sourceMap = options.sourceMap || false;
2933
3069
  const sourceFile = options.sourceFile || 'source.pln';
@@ -2949,6 +3085,10 @@ function createGenerationContext(options = {}) {
2949
3085
  sourceContent,
2950
3086
  sourceMapBuilder: builder,
2951
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,
2952
3092
  };
2953
3093
  }
2954
3094
 
@@ -2999,6 +3139,20 @@ function emitRequire(context, moduleName, alias) {
2999
3139
  return `const ${alias} = require('${npmName}');`;
3000
3140
  }
3001
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
+
3002
3156
  if (context.requires.has(npmName)) return '';
3003
3157
  context.requires.add(npmName);
3004
3158
 
@@ -3030,7 +3184,7 @@ function containsYield(statements) {
3030
3184
  if (stmt.type === 'IfStatement') {
3031
3185
  if (containsYield(stmt.consequent)) return true;
3032
3186
  if (stmt.alternate && containsYield(stmt.alternate)) return true;
3033
- } 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)) {
3034
3188
  if (containsYield(stmt.body)) return true;
3035
3189
  }
3036
3190
  }
@@ -3067,6 +3221,40 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3067
3221
  __testCatchers = [];
3068
3222
  __inTest = false;
3069
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
+
3070
3258
  const preludeStart = context.pendingPrelude.length;
3071
3259
 
3072
3260
  const bodyParts = [];
@@ -3089,12 +3277,6 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3089
3277
  const body = bodyParts.join('\n');
3090
3278
  const lines = preludeLines.concat(body).filter(Boolean);
3091
3279
 
3092
- // Top-level functions are the module's public API: export them so a built
3093
- // PlainScript file works as a normal CommonJS module (npm packages, require()).
3094
- // Harmless for programs that are only executed.
3095
- const exported = ast.body
3096
- .filter(node => node.type === 'FunctionDeclaration')
3097
- .map(node => node.name);
3098
3280
  const hasExplicitExport = ast.body.some(node => node.type === 'ExportStatement');
3099
3281
  // When the author uses explicit `export <name>`, they control the module
3100
3282
  // surface; skip the automatic function export so it does not clobber it.
@@ -3102,6 +3284,13 @@ function generate(ast, contextOrOptions = createGenerationContext(), options = {
3102
3284
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
3103
3285
  }
3104
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
+
3105
3294
  // v1.0.1 - native test runner. When any "test ... done" block exists, emit
3106
3295
  // the runner helper, register each test after its function declaration, and
3107
3296
  // execute them. Each failure prints a message and sets process.exitCode = 1.
@@ -3155,8 +3344,42 @@ let __inTest = false;
3155
3344
 
3156
3345
  function generateCondition(cond, context) {
3157
3346
  switch (cond.type) {
3158
- 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
+ }
3159
3381
  return `${generateExpr(cond.left, context)} ${cond.op} ${generateExpr(cond.right, context)}`;
3382
+ }
3160
3383
 
3161
3384
  case 'UnaryCondition':
3162
3385
  if (cond.op === 'isEmpty') {
@@ -3202,21 +3425,25 @@ function generateCondition(cond, context) {
3202
3425
  // number, a `set with ...` literal). Pure conditions recurse through the
3203
3426
  // condition generator; everything else is emitted as a general expression.
3204
3427
  case 'LogicalCondition': {
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)
3428
+ const emit = (n) => CONDITION_TYPES.has(n.type)
3215
3429
  ? generateCondition(n, context)
3216
3430
  : generateExpr(n, context);
3217
3431
  if (cond.op === 'not') return `!(${emit(cond.operand)})`;
3218
3432
  const jsOp = cond.op === 'and' ? '&&' : '||';
3219
- 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}`;
3220
3447
  }
3221
3448
 
3222
3449
  default:
@@ -3236,6 +3463,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3236
3463
  : `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
3237
3464
  return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
3238
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
+ }
3239
3470
  return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
3240
3471
  }
3241
3472
 
@@ -3339,16 +3570,26 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3339
3570
 
3340
3571
  // Enterprise & Intent-Oriented Exporting
3341
3572
  case 'ExportStatement': {
3573
+ const names = node.names || (node.name ? [node.name] : []);
3342
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 '';
3343
3578
  return `${indent}Object.assign(module.exports, require(${JSON.stringify(node.fromPath)}));`;
3344
3579
  }
3345
- const names = node.names || (node.name ? [node.name] : []);
3346
3580
  if (node.fromPath) {
3581
+ if (context.bundled) return '';
3347
3582
  const exports = names.map(n => `module.exports.${n} = require(${JSON.stringify(node.fromPath)}).${n};`);
3348
- 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 '';
3349
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.
3350
3589
  const exports = names.map(n => `module.exports.${n} = ${n};`);
3351
- 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 '';
3352
3593
  }
3353
3594
 
3354
3595
  // v1.0.1 - generators: `yield <expr>` (or bare `yield`).
@@ -3374,8 +3615,27 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3374
3615
  return `${indent}let [${vars}] = ${tuple};`;
3375
3616
  }
3376
3617
 
3377
- 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
+ }
3378
3637
  return `${indent}${generateExpr(node.expression, context)};`;
3638
+ }
3379
3639
 
3380
3640
  // Enterprise & Intent-Oriented Importing
3381
3641
  case 'ImportStatement': {
@@ -3403,9 +3663,18 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3403
3663
 
3404
3664
  // Local PlainScript module import
3405
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
+ }
3406
3675
  const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
3407
3676
  return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
3408
- }
3677
+ }
3409
3678
  return '';
3410
3679
  }
3411
3680
 
@@ -3431,7 +3700,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3431
3700
  return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
3432
3701
  }
3433
3702
 
3434
- 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': {
3435
3711
  const prevInFunction = context.inFunction;
3436
3712
  context.inFunction = true;
3437
3713
  const block = generateBlock(node.body, indent + ' ', context);
@@ -3460,7 +3736,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3460
3736
  }
3461
3737
  return p;
3462
3738
  }).join(', ');
3463
- 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}}`;
3464
3746
  }
3465
3747
 
3466
3748
  case 'IfStatement': {
@@ -3616,7 +3898,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3616
3898
  if (!_inRoute) {
3617
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');
3618
3900
  }
3619
- // Use path.resolve to handle relative paths correctly
3901
+ // Use __path.resolve to handle relative paths correctly
3620
3902
  return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
3621
3903
 
3622
3904
  case 'ReplyJsonStatement': {
@@ -3828,6 +4110,15 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3828
4110
  lines.push(`${indent} }`);
3829
4111
  if (isLast) lines.push(`${indent}}`);
3830
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} }`);
3831
4122
  if (isFirst && isLast) {
3832
4123
  lines.push(catchBody);
3833
4124
  lines.push(`${indent}}`);
@@ -3843,6 +4134,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3843
4134
  const errorName = node.catchName || '__plainError';
3844
4135
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
3845
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} }`);
3846
4145
  lines.push(recoverBody);
3847
4146
  lines.push(`${indent}}`);
3848
4147
  } else {
@@ -3910,7 +4209,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3910
4209
  // v2.2.0 - mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
3911
4210
  // Uses the mongodb driver; subsequent query/insert/update/delete/execute
3912
4211
  // statements compile to MongoDB collection operations.
3913
- // v1.0.362 - mongodb is an optional backend: the require lives inside
4212
+ // v1.0.363 - mongodb is an optional backend: the require lives inside
3914
4213
  // __mongoOpen (it is only evaluated when a database is actually opened),
3915
4214
  // so programs that never use it start without needing the module.
3916
4215
  case 'MongoStatement': {
@@ -3935,6 +4234,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3935
4234
  case 'ExecuteStatement':
3936
4235
  return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
3937
4236
 
4237
+
3938
4238
  // v2.1.0 - remember <name> as query|insert|update|delete … done
3939
4239
  case 'RememberSqlStatement': {
3940
4240
  const kind = node.kind === 'query' ? 'query'
@@ -4166,7 +4466,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4166
4466
  ].join('\n');
4167
4467
  }
4168
4468
 
4169
- // v1.0.362 - every frame … done: one requestAnimationFrame loop. The next
4469
+ // v1.0.363 - every frame … done: one requestAnimationFrame loop. The next
4170
4470
  // frame is scheduled after the body so the body always runs once per
4171
4471
  // frame; an awaiting body makes the callback async automatically.
4172
4472
  case 'EveryFrameStatement': {
@@ -4183,7 +4483,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4183
4483
  ].join('\n');
4184
4484
  }
4185
4485
 
4186
- // v1.0.362 - 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
4187
4487
  // expression scaled by the unit; an awaiting body makes the callback async.
4188
4488
  case 'AfterStatement': {
4189
4489
  const delay = generateExpr(node.delay, context);
@@ -4320,7 +4620,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4320
4620
  return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
4321
4621
  }
4322
4622
 
4323
- // v1.0.362 - when <target> "<event>" happens [as <name>] … done: DOM event
4623
+ // v1.0.363 - when <target> "<event>" happens [as <name>] … done: DOM event
4324
4624
  // listener. The handler param defaults to "event"; an awaiting body makes
4325
4625
  // the callback async automatically.
4326
4626
  case 'WhenTargetedStatement': {
@@ -4342,10 +4642,22 @@ function generateStatement(node, indent = '', context = createGenerationContext(
4342
4642
  }
4343
4643
 
4344
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`.
4345
4649
  markAsync(context);
4346
- 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
+ });
4347
4658
  const resultName = node.resultName || '__parallelResults';
4348
- 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}]);`;
4349
4661
  }
4350
4662
 
4351
4663
  default:
@@ -4377,8 +4689,10 @@ function generateExpr(node, context = createGenerationContext()) {
4377
4689
  case 'NotInCondition':
4378
4690
  case 'StringCondition':
4379
4691
  case 'LogicalCondition':
4692
+ case 'ConditionExpression':
4380
4693
  // Comparisons are first-class expressions (e.g. `(x) -> x is above 3`),
4381
- // 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`.
4382
4696
  return generateCondition(node, context);
4383
4697
  case 'DictionaryLiteral': {
4384
4698
  if (!node.pairs || node.pairs.length === 0) return 'new Map()';
@@ -4448,6 +4762,17 @@ function generateExpr(node, context = createGenerationContext()) {
4448
4762
  // Content is preserved verbatim (interpolation, whitespace, line breaks).
4449
4763
  // Only literal backtick characters inside the content need escaping.
4450
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
+ }
4451
4776
  const escaped = node.value.replace(/`/g, '\\`');
4452
4777
  return '`' + escaped + '`';
4453
4778
  }
@@ -4475,12 +4800,25 @@ function generateExpr(node, context = createGenerationContext()) {
4475
4800
  }
4476
4801
 
4477
4802
  // Nested binary operands get parentheses so (2 + 3) * 4 keeps its
4478
- // 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.
4479
4805
  case 'BinaryExpression': {
4480
- 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)
4481
4819
  ? `(${generateExpr(node.left, context)})`
4482
4820
  : generateExpr(node.left, context);
4483
- const right = node.right.type === 'BinaryExpression'
4821
+ const right = needsParens(node.right)
4484
4822
  ? `(${generateExpr(node.right, context)})`
4485
4823
  : generateExpr(node.right, context);
4486
4824
  return `${left} ${node.operator} ${right}`;
@@ -4550,7 +4888,7 @@ function generateExpr(node, context = createGenerationContext()) {
4550
4888
 
4551
4889
  case 'CallExpression': {
4552
4890
  // Method call: receiver.method(args). Member access invoked with parens -
4553
- // 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")).
4554
4892
  // Postfix calls f()(), arr[0](1), mul(6)(7) also bind here; any composite
4555
4893
  // callee (arrow, binary, comparison/logical condition) is parenthesised so
4556
4894
  // the call still applies to the whole value, not its last operand.
@@ -4564,9 +4902,10 @@ function generateExpr(node, context = createGenerationContext()) {
4564
4902
  node.callee.type === 'UnaryExpression';
4565
4903
  return `${composite ? `(${callee})` : callee}(${args})`;
4566
4904
  }
4567
- if (STDLIB[node.name]) {
4905
+ if (STDLIB[node.name] && !(context.declaredFunctions && context.declaredFunctions.has(node.name))) {
4568
4906
  if (node.name === 'readFile' || node.name === 'writeFile' ||
4569
- node.name === 'fileExists' || node.name === 'read') {
4907
+ node.name === 'fileExists' || node.name === 'read' ||
4908
+ node.name === 'write') {
4570
4909
  ensureBuiltin(context, 'fs');
4571
4910
  } else if (node.name === 'uuid') {
4572
4911
  ensureBuiltin(context, 'crypto');
@@ -4591,7 +4930,8 @@ function generateExpr(node, context = createGenerationContext()) {
4591
4930
 
4592
4931
  case 'CountOfExpression': {
4593
4932
  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)))`;
4933
+ const probe = (x) => `((${obj} && (${obj}).${x} !== undefined) ? (${obj}).${x} : `;
4934
+ return `${probe('count')}${probe('length')}${probe('size')}0)))`;
4595
4935
  }
4596
4936
 
4597
4937
  // v1.1 - Property access
@@ -4616,17 +4956,23 @@ function generateExpr(node, context = createGenerationContext()) {
4616
4956
 
4617
4957
  // v1.1 - Collection operations
4618
4958
  case 'AddCall':
4619
- 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)})`;
4620
4962
 
4621
4963
  case 'RemoveCall': {
4964
+ // Expression form evaluates to the (mutated) collection.
4622
4965
  const coll = generateExpr(node.collection, context);
4623
4966
  const val = generateExpr(node.value, context);
4624
- 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})`;
4625
4968
  }
4626
4969
 
4627
4970
  case 'WriteCall':
4628
4971
  ensureBuiltin(context, 'fs');
4629
- 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')`;
4630
4976
 
4631
4977
  // v1.0.1 - record constructor: `create a Person with name "Ada" and age 17`
4632
4978
  // calls the kind factory that `define a kind called "Person"` registered.