plainscript-lang 1.0.0 → 1.0.2-latest

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +194 -729
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +182 -79
  4. package/compiler/dependency-detector.js +5 -0
  5. package/compiler/formatter.js +1 -1
  6. package/compiler/generator.js +1083 -206
  7. package/compiler/lexer.js +130 -54
  8. package/compiler/parser.js +1117 -156
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +98 -435
  11. package/docs/PLAINSCRIPT-SPEC.md +335 -0
  12. package/docs/index.html +103 -605
  13. package/docs/website/script.js +59 -943
  14. package/docs/website/style.css +74 -656
  15. package/examples/ai-providers.pln +7 -0
  16. package/examples/arrays.pln +4 -0
  17. package/examples/async-errors.pln +18 -0
  18. package/examples/auth-api.pln +9 -0
  19. package/examples/auth-sessions.pln +32 -0
  20. package/examples/basics.pln +14 -0
  21. package/examples/bots.pln +13 -0
  22. package/examples/cache-and-jobs.pln +7 -0
  23. package/examples/cache-schedule.pln +22 -0
  24. package/examples/collections.pln +15 -0
  25. package/examples/concurrency.pln +18 -0
  26. package/examples/conditions.pln +22 -0
  27. package/examples/database.pln +8 -0
  28. package/examples/day2.pln +7 -0
  29. package/examples/day3.pln +5 -0
  30. package/examples/deployment.pln +6 -0
  31. package/examples/email-send.pln +3 -0
  32. package/examples/error-handling.pln +7 -0
  33. package/examples/expressions.pln +7 -0
  34. package/examples/file-uploads.pln +10 -0
  35. package/examples/files-and-config.pln +6 -0
  36. package/examples/files.pln +12 -0
  37. package/examples/football-backend/{app.ps → app.pln} +22 -21
  38. package/examples/functions.pln +17 -0
  39. package/examples/hello.pln +2 -0
  40. package/examples/http-client.pln +3 -0
  41. package/examples/http.pln +11 -0
  42. package/examples/id-verification/{app.ps → app.pln} +5 -4
  43. package/examples/id-verification/make-sample-id.js +29 -42
  44. package/examples/json.pln +11 -0
  45. package/examples/loops.pln +18 -0
  46. package/examples/modules/app.pln +3 -0
  47. package/examples/modules/main.pln +4 -0
  48. package/examples/modules/math.pln +9 -0
  49. package/examples/mongo.pln +33 -0
  50. package/examples/objects.pln +4 -0
  51. package/examples/ocr.pln +22 -0
  52. package/examples/packages.pln +6 -0
  53. package/examples/record-kinds.pln +7 -0
  54. package/examples/records.pln +15 -0
  55. package/examples/rest-api-fetch.pln +10 -0
  56. package/examples/rest-api.pln +8 -0
  57. package/examples/scheduled-tasks.pln +4 -0
  58. package/examples/search-and-filter.pln +4 -0
  59. package/examples/server.pln +6 -0
  60. package/examples/sessions-and-cookies.pln +8 -0
  61. package/examples/sqlite.pln +23 -0
  62. package/examples/start.pln +2 -0
  63. package/examples/stdlib.pln +4 -0
  64. package/examples/telegram-ai-bot.pln +19 -0
  65. package/examples/telegram-bot.pln +6 -0
  66. package/examples/testing.pln +13 -0
  67. package/examples/web-api.pln +27 -0
  68. package/examples/web-app.pln +8 -0
  69. package/examples/websocket-server.pln +6 -0
  70. package/examples/websocket.pln +13 -0
  71. package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +4 -5
  72. package/examples/whatsapp-bot/qr.pln +12 -0
  73. package/package.json +3 -2
  74. package/docs/PLINJS_SPEC.md +0 -1151
  75. package/examples/arrays.ps +0 -13
  76. package/examples/auth-api.ps +0 -56
  77. package/examples/cache-and-jobs.ps +0 -29
  78. package/examples/concurrency.ps +0 -49
  79. package/examples/database.ps +0 -41
  80. package/examples/day2.ps +0 -7
  81. package/examples/day3.ps +0 -11
  82. package/examples/deployment.ps +0 -12
  83. package/examples/email-send.ps +0 -22
  84. package/examples/error-handling.ps +0 -54
  85. package/examples/expressions.ps +0 -40
  86. package/examples/file-uploads.ps +0 -39
  87. package/examples/files-and-config.ps +0 -47
  88. package/examples/hello.ps +0 -3
  89. package/examples/http-client.ps +0 -44
  90. package/examples/loops.ps +0 -17
  91. package/examples/modules/app.ps +0 -16
  92. package/examples/modules/math.ps +0 -20
  93. package/examples/objects.ps +0 -12
  94. package/examples/record-kinds.ps +0 -43
  95. package/examples/rest-api-fetch.ps +0 -94
  96. package/examples/rest-api.ps +0 -68
  97. package/examples/scheduled-tasks.ps +0 -23
  98. package/examples/search-and-filter.ps +0 -34
  99. package/examples/server.ps +0 -25
  100. package/examples/sessions-and-cookies.ps +0 -54
  101. package/examples/start.ps +0 -2
  102. package/examples/stdlib.ps +0 -41
  103. package/examples/telegram-bot.ps +0 -42
  104. package/examples/web-app.ps +0 -20
  105. package/examples/websocket-server.ps +0 -27
  106. package/examples/whatsapp-bot/qr.ps +0 -8
