plainscript-lang 0.1.7-latest

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +815 -0
  3. package/compiler/bundler.js +86 -0
  4. package/compiler/cli.js +843 -0
  5. package/compiler/dependency-detector.js +173 -0
  6. package/compiler/formatter.js +170 -0
  7. package/compiler/generator.js +2032 -0
  8. package/compiler/lexer.js +413 -0
  9. package/compiler/parser.js +2077 -0
  10. package/compiler/version.js +6 -0
  11. package/docs/PLINJS_SPEC.md +1051 -0
  12. package/docs/index.html +2287 -0
  13. package/docs/logo.jpg +0 -0
  14. package/docs/website/index.html +1500 -0
  15. package/docs/website/script.js +197 -0
  16. package/docs/website/style.css +1117 -0
  17. package/examples/arrays.pln +13 -0
  18. package/examples/cache-and-jobs.pln +29 -0
  19. package/examples/database.pln +41 -0
  20. package/examples/day2.pln +7 -0
  21. package/examples/day3.pln +11 -0
  22. package/examples/deployment.pln +12 -0
  23. package/examples/email-send.pln +22 -0
  24. package/examples/expressions.pln +40 -0
  25. package/examples/football-backend/app.pln +90 -0
  26. package/examples/hello.pln +3 -0
  27. package/examples/id-verification/app.pln +29 -0
  28. package/examples/id-verification/make-sample-id.js +123 -0
  29. package/examples/loops.pln +17 -0
  30. package/examples/objects.pln +12 -0
  31. package/examples/rest-api-fetch.pln +94 -0
  32. package/examples/rest-api.pln +68 -0
  33. package/examples/scheduled-tasks.pln +23 -0
  34. package/examples/server.pln +25 -0
  35. package/examples/start.pln +2 -0
  36. package/examples/stdlib.pln +41 -0
  37. package/examples/telegram-bot.pln +42 -0
  38. package/examples/web-app.pln +20 -0
  39. package/examples/websocket-server.pln +27 -0
  40. package/examples/whatsapp-bot/pairing.pln +17 -0
  41. package/examples/whatsapp-bot/qr.pln +8 -0
  42. package/package.json +47 -0