@@ -45,8 +45,8 @@ function resolveDependencies(entryPath) {
45
45
  }
46
46
 
47
47
  // Parse the file to discover its own imports.
48
- // Annotate any tokenise/parse error with the filename so callers see
49
- // "file.ps — Line N, Column N: …" rather than a bare positional message.
48
+ // Annotate any tokenise/parse error with the filename so callers see
49
+ // "file.pln — Line N, Column N: …" rather than a bare positional message.
50
50
  const source = fs.readFileSync(absPath, 'utf8');
51
51
  let tokens, ast;
52
52
  try {
package/compiler/cli.js CHANGED
@@ -1,23 +1,25 @@
1
1
  #!/usr/bin/env node
2
- // CLI: compile and run PlainScript (.ps) files.
2
+ // CLI: compile and run PlainScript (.pln) files.
3
3
  //
4
- // Usage:
5
- // plainscript run <file.ps> install missing dependencies, compile and execute
6
- // plainscript build [file.ps] compile src/ (or one file) to dist/, names preserved
7
- // plainscript check <file.ps> check syntax only (no JS generated, no execution)
8
- // plainscript fmt <file.ps> format a PlainScript file in-place
9
- // plainscript new [name] scaffold a new PlainScript project
10
- // plainscript install install dependencies detected in the project's sources
11
- // plainscript start build src/app.ps (or index.ps) and run its dist output
12
- // plainscript doctor check the PlainScript project environment
13
- // plainscript add <package> install a package into the project
14
- // plainscript remove <package> uninstall a package from the project
15
- // plainscript update update all installed packages
16
- // plainscript version print the compiler version
17
- // plainscript help print this help text
4
+ // Usage:
5
+ // plainscript run <file.pln> install missing dependencies, compile and execute
6
+ // plainscript build [file.pln] compile src/ (or one file) to dist/, names preserved
7
+ // plainscript check [target] fully validate source(s): imports + generate + JS syntax
8
+ // (target: a .pln file, a directory, or none to scan the project)
9
+ // plainscript fmt <file.pln> format a PlainScript file in-place
10
+ // plainscript new [name] scaffold a new PlainScript project
11
+ // plainscript install install dependencies detected in the project's sources
12
+ // plainscript start build src/app.pln (or index.pln) and run its dist output
13
+ // plainscript doctor check the PlainScript project environment
14
+ // plainscript add <package> install a package into the project
15
+ // plainscript remove <package> uninstall a package from the project
16
+ // plainscript update update all installed packages
17
+ // plainscript version print the compiler version
18
+ // plainscript help print this help text
18
19
 
19
20
  const fs = require('fs');
20
21
  const path = require('path');
22
+ const vm = require('vm');
21
23
  const { execFileSync } = require('child_process');
22
24
  const { tokenize } = require('./lexer');
23
25
  const { parse } = require('./parser');
@@ -49,18 +51,20 @@ function warn(message) {
49
51
  const section = (title) => `\n${clrCyan(clrBold(title))}`;
50
52
 
51
53
  const HELP = `
52
- ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .ps compiles to readable Node.js')}
54
+ ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .pln compiles to readable Node.js')}
53
55
 
54
56
  ${section('START')}
55
- plainscript new [name] Scaffold a new project with a working app.ps
56
- plainscript run <file.ps> Install missing deps, compile, execute
57
- plainscript start Build src/app.ps and run it from dist/
57
+ plainscript new [name] Scaffold a new project with a working app.pln
58
+ plainscript run <file.pln> Install missing deps, compile, execute
59
+ plainscript start Build src/app.pln and run it from dist/
58
60
 
59
61
  ${section('BUILD & CHECK')}
60
- plainscript build Compile every .ps under src/ into dist/
61
- plainscript build <file.ps> Compile one file into dist/ (name preserved)
62
- plainscript check <file.ps> Syntax-check only — fastest feedback loop
63
- plainscript fmt <file.ps> Format a file in place
62
+ plainscript build Compile every .pln under src/ into dist/
63
+ plainscript build <file.pln> Compile one file into dist/ (name preserved)
64
+ plainscript check [target] Validate imports + generate + JS output (no writes)
65
+ target: a .pln file, a directory, or none = project scan
66
+ --json emits deterministic machine-readable output
67
+ plainscript fmt <file.pln> Format a file in place
64
68
 
65
69
  ${section('PACKAGES')}
66
70
  plainscript install Install everything your source needs
@@ -84,17 +88,17 @@ ${section('THE LANGUAGE IN EIGHT LINES')}
84
88
  try ... recover as err ... done retry 3 times every 5s errors
85
89
 
86
90
  ${section('ALSO SHIPPED')}
87
- Comparisons and stdlib (v1.0) · PlainScript Expressions (v1.1) ·
88
- JavaScript gateway with ask (v1.1.1) · OCR · Telegram bots ·
89
- WhatsApp bots (v2.1.1) ·
90
- email · schedules · WebSocket · cache (v2.1) ·
91
- sessions · uploads · cookies · rate limits · api keys · OAuth (v2.1.1)
91
+ Comparisons and stdlib · PlainScript Expressions ·
92
+ console input with ask · OCR · Telegram bots ·
93
+ WhatsApp bots ·
94
+ email · schedules · WebSocket · cache ·
95
+ sessions · uploads · cookies · rate limits · api keys · OAuth
92
96
  JSON body · redirect · AI chat/embeddings · vector similarity ·
93
- paginate · collection & string primitives (v2.2)
97
+ paginate · collection & string primitives
94
98
 
95
99
  ${section('FIRST RUN')}
96
100
  plainscript new hello scaffolds hello/ with a live web app
97
- plainscript run hello/app.ps serves it at http://localhost:3000
101
+ plainscript run hello/app.pln serves it at http://localhost:3000
98
102
  `.trim();
99
103
 
100
104
  // ── npm invocation ────────────────────────────────────────────────────────────
@@ -147,8 +151,8 @@ function isValidPackageName(name) {
147
151
  // "exclude": ["vendor"] } }
148
152
  //
149
153
  // Filenames and folder structure are always preserved:
150
- // src/messi.ps → dist/messi.js
151
- // src/helpers/math.ps → dist/helpers/math.js
154
+ // src/messi.pln → dist/messi.js
155
+ // src/helpers/math.pln → dist/helpers/math.js
152
156
  const SOURCE_DIR = 'src';
153
157
  const DEFAULT_OUT_DIR = 'dist';
154
158
 
@@ -181,7 +185,7 @@ function resolveOutDir(opts) {
181
185
  return DEFAULT_OUT_DIR;
182
186
  }
183
187
 
184
- // Every .ps file under srcDir, recursively, as paths relative to srcDir.
188
+ // Every .pln file under srcDir, recursively, as paths relative to srcDir.
185
189
  // Deterministic order (sorted); node_modules, hidden directories, the output
186
190
  // directory, and any user-specified exclude patterns are skipped.
187
191
  function discoverSources(srcDir, outDir, exclude) {
@@ -204,7 +208,7 @@ function discoverSources(srcDir, outDir, exclude) {
204
208
  try { stat = fs.statSync(full); } catch (_) { continue; }
205
209
  if (stat.isDirectory()) {
206
210
  walk(full);
207
- } else if (name.endsWith('.ps')) {
211
+ } else if (name.endsWith('.pln')) {
208
212
  found.push(path.relative(root, full));
209
213
  }
210
214
  }
@@ -401,7 +405,7 @@ function nodeModulesSearchPaths(entryDir) {
401
405
 
402
406
  async function cmdRun(filePath, extraArgs = []) {
403
407
  if (!filePath) {
404
- console.error('Usage: plainscript run <file.ps>');
408
+ console.error('Usage: plainscript run <file.pln>');
405
409
  process.exit(1);
406
410
  }
407
411
  const js = compile(filePath);
@@ -438,8 +442,8 @@ function buildOne(filePath, srcDir, outDir) {
438
442
  }
439
443
  const js = compile(absFile);
440
444
  const srcRoot = path.resolve(srcDir);
441
- let rel = path.relative(srcRoot, absFile).replace(/\.ps$/, '.js');
442
- if (rel.startsWith('..') || path.isAbsolute(rel)) rel = path.basename(absFile).replace(/\.ps$/, '.js');
445
+ let rel = path.relative(srcRoot, absFile).replace(/\.pln$/, '.js');
446
+ if (rel.startsWith('..') || path.isAbsolute(rel)) rel = path.basename(absFile).replace(/\.pln$/, '.js');
443
447
  const outPath = path.join(path.resolve(outDir), rel);
444
448
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
445
449
  fs.writeFileSync(outPath, js, 'utf8');
@@ -449,16 +453,16 @@ function buildOne(filePath, srcDir, outDir) {
449
453
  // `plainscript build` — TypeScript-style production build:
450
454
  //
451
455
  // Zero config (default):
452
- // messi.ps → dist/messi.js (project-root sources)
453
- // src/index.ps → dist/index.js (src/ is the source root)
454
- // src/a/b.ps → dist/a/b.js (structure preserved)
456
+ // messi.pln → dist/messi.js (project-root sources)
457
+ // src/index.pln → dist/index.js (src/ is the source root)
458
+ // src/a/b.pln → dist/a/b.js (structure preserved)
455
459
  //
456
460
  // With plainscript.config.json:
457
461
  // { "compilerOptions": { "outDir": "./build", "rootDir": "./lib" } }
458
- // lib/app.ps → build/app.js
462
+ // lib/app.pln → build/app.js
459
463
  //
460
464
  // With an explicit file argument only that entry is compiled; without one,
461
- // every .ps under the discovered source root builds to the output directory.
465
+ // every .pln under the discovered source root builds to the output directory.
462
466
  async function cmdBuild(filePath) {
463
467
  const opts = readCompilerOptions();
464
468
  const srcDir = resolveSrcDir(opts);
@@ -471,7 +475,7 @@ async function cmdBuild(filePath) {
471
475
  }
472
476
  const sources = discoverSources(srcDir, outDir, exclude);
473
477
  if (sources.length === 0) {
474
- console.error(`No .ps files found under "${srcDir}".`);
478
+ console.error(`No .pln files found under "${srcDir}".`);
475
479
  process.exit(1);
476
480
  }
477
481
  QUIET_STAGES = true;
@@ -496,7 +500,7 @@ async function cmdStart(extraArgs = []) {
496
500
  const outDir = resolveOutDir(opts);
497
501
  const entryPath = findEntry(opts);
498
502
  if (!entryPath) {
499
- console.error('No entry file found. Expected "src/app.ps" or "src/index.ps".');
503
+ console.error('No entry file found. Expected "src/app.pln" or "src/index.pln".');
500
504
  process.exit(1);
501
505
  }
502
506
  const outFile = buildOne(entryPath, srcDir, outDir);
@@ -521,34 +525,30 @@ function cmdNew(projectName) {
521
525
  fs.mkdirSync(path.join(dir, 'public'));
522
526
  fs.mkdirSync(path.join(dir, 'src'));
523
527
 
524
- // src/app.ps — starter Express app
525
- fs.writeFileSync(path.join(dir, 'src', 'app.ps'), `use express
526
-
527
- remember app as express()
528
+ // src/app.pln — starter web app
529
+ fs.writeFileSync(path.join(dir, 'src', 'app.pln'), `web app
528
530
 
529
531
  serve folder "public"
530
532
 
531
- when someone visits "/"
533
+ route get "/"
532
534
  reply "Hello from PlainScript!"
533
535
  done
534
536
 
535
- when someone visits "/api/status"
537
+ route get "/api/status"
536
538
  reply json
537
539
  status is "ok"
538
- version is "1.0"
540
+ version is "1.0.2-latest"
539
541
  done
540
542
  done
541
543
 
542
- listen on 3000
543
- show "Server running at http://localhost:3000"
544
- done
544
+ start 3000
545
545
  `);
546
546
 
547
547
  // package.json — plain Node semantics; PlainScript itself is a devDependency and
548
548
  // deployment only needs the generated dist/ output.
549
549
  fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
550
550
  name,
551
- version: '1.0.0',
551
+ version: VERSION,
552
552
  description: `A PlainScript v${VERSION} application`,
553
553
  main: 'dist/app.js',
554
554
  scripts: {
@@ -580,7 +580,7 @@ Then open http://localhost:3000 in your browser.
580
580
  `);
581
581
 
582
582
  console.log(`✓ Created project "${name}"`);
583
- console.log(`\nNext steps:\n cd ${name}\n npm install\n npx plainscript run src/app.ps`);
583
+ console.log(`\nNext steps:\n cd ${name}\n npm install\n npx plainscript run src/app.pln`);
584
584
  }
585
585
 
586
586
  // ── plainscript install ────────────────────────────────────────────────────────────
@@ -590,11 +590,11 @@ Then open http://localhost:3000 in your browser.
590
590
  function findEntry(opts) {
591
591
  const srcDir = resolveSrcDir(opts);
592
592
  const candidates = [
593
- path.join(srcDir, 'app.ps'),
594
- path.join(srcDir, 'index.ps'),
593
+ path.join(srcDir, 'app.pln'),
594
+ path.join(srcDir, 'index.pln'),
595
595
  ];
596
596
  if (srcDir !== '.') {
597
- candidates.push('app.ps', 'index.ps');
597
+ candidates.push('app.pln', 'index.pln');
598
598
  }
599
599
  return candidates.find((c) => fs.existsSync(path.resolve(c))) || null;
600
600
  }
@@ -609,7 +609,7 @@ function collectSourceAsts() {
609
609
  const exclude = opts && opts.exclude;
610
610
  const sources = discoverSources(srcDir, outDir, exclude);
611
611
  if (sources.length === 0) {
612
- console.error(`No .ps source files found under "${srcDir}".`);
612
+ console.error(`No .pln source files found under "${srcDir}".`);
613
613
  process.exit(1);
614
614
  }
615
615
  const root = path.resolve(srcDir);
@@ -665,14 +665,14 @@ function cmdDoctor() {
665
665
  check('Runtime', fs.existsSync(path.join(__dirname, 'generator.js')));
666
666
  console.log('');
667
667
 
668
- // Source discovery check: does the project have any .ps files?
668
+ // Source discovery check: does the project have any .pln files?
669
669
  const opts = readCompilerOptions();
670
670
  const srcDir = resolveSrcDir(opts);
671
671
  const outDir = resolveOutDir(opts);
672
672
  const exclude = opts && opts.exclude;
673
673
  const sources = discoverSources(srcDir, outDir, exclude);
674
674
  check('Source files', sources.length > 0,
675
- sources.length > 0 ? `"${srcDir}/" discovered (${sources.length} file(s))` : `no .ps files under "${srcDir}"`);
675
+ sources.length > 0 ? `"${srcDir}/" discovered (${sources.length} file(s))` : `no .pln files under "${srcDir}"`);
676
676
  if (sources.length === 0) return;
677
677
 
678
678
  // Dependency check: scan every source file for npm imports
@@ -747,31 +747,133 @@ function cmdUpdate() {
747
747
  }
748
748
 
749
749
  // Check syntax of a PlainScript file without generating JavaScript or executing.
750
- function cmdCheck(filePath) {
751
- if (!filePath) {
752
- console.error('Usage: plainscript check <file.ps>');
753
- process.exit(1);
754
- }
755
- const absPath = path.resolve(filePath);
756
- if (!fs.existsSync(absPath)) {
757
- console.error(`File not found: ${filePath}`);
758
- process.exit(1);
759
- }
750
+ // Full validation of a single .pln entry: resolve imports, parse+generate every
751
+ // file in dependency order, and verify the emitted JavaScript is syntactically
752
+ // valid — all without writing anything to disk. Returns a deterministic
753
+ // result record; `deps` are the npm packages the sources require.
754
+ function validateSource(absPath) {
755
+ const rel = path.relative(process.cwd(), absPath) || absPath;
760
756
  const t0 = Date.now();
761
757
  try {
762
- resolveDependencies(absPath);
763
- const ms = Date.now() - t0;
764
- console.log(`${clrGreen('✓')} ${filePath} — no errors found.${clrDim(` (${ms}ms)`)}`);
758
+ // resolveDependencies parses each file too, so a parse error anywhere in
759
+ // the import graph surfaces here with a "file.pln — Line:Col" prefix.
760
+ const files = resolveDependencies(absPath);
761
+ const context = createGenerationContext();
762
+ let js = files.map(({ ast }) => generate(ast, context)).filter(s => s.trim()).join('\n');
763
+ if (context.needsAsync) js = wrapAsync(js);
764
+
765
+ // The compiler must never emit broken JavaScript. Parsing the output with
766
+ // the V8 compiler catches generator regressions at check time.
767
+ new vm.Script(js);
768
+
769
+ // Collect unique npm dependencies across the file and its imports.
770
+ const deps = [];
771
+ for (const { absPath: f } of files) {
772
+ let source;
773
+ try { source = fs.readFileSync(f, 'utf8'); } catch (_) { continue; }
774
+ for (const d of detectDependencies(source)) {
775
+ if (!deps.includes(d)) deps.push(d);
776
+ }
777
+ }
778
+ return { file: rel, ok: true, deps, ms: Date.now() - t0 };
765
779
  } catch (err) {
766
- console.error(err.message);
780
+ return { file: rel, ok: false, error: err.message, ms: Date.now() - t0 };
781
+ }
782
+ }
783
+
784
+ // `plainscript check [target] [--json]`
785
+ //
786
+ // Fully validates one .pln file, every .pln under a directory, or (with no
787
+ // target) the project sources, deterministically and non-interactively:
788
+ // resolve imports, parse + generate, and confirm the JS output parses. Never
789
+ // prompts, never writes files, never installs packages.
790
+ //
791
+ // plainscript check validate every .pln in the project source root
792
+ // plainscript check app.pln validate one file (and its imports)
793
+ // plainscript check src/ validate every .pln under a directory
794
+ // plainscript check --json machine-readable JSON on stdout
795
+ function cmdCheck(target, json) {
796
+ const opts = readCompilerOptions();
797
+ const srcDir = resolveSrcDir(opts);
798
+ const outDir = resolveOutDir(opts);
799
+ const exclude = opts && opts.exclude;
800
+
801
+ let sources;
802
+ if (target) {
803
+ const abs = path.resolve(target);
804
+ if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
805
+ sources = discoverSources(abs, outDir, exclude).map(r => path.join(abs, r));
806
+ } else if (/\.pln$/.test(target) && !fs.existsSync(abs)) {
807
+ if (json) {
808
+ console.log(JSON.stringify({
809
+ plainscript: VERSION, ok: false,
810
+ sources: [], summary: { total: 0, passed: 0, failed: 1 },
811
+ errors: [{ file: target, error: `File not found: ${target}` }],
812
+ }));
813
+ } else {
814
+ console.error(`File not found: ${target}`);
815
+ }
816
+ process.exit(1);
817
+ } else {
818
+ sources = [abs];
819
+ }
820
+ } else {
821
+ const root = path.resolve(srcDir);
822
+ sources = discoverSources(srcDir, outDir, exclude).map(r => path.join(root, r));
823
+ if (sources.length === 0) {
824
+ const msg = `No .pln files found under "${srcDir}".`;
825
+ if (json) console.log(JSON.stringify({ plainscript: VERSION, ok: false, sources: [], summary: { total: 0, passed: 0, failed: 1 }, errors: [{ file: srcDir, error: msg }] }));
826
+ else console.error(msg);
827
+ process.exit(1);
828
+ }
829
+ }
830
+
831
+ sources.sort(); // deterministic regardless of filesystem order
832
+ const results = sources.map(validateSource);
833
+ const passed = results.filter(r => r.ok);
834
+ const failed = results.filter(r => !r.ok);
835
+
836
+ if (json) {
837
+ const dependencySummary = [];
838
+ const depIndex = new Map();
839
+ for (const r of passed) {
840
+ for (const d of r.deps) {
841
+ if (!depIndex.has(d)) { depIndex.set(d, []); dependencySummary.push(d); }
842
+ depIndex.get(d).push(r.file);
843
+ }
844
+ }
845
+ console.log(JSON.stringify({
846
+ plainscript: VERSION,
847
+ ok: failed.length === 0,
848
+ sources: results,
849
+ summary: { total: results.length, passed: passed.length, failed: failed.length },
850
+ dependencySummary: dependencySummary.map(d => ({ package: d, usedBy: depIndex.get(d) })),
851
+ }));
852
+ process.exit(failed.length ? 1 : 0);
853
+ }
854
+
855
+ for (const r of results) {
856
+ if (r.ok) {
857
+ console.log(`${clrGreen('✓')} ${r.file} — ok${clrDim(` (${r.ms}ms)`)}`);
858
+ } else {
859
+ console.log(`${clrRed('✗')} ${r.file}`);
860
+ console.error(r.error);
861
+ }
862
+ }
863
+
864
+ if (failed.length > 0) {
865
+ console.error(`\n${failed.length} of ${results.length} file(s) failed validation.`);
767
866
  process.exit(1);
768
867
  }
868
+ if (results.length > 0) {
869
+ console.log(clrGreen(`\n✓ ${results.length} file(s) validated.`));
870
+ }
769
871
  }
770
872
 
771
873
  // Format a PlainScript file in-place.
772
874
  function cmdFmt(filePath) {
773
875
  if (!filePath) {
774
- console.error('Usage: plainscript fmt <file.ps>');
876
+ console.error('Usage: plainscript fmt <file.pln>');
775
877
  process.exit(1);
776
878
  }
777
879
  const absPath = path.resolve(filePath);
@@ -805,6 +907,7 @@ async function main() {
805
907
  // Global flags — recognized anywhere in the argument list.
806
908
  const quiet = args.includes('--quiet');
807
909
  const verbose = args.includes('--verbose');
910
+ const json = args.includes('--json');
808
911
  if (quiet) { stage = stageQuiet; QUIET_STAGES = true; }
809
912
  if (verbose) { stage = stageVerbose; VERBOSE = true; }
810
913
 
@@ -817,7 +920,7 @@ async function main() {
817
920
  switch (command) {
818
921
  case 'run': await cmdRun(fileArg, positional.slice(2)); break;
819
922
  case 'build': await cmdBuild(fileArg); break;
820
- case 'check': cmdCheck(fileArg); break;
923
+ case 'check': cmdCheck(fileArg, json); break;
821
924
  case 'fmt': cmdFmt(fileArg); break;
822
925
  case 'new': cmdNew(fileArg); break;
823
926
  case 'install': cmdInstall(); break;
@@ -830,7 +933,7 @@ async function main() {
830
933
  case 'help': cmdHelp(); break;
831
934
  default:
832
935
  // Backwards-compatible: treat the first arg as a file to run directly
833
- if (command && command.endsWith('.ps')) {
936
+ if (command && command.endsWith('.pln')) {
834
937
  await cmdRun(command);
835
938
  } else {
836
939
  console.error(`Unknown command: "${command}". Run "plainscript help" for usage.`);
@@ -33,6 +33,8 @@ const PACKAGE_MAP = Object.freeze({
33
33
  // through qrcode-terminal. Neither package ever appears in PlainScript source.
34
34
  whatsapp: '@whiskeysockets/baileys',
35
35
  'wa-qrcode': 'qrcode-terminal',
36
+ // v2.2.0 — MongoDB driver.
37
+ mongodb: 'mongodb',
36
38
  });
37
39
 
38
40
  const BUILTIN_MODULES = new Set(builtinModules);
@@ -87,6 +89,9 @@ function visit(node, onUse) {
87
89
  } else if (node.type === 'PostgresStatement') {
88
90
  // v2.1.0 — `postgres "<url>"` uses node-postgres under the hood.
89
91
  onUse('postgres');
92
+ } else if (node.type === 'MongoStatement') {
93
+ // v2.2.0 — `mongo "<uri>"` uses mongodb driver under the hood.
94
+ onUse('mongodb');
90
95
  } else if (node.type === 'OcrStatement') {
91
96
  // v2.0.1 — `ocr "<image>" as <variable>` uses tesseract.js under the hood.
92
97
  onUse('ocr');
@@ -17,7 +17,7 @@ const INDENT_STARTERS = [
17
17
  /^make\s+\S+\s*\(/, // make name(...)
18
18
  /^if\s+/, // if ...
19
19
  /^otherwise\b/, // otherwise
20
- /^for\s+(each|every)\s+/, // for each ... / for every ...
20
+ /^for\s+each\s+/, // for each ...
21
21
  /^while\s+/, // while ...
22
22
  /^when\s+someone\s+visits/, // when someone visits ...
23
23
  /^when\s+someone\s+(sends|clicks)\b/, // when someone sends / clicks (Telegram)