@@ -0,0 +1,1051 @@
1
+ # PlainScript Language Specification (v0.1.7)
2
+
3
+ Version: 2.1.1
4
+ Status: Stable
5
+ File Extension: .pln
6
+
7
+ Tagline: "When even a simple sentence can be code."
8
+
9
+ ---
10
+
11
+ ## Mission
12
+
13
+ PlainScript is an Intent-Oriented Programming Language (IOPL).
14
+
15
+ Its goal is to let developers describe WHAT they want while the compiler decides HOW JavaScript should implement it.
16
+
17
+ PlainScript is designed to be: beginner-friendly, readable, predictable, consistent, and easy to teach.
18
+
19
+ Every keyword should be understandable by a 12-year-old.
20
+
21
+ ---
22
+
23
+ ## Core Principles
24
+
25
+ 1. One way to do everything.
26
+ 2. Readability over fewer characters.
27
+ 3. Keywords never have aliases.
28
+ 4. Error messages should teach.
29
+ 5. JavaScript is an implementation detail.
30
+ 6. Code should read like documentation.
31
+
32
+ ---
33
+
34
+ ## Comments
35
+
36
+ // This is a comment
37
+
38
+ ---
39
+
40
+ ## Variables
41
+
42
+ Declare:
43
+
44
+ remember name as "Ayokunle"
45
+ remember age as 16
46
+
47
+ Reassign:
48
+
49
+ age becomes 17
50
+
51
+ ---
52
+
53
+ ## Printing
54
+
55
+ show "Hello"
56
+ show("Hello")
57
+ show age
58
+ show(players[0])
59
+ show user.name
60
+
61
+ Both keyword form (`show expr`) and call form (`show(expr)`) are valid and produce identical output.
62
+
63
+ ---
64
+
65
+ ## Conditions
66
+
67
+ if age is 18
68
+ show "Adult"
69
+ otherwise
70
+ show "Minor"
71
+ done
72
+
73
+ ### Comparison Operators
74
+
75
+ | PlainScript | JavaScript |
76
+ |------------------------------|--------------------|
77
+ | `is` / `is equal to` | `===` |
78
+ | `is not` | `!==` |
79
+ | `is greater than` | `>` |
80
+ | `is above` | `>` |
81
+ | `is less than` | `<` |
82
+ | `is below` | `<` |
83
+ | `is at least` | `>=` |
84
+ | `is at most` | `<=` |
85
+ | `is empty` | `.length === 0` |
86
+ | `is not empty` | `.length > 0` |
87
+ | `contains "x"` | `.includes("x")` |
88
+ | `starts with "x"` | `.startsWith("x")` |
89
+ | `ends with "x"` | `.endsWith("x")` |
90
+ | `between A and B` | `>= A && <= B` |
91
+
92
+ ---
93
+
94
+ ## Functions
95
+
96
+ make greet()
97
+ show "Hello"
98
+ done
99
+
100
+ greet()
101
+
102
+ make add(a, b)
103
+ give a + b
104
+ done
105
+
106
+ show add(5, 7)
107
+
108
+ ---
109
+
110
+ ## Arrays
111
+
112
+ remember players as [
113
+ "Haaland",
114
+ "Foden",
115
+ "Rodri"
116
+ ]
117
+
118
+ show players[0]
119
+ players[1] becomes "Palmer"
120
+
121
+ ---
122
+
123
+ ## Objects
124
+
125
+ remember user as
126
+ name is "Ayokunle"
127
+ age is 17
128
+ country is "Nigeria"
129
+ done
130
+
131
+ show user.name
132
+ user.age becomes 18
133
+
134
+ ---
135
+
136
+ ## Loops
137
+
138
+ For each:
139
+
140
+ for each player in players
141
+ show player
142
+ done
143
+
144
+ For every (alias for for each):
145
+
146
+ for every item in basket
147
+ show item
148
+ done
149
+
150
+ While:
151
+
152
+ while age is less than 18
153
+ age becomes age + 1
154
+ done
155
+
156
+ ---
157
+
158
+ ## Standard Library
159
+
160
+ All built-in functions are available without any `use` or `import` statement.
161
+
162
+ ### Strings & Numbers
163
+
164
+ | PlainScript | JavaScript equivalent |
165
+ |-----------------|-------------------------|
166
+ | `length(x)` | `(x).length` |
167
+ | `uppercase(x)` | `(x).toUpperCase()` |
168
+ | `lowercase(x)` | `(x).toLowerCase()` |
169
+ | `random()` | `Math.random()` |
170
+ | `round(x)` | `Math.round(x)` |
171
+
172
+ ### String Templates
173
+
174
+ Backtick-delimited strings preserve whitespace and support `${expression}` interpolation. They compile to JavaScript template literals.
175
+
176
+ remember name as "World"
177
+ remember greeting as `Hello ${name}!`
178
+ show greeting
179
+
180
+ remember body as `{"key": "value"}`
181
+ remember response as await fetch "https://api.example.com" with
182
+ method is "POST"
183
+ body is body
184
+ headers is { "Content-Type": "application/json" }
185
+ done
186
+
187
+ Multiline templates preserve line breaks:
188
+
189
+ remember email as `Dear ${customer},
190
+
191
+ Thank you for your order #${orderId}.
192
+
193
+ Best regards,
194
+ The Team`
195
+
196
+ Notes:
197
+ - Interpolation `${expr}` compiles directly to JavaScript `${expr}` — it is not evaluated at compile time.
198
+ - Literal dollar signs that are not followed by `{` are preserved as-is (e.g. `` `$5` ``).
199
+ - Escape sequences work in both string forms: double-quoted strings decode `\n`, `\t`, `\r`, `\0`, `\\`, `\"`, and `\'` (an unknown escape keeps the escaped character itself); inside backtick templates an escaped backtick stays literal instead of closing the string.
200
+ - Embedded backtick characters within the template content are escaped in the output.
201
+
202
+ ### I/O & Files
203
+
204
+ | PlainScript | JavaScript equivalent |
205
+ |------------------------------|--------------------------------------------------|
206
+ | `print(x)` | `console.log(x)` |
207
+ | `readFile(path)` | `require('fs').readFileSync(path, 'utf8')` |
208
+ | `writeFile(path, content)` | `require('fs').writeFileSync(path, content, 'utf8')` |
209
+ | `fileExists(path)` | `require('fs').existsSync(path)` |
210
+
211
+ ### Time & System
212
+
213
+ | PlainScript | JavaScript equivalent |
214
+ |----------------|----------------------------------------|
215
+ | `time()` | `Date.now()` |
216
+ | `date()` | `new Date().toISOString()` |
217
+ | `sleep(ms)` | `Atomics.wait(...)` (synchronous) |
218
+ | `uuid()` | `require('crypto').randomUUID()` |
219
+ | `env(key)` | `process.env[key]` |
220
+ | `exit(code)` | `process.exit(code)` |
221
+
222
+ ### JSON
223
+
224
+ | PlainScript | JavaScript equivalent |
225
+ |--------------------|-----------------------------|
226
+ | `jsonEncode(x)` | `JSON.stringify(x)` |
227
+ | `jsonDecode(s)` | `JSON.parse(s)` |
228
+
229
+ ---
230
+
231
+ ## PlainScript Imports
232
+
233
+ Split a project across multiple `.pln` files:
234
+
235
+ import "./math.pln"
236
+ import "./utils.pln"
237
+
238
+ Rules:
239
+
240
+ - Paths must be relative (start with `./` or `../`).
241
+ - Files are compiled in dependency order (deepest first).
242
+ - Duplicate imports are silently de-duplicated.
243
+ - Circular imports produce a friendly compiler error.
244
+ - Missing files produce a friendly compiler error.
245
+
246
+ Example project layout:
247
+
248
+ app.pln
249
+ math.pln
250
+ utils.pln
251
+
252
+ `math.pln`:
253
+
254
+ remember PI as 3.14
255
+
256
+ `app.pln`:
257
+
258
+ import "./math.pln"
259
+ show PI
260
+
261
+ Output: one combined JavaScript file with `math.pln` code before `app.pln` code.
262
+
263
+ ---
264
+
265
+ ## Runtime Packages
266
+
267
+ Supported packages:
268
+
269
+ use express → const express = require('express');
270
+ use sqlite → const Database = require('better-sqlite3');
271
+ use fs → const fs = require('fs');
272
+ use path → const path = require('path');
273
+
274
+ Any npm package can be declared, including hyphenated and scoped names
275
+ (RFC-0011 §5.1):
276
+
277
+ use axios → const axios = require('axios');
278
+ use node-fetch → require('node-fetch'); // side effect only
279
+ use @scope/package-name → require('@scope/package-name');
280
+
281
+ ### Aliases and version ranges
282
+
283
+ A package that is not a valid JavaScript identifier gets no binding by
284
+ default — declare an alias to bind it to a variable:
285
+
286
+ use node-fetch as fetch → const fetch = require('node-fetch');
287
+ use left-pad as pad → const pad = require('left-pad');
288
+ use @scope/pkg as scoped → const scoped = require('@scope/pkg');
289
+
290
+ Rules:
291
+
292
+ - The alias must be a valid JavaScript identifier; anything else fails with a
293
+ clear error.
294
+ - Built-in runtime packages (`express`, `sqlite`, `fs`, `path`, `axios`,
295
+ `chalk`) keep their canonical bindings; aliasing them is an error.
296
+ - A package can be required once per alias; the plain form and an aliased
297
+ form of the same package may coexist.
298
+
299
+ Version ranges are part of the specifier and flow through to installation;
300
+ `require()` always uses the bare name:
301
+
302
+ use left-pad@^1.3.0 → require('left-pad'); // npm install left-pad@^1.3.0
303
+ use sqlite@7 → const Database = require('better-sqlite3');
304
+ use dotenv@16 as env → const env = require('dotenv');
305
+
306
+ `plainscript install`, `plainscript run`, and `plainscript build` check installed-ness by bare
307
+ package name but install with the full `name@range` specifier.
308
+
309
+ ### Runtime dependency detection and installation
310
+
311
+ The compiler exposes a reusable dependency detector that reads PlainScript source
312
+ without duplicate results. It scans every `use` statement and runtime
313
+ shorthand, returning a unique list of npm package names in first-seen order.
314
+
315
+ PlainScript module names are mapped to npm packages:
316
+
317
+ | PlainScript module | npm package |
318
+ |--------------|-------------|
319
+ | `express` | `express` |
320
+ | `sqlite` | `better-sqlite3` |
321
+ | `web app` | `express` |
322
+ | `axios` | `axios` |
323
+ | `chalk` | `chalk` |
324
+ | `ocr` | `tesseract.js` |
325
+
326
+ Node built-in modules, including `fs` and `path`, are ignored because they do
327
+ not need to be installed. A source file with no runtime package uses returns
328
+ an empty list.
329
+
330
+ Version ranges survive detection: `use left-pad@^1.3.0` is reported as
331
+ `left-pad@^1.3.0`, and friendly names map through the range (`use sqlite@7`
332
+ is reported as `better-sqlite3@7`).
333
+
334
+ Built-in modules are never installed. Missing npm packages are installed by
335
+ `plainscript install`, `plainscript run`, and `plainscript build`; package checks are cached for
336
+ the duration of one CLI command so repeated imports do not rescan the
337
+ filesystem.
338
+
339
+ ### Deployment workflow
340
+
341
+ ```bash
342
+ npm install --save-dev plainscript
343
+ plainscript install
344
+ plainscript build app.pln
345
+ plainscript run app.pln
346
+ ```
347
+
348
+ `plainscript start` builds `src/app.pln` (or `src/index.pln`) into the output
349
+ directory and runs it. `plainscript doctor` reports missing tools, source files,
350
+ or dependencies. Generated JavaScript remains standard
351
+ Node.js-compatible JavaScript and runtime `require()` declarations are emitted
352
+ once in deterministic order.
353
+
354
+ ---
355
+
356
+ ## Express Server
357
+
358
+ Classic style:
359
+
360
+ use express
361
+
362
+ remember app as express()
363
+
364
+ serve folder "public"
365
+
366
+ when someone visits "/"
367
+ reply "Hello from PlainScript!"
368
+ done
369
+
370
+ when someone visits "/api/status"
371
+ reply json
372
+ status is "ok"
373
+ version is "1.0"
374
+ done
375
+ done
376
+
377
+ listen on 3000
378
+ show "Server running at http://localhost:3000"
379
+ done
380
+
381
+ Shorthand style:
382
+
383
+ web app
384
+
385
+ route "/"
386
+ reply "Hello from PlainScript!"
387
+ done
388
+
389
+ start 3000
390
+
391
+ ### Routes
392
+
393
+ when someone visits "<path>"
394
+ ...
395
+ done
396
+
397
+ route "<path>"
398
+ ...
399
+ done
400
+
401
+ Both compile to: `app.get(path, (req, res) => { ... })`
402
+
403
+ Inside route bodies:
404
+
405
+ - `request` → `req`
406
+ - `response` → `res`
407
+
408
+ ### Sending Responses
409
+
410
+ reply "Hello" → res.send("Hello")
411
+ reply user → res.send(user)
412
+
413
+ ### JSON Responses
414
+
415
+ reply json
416
+ name is "PlainScript"
417
+ version is "1.0"
418
+ done
419
+
420
+ Compiles to: `res.json({ "name": "PlainScript", "version": "1.0" })`
421
+
422
+ ### Static Files
423
+
424
+ serve folder "public"
425
+
426
+ Compiles to: `app.use(express.static("public"))`
427
+
428
+ ### Listening
429
+
430
+ listen on 3000
431
+ show "Running"
432
+ done
433
+
434
+ Compiles to: `app.listen(3000, () => { ... })`
435
+
436
+ ### Start (shorthand)
437
+
438
+ start 3000
439
+
440
+ Compiles to: `app.listen(3000)`
441
+
442
+ ---
443
+
444
+ ## SQLite
445
+
446
+ Classic style:
447
+
448
+ use sqlite
449
+
450
+ remember db as sqlite("database.db")
451
+
452
+ Compiles to: `new Database("database.db")`
453
+
454
+ Shorthand style:
455
+
456
+ database "app.db"
457
+
458
+ execute
459
+ CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)
460
+ done
461
+
462
+ insert
463
+ INSERT INTO users (name) VALUES ('Alice')
464
+ done
465
+
466
+ query
467
+ SELECT * FROM users
468
+ done
469
+
470
+ ### SQL Block Commands
471
+
472
+ | PlainScript | Compiles to |
473
+ |--------------------|----------------------------------|
474
+ | `database "f.db"` | `const db = new Database("f.db")`|
475
+ | `query ... done` | `db.prepare(...).all()` |
476
+ | `insert ... done` | `db.prepare(...).run()` |
477
+ | `update ... done` | `db.prepare(...).run()` |
478
+ | `delete ... done` | `db.prepare(...).run()` |
479
+ | `execute ... done` | `db.exec(...)` |
480
+
481
+ ---
482
+
483
+ ## HTTP Routing
484
+
485
+ Method routes extend the basic route shorthand. The plain form stays GET.
486
+
487
+ route get|post|put|patch|delete "<path>" ... done
488
+ group "<prefix>" ... done
489
+
490
+ Groups compose: a route inside two groups accumulates both prefixes.
491
+ `param("id")`, `query("page")` and `header("x-token")` read request data and
492
+ are compile-time errors outside routes. `status <expr>` sets the response
493
+ code; `status becomes n` keeps its ordinary variable meaning. `allow cors`
494
+ enables permissive CORS middleware (including OPTIONS preflight). Inside a
495
+ `web app` block the body is parsed as JSON automatically.
496
+
497
+ remember missing as validate(body of request, ["name", "email"])
498
+
499
+ returns the list of missing field names.
500
+
501
+ ## Databases
502
+
503
+ SQL placeholders are written `{likeThis}` and bind to PlainScript variables of the
504
+ same name. Results are captured with `remember`:
505
+
506
+ database "app.db"
507
+ remember who as "ana"
508
+ insert
509
+ INSERT INTO users (name) VALUES ({who})
510
+ done
511
+ remember adults as query
512
+ SELECT * FROM users WHERE age >= {minAge}
513
+ done
514
+ transaction
515
+ insert
516
+ INSERT INTO users (name) VALUES ('bo')
517
+ done
518
+ done
519
+
520
+ A `transaction ... done` block runs all enclosed writes atomically.
521
+
522
+ PostgreSQL swaps the driver for every later SQL statement:
523
+
524
+ postgres env("DATABASE_URL")
525
+
526
+ compiles to `new Pool({ connectionString })`; queries become awaited pool
527
+ queries with `$n` markers, and `remember x as query` captures `.rows`.
528
+
529
+ ## Filesystem and Helpers
530
+
531
+ Filesystem: `copyFile`, `moveFile`, `deleteFile`, `makeFolder`,
532
+ `deleteFolder`, `listFolder`, `appendFile`, `readBytes`, `writeBytes`.
533
+
534
+ Text/numbers: `trim`, `replace`, `split`, `join`, `number`, `text`, `floor`,
535
+ `ceiling`. Collections: `sort` (unified ordering across types), `reverse`,
536
+ `unique`, `sum`, `smallest`, `largest`, `keys`, `values`, `hasKey`, `merge`.
537
+
538
+ ## Email
539
+
540
+ mail transport
541
+ host is "smtp.gmail.com"
542
+ port is 587
543
+ user is env("EMAIL_USER")
544
+ pass is env("EMAIL_PASS")
545
+ done
546
+
547
+ send mail
548
+ from is "hello@plainscript.dev"
549
+ to is "you@example.com"
550
+ subject is "Hello"
551
+ text is "Body"
552
+ done
553
+
554
+ Uses nodemailer; `user`/`pass` become the SMTP `auth`.
555
+
556
+ ## Scheduling and Background Jobs
557
+
558
+ every 5 minutes
559
+ show "tick"
560
+ done
561
+
562
+ schedule "0 2 * * *"
563
+ show "nightly cleanup"
564
+ done
565
+
566
+ run background resizeImage("photo.png")
567
+
568
+ `every` accepts seconds/minutes/hours/days (plural or singular). `schedule`
569
+ accepts any standard cron expression (powered by croner). `run background`
570
+ fires the call without blocking; errors are logged, never raised.
571
+
572
+ ## WebSocket Servers
573
+
574
+ websocket server on 8080
575
+ when socket connects
576
+ send socket "Welcome!"
577
+ done
578
+ when socket sends message
579
+ broadcast message
580
+ done
581
+ when socket disconnects
582
+ done
583
+ done
584
+
585
+ Handlers are optional. `send socket <value>` replies to one client,
586
+ `broadcast <value>` to all connected clients. Uses the ws package.
587
+
588
+ ## Cache
589
+
590
+ cache "redis://localhost:6379"
591
+
592
+ connects Redis once. Then:
593
+
594
+ | PlainScript | Compiles to |
595
+ |------------------------------|--------------------------------|
596
+ | `cacheGet("k")` | `client.get(k)` |
597
+ | `cacheSet("k", v)` | `client.set(k, v)` |
598
+ | `cacheSet("k", v, 60)` | `client.set(k, v, { EX: 60 })` |
599
+ | `cacheDelete("k")` | `client.del(k)` |
600
+
601
+ All three are async and require a configured cache first.
602
+
603
+ ---
604
+
605
+ ## Backend Services
606
+
607
+ All statements below compile deterministically. Implementation packages
608
+ (`better-sqlite3`, `sql.js`, `multer`) are detected and installed
609
+ automatically; they never appear in PlainScript source.
610
+
611
+ ### Portable databases
612
+
613
+ database "app.db" // probe native, fall back to WebAssembly
614
+ database "app.db" using "native" // require better-sqlite3
615
+ database "app.db" using "wasm" // require sql.js
616
+
617
+ - The default probes the native driver (`better-sqlite3`) by opening an
618
+ in-memory database; if that fails, the program continues on the pure-
619
+ JavaScript WebAssembly engine (`sql.js`).
620
+ - `using "native"` / `using "wasm"` pin the engine; anything else fails at
621
+ compile time.
622
+ - The WebAssembly engine writes the whole database file after every mutating
623
+ statement, so data survives restarts. In-memory databases (`":memory:"`)
624
+ are never persisted.
625
+ - Transactions run their body exactly once on both engines.
626
+
627
+ ### HTTP client
628
+
629
+ get "<url>"
630
+ post <url> with <body>
631
+ put <url> with <body>
632
+ patch <url> with <body>
633
+ delete "<url>"
634
+
635
+ Optional clauses on any method: `headers { key is "value" ... }` (inline
636
+ object or block form) and `timeout <milliseconds>`. Requests are values, so
637
+ they compose:
638
+
639
+ remember r as get "https://api.example.com/users"
640
+
641
+ The response is a record:
642
+
643
+ | Field | Meaning |
644
+ |------------|------------------------------------------------------|
645
+ | `ok of r` | `true` for 2xx status codes |
646
+ | `status` | HTTP status number |
647
+ | `headers` | response headers as a record |
648
+ | `data` | parsed JSON body when the content type says `json`, otherwise the raw text |
649
+
650
+ Bodies sent to `post`/`put`/`patch`: records and arrays are serialised as
651
+ JSON; strings and buffers are sent verbatim. The default timeout is 30
652
+ seconds; a timeout aborts the request and rejects. `wait for fetch(...)`
653
+ awaits a raw promise.
654
+
655
+ ### Passwords and tokens
656
+
657
+ | PlainScript | Behaviour |
658
+ |----------------------------------------|----------------------------------------------|
659
+ | `hashPassword(pw)` | scrypt hash with per-password salt |
660
+ | `checkPassword(pw, storedHash)` | constant-time verification, returns boolean |
661
+ | `createToken(payload, secret [, ttl])` | HMAC-signed token, default TTL 3600 seconds |
662
+ | `readToken(token, secret)` | verified payload or null (tamper/expiry) |
663
+
664
+ ### Sessions
665
+
666
+ web app
667
+ enable sessions "a-long-random-secret"
668
+ route post "/login"
669
+ user of session of request becomes username of body of request
670
+ reply "welcome"
671
+ done
672
+ route post "/logout"
673
+ destroy session
674
+ reply "bye"
675
+ done
676
+
677
+ - The session rides an HMAC-signed cookie named `plainscript.sid`
678
+ (`HttpOnly`, `SameSite=Lax`).
679
+ - `session of request` is the session record; assign fields onto it with
680
+ `becomes`.
681
+ - Reading `session of request` outside a route, or without
682
+ `enable sessions`, is a teaching error.
683
+ - The store lives in memory: restarting the process signs everyone out.
684
+
685
+ ### File uploads
686
+
687
+ accept uploads limit "5 MB" allow ["image/png", "image/jpeg"] folder "uploads"
688
+
689
+ All clauses are optional; the statement must appear before the routes it
690
+ protects. Inside routes:
691
+
692
+ | PlainScript | Result |
693
+ |---------------------|-------------------------------------------------------|
694
+ | `upload("field")` | first file under the field, or null |
695
+ | `uploads("field")` | array of files under the field |
696
+
697
+ Each file is a record: `name` (original name), `type` (MIME), `size` (bytes),
698
+ `data` (buffer, memory storage) and `path` (string, folder storage). A file
699
+ over the limit is rejected with HTTP **413**; a disallowed MIME type with
700
+ HTTP **415**. With `folder`, uploaded files are written to disk (the folder
701
+ is created if needed).
702
+
703
+ ### Cookies
704
+
705
+ set cookie "theme" to "dark" expires in 7 days
706
+ show cookie("theme")
707
+ clear cookie "theme"
708
+
709
+ `expires in` accepts seconds/minutes/hours/days. Cookie accessors are
710
+ route-only.
711
+
712
+ ### Rate limiting
713
+
714
+ limit requests to 100 per minute
715
+
716
+ Sliding window keyed by client IP; requests past the quota receive HTTP 429.
717
+ Units: seconds, minutes, hours.
718
+
719
+ ### API-key protection
720
+
721
+ require api key from env("API_KEY")
722
+
723
+ Requests must carry the expected value in the `x-api-key` header; everything
724
+ else receives HTTP 401. When the configured key is unset, every request is
725
+ rejected (fail closed). Middleware applies to routes registered after it.
726
+
727
+ ### Google OAuth
728
+
729
+ google oauth
730
+ id is env("GOOGLE_ID")
731
+ secret is env("GOOGLE_SECRET")
732
+ callback is "https://myapp.dev/auth/google/callback"
733
+ landing is "/dashboard"
734
+ done
735
+
736
+ Registers two endpoints: `/auth/google` redirects to Google's consent screen
737
+ with a signed `state`; `/auth/google/callback` validates the state, swaps the
738
+ code for tokens, fetches the profile and stores the user on the session
739
+ before redirecting to `landing`.
740
+
741
+ ### Custom 404
742
+
743
+ when nothing matches
744
+ status 404
745
+ reply json
746
+ error is "No such road"
747
+ done
748
+ done
749
+
750
+ Registers the final handler at its source position — place it after your
751
+ routes.
752
+
753
+ ### Error handling
754
+
755
+ try
756
+ remember data as jsonDecode(raw)
757
+ recover as err
758
+ show "bad json: " + message of err
759
+ done
760
+
761
+ `recover` is optional; without it errors are swallowed. `err` is the thrown
762
+ value (use `message of err` for Error objects).
763
+
764
+ ### Retries
765
+
766
+ retry 3 times every 5 seconds
767
+ wait for fetch("https://flaky.api")
768
+ done
769
+
770
+ `every` is optional (default delay one second); zero seconds retries
771
+ immediately. The body runs until it succeeds or attempts run out; failures
772
+ are logged with the last error.
773
+
774
+ ---
775
+
776
+ ## OCR
777
+
778
+ Extract text from an image file with Tesseract.js:
779
+
780
+ ocr "scan.png" as text
781
+ show text
782
+
783
+ With a language pack:
784
+
785
+ ocr "brief.png" as inhalt using "deu"
786
+
787
+ Semantics:
788
+
789
+ - `ocr "<image>" as <variable>` mirrors `ask "<prompt>" as <name>`: the
790
+ extracted text is bound to `<variable>`.
791
+ - The image may be any expression that evaluates to an image path, buffer,
792
+ or URL accepted by Tesseract.js.
793
+ - `using "<lang>"` selects the Tesseract language pack (`"eng"` by default;
794
+ combinations like `"deu+eng"` are allowed).
795
+ - The statement is async — top-level use wraps the program in the async
796
+ runtime, and using it inside a function makes that function async.
797
+ - `tesseract.js` is an implementation dependency: it never appears in PlainScript
798
+ source, but `plainscript install`, `plainscript run`, and `plainscript build` fetch it
799
+ automatically through dependency detection.
800
+
801
+ Generated JavaScript shape:
802
+
803
+ ```js
804
+ const { createWorker } = require('tesseract.js');
805
+
806
+ async function __ocr(imagePath, lang) {
807
+ const worker = await createWorker(lang || 'eng');
808
+ try {
809
+ const { data } = await worker.recognize(imagePath);
810
+ return data.text;
811
+ } finally {
812
+ await worker.terminate();
813
+ }
814
+ }
815
+
816
+ let text = await __ocr("scan.png");
817
+ ```
818
+
819
+ ---
820
+
821
+ ## WhatsApp Bots
822
+
823
+ A `whatsapp bot` block declares one WhatsApp connection and its message
824
+ handlers. The implementation package (`@whiskeysockets/baileys`, with
825
+ `qrcode-terminal` for QR rendering) is detected, installed, and hidden —
826
+ it never appears in PlainScript source.
827
+
828
+ whatsapp bot
829
+ auth "session" // credential folder
830
+ login pairing "2348012345678" // or: login qr
831
+ // or: login pairing phone
832
+
833
+ on message
834
+ log message
835
+
836
+ if message.text is "/start"
837
+ reply "Welcome!"
838
+ done
839
+
840
+ if message.text is "/help"
841
+ reply `Available commands:
842
+ /start /help`
843
+ done
844
+ done
845
+ done
846
+
847
+ Interactive linking — the number may come from any value:
848
+
849
+ ask "WhatsApp number: " as phone
850
+
851
+ whatsapp bot
852
+ auth "session"
853
+ login pairing phone
854
+ done
855
+
856
+ Syntax:
857
+
858
+ - The block opens with `whatsapp bot` and closes with `done`. It may contain
859
+ at most one `auth`, one `login`, and any number of `on message` handlers;
860
+ anything else is a teaching error.
861
+ - `auth "<folder>"` selects the credential folder created by
862
+ `useMultiFileAuthState` and reused across restarts. Optional; defaults to
863
+ `"plainscript-whatsapp-auth"`.
864
+ - `login qr` links by scanning a terminal QR code; it is the default when the
865
+ clause is omitted. `login pairing "<number>"` requests an enter-on-phone
866
+ pairing code instead. Pairing numbers are validated at compile time: after
867
+ stripping separators and a leading plus (`+234 801-234-5678`) they must be
868
+ 8–15 digits.
869
+ - `login pairing` also accepts any PlainScript value
870
+ (`login pairing phone`) — typically a variable filled by `ask`. Values are
871
+ normalized and validated when the bot starts; invalid input fails with the
872
+ same teaching message before any connection attempt.
873
+ - `on message ... done` registers one handler for incoming messages. Inside:
874
+ - `message` refers to the normalized record `{ text, chat, sender, name,
875
+ id, time, isGroup }` of the current delivery.
876
+ - `log message` prints the record to the console; using it outside an
877
+ `on message` body is a compile-time teaching error.
878
+ - `reply <value>` answers the current chat — strings verbatim, other values
879
+ as JSON.
880
+
881
+ Runtime semantics:
882
+
883
+ - Only `messages.upsert` events of type `notify` are delivered; the bot's own
884
+ outgoing messages (`fromMe`) and `status@broadcast` are filtered out before
885
+ handlers run.
886
+ - Ephemeral and view-once wrappers are unwrapped; text falls back through
887
+ caption fields for media messages.
888
+ - Group chats set `sender` to the participant JID and `isGroup` to true;
889
+ replies go to the group chat.
890
+ - Handler errors are logged and never crash the process.
891
+ - On transient disconnects the socket reconnects after 3 seconds; a remote
892
+ sign-out stops cleanly instead of looping.
893
+
894
+ Generated JavaScript shape (abridged):
895
+
896
+ ```js
897
+ const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {
898
+ // makeWASocket + useMultiFileAuthState + fetchLatestBaileysVersion live in
899
+ // here, behind require('@whiskeysockets/baileys')
900
+ })();
901
+ await __whatsappStart({ folder: "session", login: { mode: 'pairing', phone: "2348012345678" } });
902
+ // value form: login: { mode: 'pairing', phone: (phone) }
903
+ __whatsappOnMessage(async (__waCtx) => {
904
+ console.log(__waCtx.message);
905
+ if (__waCtx.message.text === "/start") {
906
+ await __whatsappReply(__waCtx.chat, "Welcome!");
907
+ }
908
+ });
909
+ ```
910
+
911
+ ---
912
+
913
+ ## Developer Experience
914
+
915
+ ### Formatter
916
+
917
+ Format a PlainScript file in-place:
918
+
919
+ plainscript fmt app.pln
920
+
921
+ Formatting rules:
922
+
923
+ - 4-space consistent indentation
924
+ - Trailing whitespace removed from every line
925
+ - One blank line between top-level blocks
926
+ - Multiple consecutive blank lines collapsed into one
927
+ - Multi-line array elements indented relative to their enclosing block
928
+
929
+ ### Syntax Checker
930
+
931
+ Check syntax without generating JavaScript or running anything:
932
+
933
+ plainscript check app.pln
934
+
935
+ Exits with code 0 if no errors are found. Exits with code 1 and prints a
936
+ friendly error (with line, column, and suggestion where possible) if the
937
+ file contains a syntax error.
938
+
939
+ ### VS Code Extension
940
+
941
+ Install `plainscript-vscode` for:
942
+
943
+ - Syntax highlighting
944
+ - File icon for `.pln` files
945
+ - Auto-closing pairs: `()` `[]` `{}` `""`
946
+ - Comment toggling (`//`)
947
+ - Bracket matching
948
+ - Code folding
949
+ - Snippets for common patterns
950
+
951
+ See `plainscript-vscode/README.md` for installation instructions.
952
+
953
+ ### Acode Editor
954
+
955
+ Acode support (`plainscript-acode/`) provides syntax highlighting and `.pln` file
956
+ recognition in the [Acode](https://acode.app) Android editor, using Acode's
957
+ modern CodeMirror 6 `editorLanguages` API.
958
+
959
+ Install it by zipping the `plainscript-acode/` folder contents (`plugin.json`,
960
+ `main.js`, `stream-spec.js`, `README.md`) and selecting the zip in Acode:
961
+ Settings → Plugins → "+".
962
+
963
+ Acode support highlights keywords, comparisons, strings, numbers, comments,
964
+ route paths, `use` package names, stdlib calls, expression words, number
965
+ words, and JavaScript/SQL blocks. It does **not** provide LSP diagnostics,
966
+ autocomplete, or compiler execution. The tokenizer in `stream-spec.js` is
967
+ pure CommonJS and is exercised by the test suite (`tests/compiler.test.js`).
968
+
969
+ See `plainscript-acode/README.md` for details.
970
+
971
+ ---
972
+
973
+ ## Project Management
974
+
975
+ PlainScript follows a zero-configuration model. Source files live in `src/` (or the
976
+ project root when `src/` doesn't exist) and `plainscript build` discovers them
977
+ automatically, preserving file names and directory structure into `dist/`.
978
+
979
+ For projects that need custom output or source directories, add an optional
980
+ `plainscript.config.json` with a `compilerOptions` block:
981
+
982
+ ```json
983
+ {
984
+ "compilerOptions": {
985
+ "outDir": "./build",
986
+ "rootDir": "./lib",
987
+ "exclude": ["vendor"]
988
+ }
989
+ }
990
+ ```
991
+
992
+ ### Commands
993
+
994
+ | Command | Behaviour |
995
+ |-------------------------|------------------------------------------------------|
996
+ | `plainscript run <file.pln>` | Install dependencies, compile and execute |
997
+ | `plainscript build [file]` | Compile to dist/ preserving names; no arg builds all|
998
+ | `plainscript check <file.pln>` | Check syntax only (no output, no execution) |
999
+ | `plainscript fmt <file.pln>` | Format a PlainScript file in-place |
1000
+ | `plainscript new [name]` | Create a new PlainScript project |
1001
+ | `plainscript install` | Detect and install dependencies from source files |
1002
+ | `plainscript start` | Build src/app.pln and run its dist/ output |
1003
+ | `plainscript doctor` | Check the PlainScript project environment |
1004
+ | `plainscript add <pkg>` | Install a package into the project |
1005
+ | `plainscript remove <pkg>` | Uninstall a package from the project |
1006
+ | `plainscript update` | Runs `npm update` for all installed packages |
1007
+ | `plainscript version` | Print the compiler version |
1008
+ | `plainscript help` | Print help text |
1009
+
1010
+ ### Dependency Validation
1011
+
1012
+ Before compiling, PlainScript checks that every package referenced by `use` is installed.
1013
+ If a package is missing, the compiler prints a friendly error and stops:
1014
+
1015
+ Package "express" is not installed.
1016
+ Run: plainscript add express
1017
+
1018
+ ---
1019
+
1020
+ ## Reserved Keywords
1021
+
1022
+ remember becomes show
1023
+ make give
1024
+ if otherwise done
1025
+ for each every in
1026
+ while
1027
+ use import
1028
+ when someone visits
1029
+ listen on
1030
+ reply json
1031
+ serve folder
1032
+ is greater less than
1033
+ above below at least most
1034
+ not empty contains
1035
+ starts ends with
1036
+ between and
1037
+ web route start
1038
+ database query insert update delete execute
1039
+ ask ocr using
1040
+ true false null
1041
+ try recover retry times wait
1042
+ accept uploads session sessions destroy
1043
+ cookie expires limit allow folder
1044
+ rate requests enable oauth google
1045
+ require api key matches nothing
1046
+ note
1047
+
1048
+ ---
1049
+
1050
+ This document is the single source of truth for PlainScript v0.1.7.
1051
+ Every compiler implementation must follow this specification.